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 |
|---|---|---|---|---|---|---|
source4code/repo | jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java | // Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public final class UnmarshalHelper {
private static final Logger LOGGER = LoggerFactory
.getLogger(UnmarshalHelper.class);
private UnmarshalHelper() {
// not called
}
| // Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public final class UnmarshalHelper {
private static final Logger LOGGER = LoggerFactory
.getLogger(UnmarshalHelper.class);
private UnmarshalHelper() {
// not called
}
| public static Car unmarshalError(File file) throws JAXBException { |
source4code/repo | jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/filter/LoginFilter.java | // Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/controller/UserManager.java
// @ManagedBean
// @SessionScoped
// public class UserManager {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UserManager.class);
//
// public static final String HOME_PAGE_REDIRECT = "/secured/home.xhtml?faces-redirect=true";
// public static final String LOGOUT_PAGE_REDIRECT = "/logout.xhtml?faces-redirect=true";
//
// private String userId;
// private String userPassword;
// private User currentUser;
//
// public String login() {
// // lookup the user based on user name and user password
// currentUser = find(userId, userPassword);
//
// if (currentUser != null) {
// LOGGER.info("login successful for '{}'", userId);
//
// return HOME_PAGE_REDIRECT;
// } else {
// LOGGER.info("login failed for '{}'", userId);
// FacesContext.getCurrentInstance().addMessage(
// null,
// new FacesMessage(FacesMessage.SEVERITY_WARN,
// "Login failed",
// "Invalid or unknown credentials."));
//
// return null;
// }
// }
//
// public String logout() {
// String identifier = userId;
//
// // invalidate the session
// LOGGER.debug("invalidating session for '{}'", identifier);
// FacesContext.getCurrentInstance().getExternalContext()
// .invalidateSession();
//
// LOGGER.info("logout successful for '{}'", identifier);
// return LOGOUT_PAGE_REDIRECT;
// }
//
// public boolean isLoggedIn() {
// return currentUser != null;
// }
//
// public String isLoggedInForwardHome() {
// if (isLoggedIn()) {
// return HOME_PAGE_REDIRECT;
// }
//
// return null;
// }
//
// private User find(String userId, String password) {
// User result = null;
//
// // code block to be replaced with actual retrieval of user
// if ("john.doe".equalsIgnoreCase(userId)
// && "1234".equals(password)) {
// result = new User(userId, "John", "Doe");
// }
//
// return result;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserPassword() {
// return userPassword;
// }
//
// public void setUserPassword(String userPassword) {
// this.userPassword = userPassword;
// }
//
// public User getCurrentUser() {
// return currentUser;
// }
//
// // do not provide a setter for currentUser!
// }
| import info.source4code.jsf.primefaces.controller.UserManager;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jsf.primefaces.filter;
public class LoginFilter implements Filter {
private static final Logger LOGGER = LoggerFactory
.getLogger(LoginFilter.class);
public static final String LOGIN_PAGE = "/login.xhtml";
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
// managed bean name is exactly the session attribute name | // Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/controller/UserManager.java
// @ManagedBean
// @SessionScoped
// public class UserManager {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UserManager.class);
//
// public static final String HOME_PAGE_REDIRECT = "/secured/home.xhtml?faces-redirect=true";
// public static final String LOGOUT_PAGE_REDIRECT = "/logout.xhtml?faces-redirect=true";
//
// private String userId;
// private String userPassword;
// private User currentUser;
//
// public String login() {
// // lookup the user based on user name and user password
// currentUser = find(userId, userPassword);
//
// if (currentUser != null) {
// LOGGER.info("login successful for '{}'", userId);
//
// return HOME_PAGE_REDIRECT;
// } else {
// LOGGER.info("login failed for '{}'", userId);
// FacesContext.getCurrentInstance().addMessage(
// null,
// new FacesMessage(FacesMessage.SEVERITY_WARN,
// "Login failed",
// "Invalid or unknown credentials."));
//
// return null;
// }
// }
//
// public String logout() {
// String identifier = userId;
//
// // invalidate the session
// LOGGER.debug("invalidating session for '{}'", identifier);
// FacesContext.getCurrentInstance().getExternalContext()
// .invalidateSession();
//
// LOGGER.info("logout successful for '{}'", identifier);
// return LOGOUT_PAGE_REDIRECT;
// }
//
// public boolean isLoggedIn() {
// return currentUser != null;
// }
//
// public String isLoggedInForwardHome() {
// if (isLoggedIn()) {
// return HOME_PAGE_REDIRECT;
// }
//
// return null;
// }
//
// private User find(String userId, String password) {
// User result = null;
//
// // code block to be replaced with actual retrieval of user
// if ("john.doe".equalsIgnoreCase(userId)
// && "1234".equals(password)) {
// result = new User(userId, "John", "Doe");
// }
//
// return result;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserPassword() {
// return userPassword;
// }
//
// public void setUserPassword(String userPassword) {
// this.userPassword = userPassword;
// }
//
// public User getCurrentUser() {
// return currentUser;
// }
//
// // do not provide a setter for currentUser!
// }
// Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/filter/LoginFilter.java
import info.source4code.jsf.primefaces.controller.UserManager;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jsf.primefaces.filter;
public class LoginFilter implements Filter {
private static final Logger LOGGER = LoggerFactory
.getLogger(LoginFilter.class);
public static final String LOGIN_PAGE = "/login.xhtml";
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
// managed bean name is exactly the session attribute name | UserManager userManager = (UserManager) httpServletRequest |
source4code/repo | jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/UnmarshalHelper.java | // Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import info.source4code.jaxb.model.Car;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public final class UnmarshalHelper {
private static final Logger LOGGER = LoggerFactory
.getLogger(UnmarshalHelper.class);
private UnmarshalHelper() {
// not called
}
| // Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
import info.source4code.jaxb.model.Car;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public final class UnmarshalHelper {
private static final Logger LOGGER = LoggerFactory
.getLogger(UnmarshalHelper.class);
private UnmarshalHelper() {
// not called
}
| public static Car unmarshal(String xml) throws JAXBException { |
source4code/repo | jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/controller/UserManager.java | // Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String userId;
// private String firstName;
// private String lastName;
//
// public User(String userId, String firstName, String lastName) {
// super();
//
// this.userId = userId;
// this.firstName = firstName;
// this.lastName = lastName;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getName() {
// return firstName + " " + lastName;
// }
//
// public String toString() {
// return "user[userId=" + userId + ", firstName=" + firstName
// + ", lastName=" + lastName + "]";
// }
// }
| import info.source4code.jsf.primefaces.model.User;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jsf.primefaces.controller;
@ManagedBean
@SessionScoped
public class UserManager {
private static final Logger LOGGER = LoggerFactory
.getLogger(UserManager.class);
public static final String HOME_PAGE_REDIRECT = "/secured/home.xhtml?faces-redirect=true";
public static final String LOGOUT_PAGE_REDIRECT = "/logout.xhtml?faces-redirect=true";
private String userId;
private String userPassword; | // Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String userId;
// private String firstName;
// private String lastName;
//
// public User(String userId, String firstName, String lastName) {
// super();
//
// this.userId = userId;
// this.firstName = firstName;
// this.lastName = lastName;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getName() {
// return firstName + " " + lastName;
// }
//
// public String toString() {
// return "user[userId=" + userId + ", firstName=" + firstName
// + ", lastName=" + lastName + "]";
// }
// }
// Path: jsf-jetty-primefaces-login-servlet-filter/src/main/java/info/source4code/jsf/primefaces/controller/UserManager.java
import info.source4code.jsf.primefaces.model.User;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jsf.primefaces.controller;
@ManagedBean
@SessionScoped
public class UserManager {
private static final Logger LOGGER = LoggerFactory
.getLogger(UserManager.class);
public static final String HOME_PAGE_REDIRECT = "/secured/home.xhtml?faces-redirect=true";
public static final String LOGOUT_PAGE_REDIRECT = "/logout.xhtml?faces-redirect=true";
private String userId;
private String userPassword; | private User currentUser; |
source4code/repo | jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/MarshalHelperTest.java | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/MarshalHelper.java
// public final class MarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(MarshalHelper.class);
//
// private MarshalHelper() {
// // not called
// }
//
// public static String marshalError(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// jaxbMarshaller.marshal(car, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
//
// public static String marshal(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// QName qName = new QName("info.source4code.jaxb.model", "car");
// JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);
//
// jaxbMarshaller.marshal(root, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.MarshalHelper;
import info.source4code.jaxb.model.Car;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public class MarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(MarshalHelperTest.class);
| // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/MarshalHelper.java
// public final class MarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(MarshalHelper.class);
//
// private MarshalHelper() {
// // not called
// }
//
// public static String marshalError(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// jaxbMarshaller.marshal(car, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
//
// public static String marshal(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// QName qName = new QName("info.source4code.jaxb.model", "car");
// JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);
//
// jaxbMarshaller.marshal(root, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/MarshalHelperTest.java
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.MarshalHelper;
import info.source4code.jaxb.model.Car;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public class MarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(MarshalHelperTest.class);
| public static Car car; |
source4code/repo | jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/MarshalHelperTest.java | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/MarshalHelper.java
// public final class MarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(MarshalHelper.class);
//
// private MarshalHelper() {
// // not called
// }
//
// public static String marshalError(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// jaxbMarshaller.marshal(car, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
//
// public static String marshal(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// QName qName = new QName("info.source4code.jaxb.model", "car");
// JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);
//
// jaxbMarshaller.marshal(root, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.MarshalHelper;
import info.source4code.jaxb.model.Car;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public class MarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(MarshalHelperTest.class);
public static Car car;
@BeforeClass
public static void setUpBeforeClass() {
car = new Car();
car.setMake("Passat");
car.setManufacturer("Volkswagen");
car.setId("ABC-123");
}
@Test
public void testMarshalError() throws JAXBException {
try { | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/MarshalHelper.java
// public final class MarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(MarshalHelper.class);
//
// private MarshalHelper() {
// // not called
// }
//
// public static String marshalError(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// jaxbMarshaller.marshal(car, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
//
// public static String marshal(Car car) throws JAXBException {
// StringWriter stringWriter = new StringWriter();
//
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // format the XML output
// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//
// QName qName = new QName("info.source4code.jaxb.model", "car");
// JAXBElement<Car> root = new JAXBElement<Car>(qName, Car.class, car);
//
// jaxbMarshaller.marshal(root, stringWriter);
//
// String result = stringWriter.toString();
// LOGGER.info(result);
// return result;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/MarshalHelperTest.java
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.MarshalHelper;
import info.source4code.jaxb.model.Car;
import javax.xml.bind.JAXBException;
import javax.xml.bind.MarshalException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public class MarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(MarshalHelperTest.class);
public static Car car;
@BeforeClass
public static void setUpBeforeClass() {
car = new Car();
car.setMake("Passat");
car.setManufacturer("Volkswagen");
car.setId("ABC-123");
}
@Test
public void testMarshalError() throws JAXBException {
try { | MarshalHelper.marshalError(car); |
source4code/repo | jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/UnmarshalHelperTest.java | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
// public final class UnmarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UnmarshalHelper.class);
//
// private UnmarshalHelper() {
// // not called
// }
//
// public static Car unmarshalError(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// Car car = (Car) jaxbUnmarshaller.unmarshal(file);
//
// LOGGER.info(car.toString());
// return car;
// }
//
// public static Car unmarshal(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// JAXBElement<Car> root = jaxbUnmarshaller.unmarshal(new StreamSource(
// file), Car.class);
// Car car = root.getValue();
//
// LOGGER.info(car.toString());
// return car;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.UnmarshalHelper;
import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public class UnmarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(UnmarshalHelperTest.class);
public static File file;
@BeforeClass
public static void setUpBeforeClass() {
file = new File("./src/test/resources/xml/golf.xml");
}
@Test
public void testUnmarshalError() {
try { | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
// public final class UnmarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UnmarshalHelper.class);
//
// private UnmarshalHelper() {
// // not called
// }
//
// public static Car unmarshalError(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// Car car = (Car) jaxbUnmarshaller.unmarshal(file);
//
// LOGGER.info(car.toString());
// return car;
// }
//
// public static Car unmarshal(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// JAXBElement<Car> root = jaxbUnmarshaller.unmarshal(new StreamSource(
// file), Car.class);
// Car car = root.getValue();
//
// LOGGER.info(car.toString());
// return car;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/UnmarshalHelperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.UnmarshalHelper;
import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public class UnmarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(UnmarshalHelperTest.class);
public static File file;
@BeforeClass
public static void setUpBeforeClass() {
file = new File("./src/test/resources/xml/golf.xml");
}
@Test
public void testUnmarshalError() {
try { | UnmarshalHelper.unmarshalError(file); |
source4code/repo | jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/UnmarshalHelperTest.java | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
// public final class UnmarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UnmarshalHelper.class);
//
// private UnmarshalHelper() {
// // not called
// }
//
// public static Car unmarshalError(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// Car car = (Car) jaxbUnmarshaller.unmarshal(file);
//
// LOGGER.info(car.toString());
// return car;
// }
//
// public static Car unmarshal(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// JAXBElement<Car> root = jaxbUnmarshaller.unmarshal(new StreamSource(
// file), Car.class);
// Car car = root.getValue();
//
// LOGGER.info(car.toString());
// return car;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.UnmarshalHelper;
import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package info.source4code.jaxb;
public class UnmarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(UnmarshalHelperTest.class);
public static File file;
@BeforeClass
public static void setUpBeforeClass() {
file = new File("./src/test/resources/xml/golf.xml");
}
@Test
public void testUnmarshalError() {
try {
UnmarshalHelper.unmarshalError(file);
fail("no exception thrown");
} catch (Exception e) {
logger.error("MarshalException", e);
assertTrue(e.toString().contains("unexpected element (uri:"));
}
}
@Test
public void testUnmarshal() throws JAXBException { | // Path: jaxb-missing-rootelement/src/main/java/info/source4code/jaxb/UnmarshalHelper.java
// public final class UnmarshalHelper {
//
// private static final Logger LOGGER = LoggerFactory
// .getLogger(UnmarshalHelper.class);
//
// private UnmarshalHelper() {
// // not called
// }
//
// public static Car unmarshalError(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// Car car = (Car) jaxbUnmarshaller.unmarshal(file);
//
// LOGGER.info(car.toString());
// return car;
// }
//
// public static Car unmarshal(File file) throws JAXBException {
// JAXBContext jaxbContext = JAXBContext.newInstance(Car.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//
// JAXBElement<Car> root = jaxbUnmarshaller.unmarshal(new StreamSource(
// file), Car.class);
// Car car = root.getValue();
//
// LOGGER.info(car.toString());
// return car;
// }
// }
//
// Path: jaxb-unmarshal-string/src/main/java/info/source4code/jaxb/model/Car.java
// @XmlRootElement(namespace = "info.source4code.jaxb.model", name = "Car")
// public class Car {
//
// private String make;
// private String manufacturer;
// private String id;
//
// public String getMake() {
// return make;
// }
//
// @XmlElement
// public void setMake(String make) {
// this.make = make;
// }
//
// public String getManufacturer() {
// return manufacturer;
// }
//
// @XmlElement
// public void setManufacturer(String manufacturer) {
// this.manufacturer = manufacturer;
// }
//
// public String getId() {
// return id;
// }
//
// @XmlAttribute
// public void setId(String id) {
// this.id = id;
// }
//
// public String toString() {
// return "Car [" + "make=" + make + ", manufacturer=" + manufacturer
// + ", id=" + id + "]";
// }
// }
// Path: jaxb-missing-rootelement/src/test/java/info/source4code/jaxb/UnmarshalHelperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import info.source4code.jaxb.UnmarshalHelper;
import info.source4code.jaxb.model.Car;
import java.io.File;
import javax.xml.bind.JAXBException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package info.source4code.jaxb;
public class UnmarshalHelperTest {
private static final Logger logger = LoggerFactory
.getLogger(UnmarshalHelperTest.class);
public static File file;
@BeforeClass
public static void setUpBeforeClass() {
file = new File("./src/test/resources/xml/golf.xml");
}
@Test
public void testUnmarshalError() {
try {
UnmarshalHelper.unmarshalError(file);
fail("no exception thrown");
} catch (Exception e) {
logger.error("MarshalException", e);
assertTrue(e.toString().contains("unexpected element (uri:"));
}
}
@Test
public void testUnmarshal() throws JAXBException { | Car car = UnmarshalHelper.unmarshal(file); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERBitString.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays; |
/**
* @return the value of the bit string as an int (truncating if necessary)
*/
public int intValue()
{
int value = 0;
for (int i = 0; i != data.length && i != 4; i++)
{
value |= (data[i] & 0xff) << (8 * i);
}
return value;
}
void encode(
DEROutputStream out)
throws IOException
{
byte[] bytes = new byte[getBytes().length + 1];
bytes[0] = (byte)getPadBits();
System.arraycopy(getBytes(), 0, bytes, 1, bytes.length - 1);
out.writeEncoded(BIT_STRING, bytes);
}
public int hashCode()
{ | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERBitString.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays;
/**
* @return the value of the bit string as an int (truncating if necessary)
*/
public int intValue()
{
int value = 0;
for (int i = 0; i != data.length && i != 4; i++)
{
value |= (data[i] & 0xff) << (8 * i);
}
return value;
}
void encode(
DEROutputStream out)
throws IOException
{
byte[] bytes = new byte[getBytes().length + 1];
bytes[0] = (byte)getPadBits();
System.arraycopy(getBytes(), 0, bytes, 1, bytes.length - 1);
out.writeEncoded(BIT_STRING, bytes);
}
public int hashCode()
{ | return padBits ^ Arrays.hashCode(data); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/androidTest/java/com/braintreegateway/encryption/util/AesDecrypter.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
| import com.braintree.org.bouncycastle.util.encoders.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | package com.braintreegateway.encryption.util;
public final class AesDecrypter {
private static int IV_LENGTH = 16;
public static byte[] decrypt(String data, byte[] aesKey) throws InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException,
NoSuchPaddingException { | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
// Path: BraintreeAndroidEncryption/src/androidTest/java/com/braintreegateway/encryption/util/AesDecrypter.java
import com.braintree.org.bouncycastle.util.encoders.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
package com.braintreegateway.encryption.util;
public final class AesDecrypter {
private static int IV_LENGTH = 16;
public static byte[] decrypt(String data, byte[] aesKey) throws InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException,
NoSuchPaddingException { | byte[] decodedData = Base64.decode(data); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DefiniteLengthInputStream.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
| import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams; | if (_remaining == 0)
{
return -1;
}
int toRead = Math.min(len, _remaining);
int numRead = _in.read(buf, off, toRead);
if (numRead < 0)
{
throw new EOFException("DEF length " + _originalLength + " object truncated by " + _remaining);
}
if ((_remaining -= numRead) == 0)
{
setParentEofDetect(true);
}
return numRead;
}
byte[] toByteArray()
throws IOException
{
if (_remaining == 0)
{
return EMPTY_BYTES;
}
byte[] bytes = new byte[_remaining]; | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DefiniteLengthInputStream.java
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams;
if (_remaining == 0)
{
return -1;
}
int toRead = Math.min(len, _remaining);
int numRead = _in.read(buf, off, toRead);
if (numRead < 0)
{
throw new EOFException("DEF length " + _originalLength + " object truncated by " + _remaining);
}
if ((_remaining -= numRead) == 0)
{
setParentEofDetect(true);
}
return numRead;
}
byte[] toByteArray()
throws IOException
{
if (_remaining == 0)
{
return EMPTY_BYTES;
}
byte[] bytes = new byte[_remaining]; | if ((_remaining -= Streams.readFully(_in, bytes)) != 0) |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintreegateway/encryption/Aes.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
| import com.braintree.org.bouncycastle.util.encoders.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | package com.braintreegateway.encryption;
public final class Aes {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
public static final int KEY_LENGTH = 32;
public static final int IV_LENGTH = 16;
public static String encrypt(String data, byte[] aesKey, byte[] iv) throws BraintreeEncryptionException {
SecretKeySpec key = new SecretKeySpec(aesKey, ALGORITHM);
Cipher cipher = aesCipher();
try {
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParamSpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
byte[] buffer = Arrays.copyOf(iv, iv.length + encryptedBytes.length);
System.arraycopy(encryptedBytes, 0, buffer, iv.length, encryptedBytes.length); | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintreegateway/encryption/Aes.java
import com.braintree.org.bouncycastle.util.encoders.Base64;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
package com.braintreegateway.encryption;
public final class Aes {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
public static final int KEY_LENGTH = 32;
public static final int IV_LENGTH = 16;
public static String encrypt(String data, byte[] aesKey, byte[] iv) throws BraintreeEncryptionException {
SecretKeySpec key = new SecretKeySpec(aesKey, ALGORITHM);
Cipher cipher = aesCipher();
try {
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParamSpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
byte[] buffer = Arrays.copyOf(iv, iv.length + encryptedBytes.length);
System.arraycopy(encryptedBytes, 0, buffer, iv.length, encryptedBytes.length); | return new String(Base64.encode(buffer)); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERInteger.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
| import java.io.IOException;
import java.math.BigInteger;
import com.braintree.org.bouncycastle.util.Arrays; |
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(INTEGER, bytes);
}
public int hashCode()
{
int value = 0;
for (int i = 0; i != bytes.length; i++)
{
value ^= (bytes[i] & 0xff) << (i % 4);
}
return value;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DERInteger))
{
return false;
}
DERInteger other = (DERInteger)o;
| // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERInteger.java
import java.io.IOException;
import java.math.BigInteger;
import com.braintree.org.bouncycastle.util.Arrays;
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(INTEGER, bytes);
}
public int hashCode()
{
int value = 0;
for (int i = 0; i != bytes.length; i++)
{
value ^= (bytes[i] & 0xff) << (i % 4);
}
return value;
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DERInteger))
{
return false;
}
DERInteger other = (DERInteger)o;
| return Arrays.areEqual(bytes, other.bytes); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/androidTest/java/com/braintreegateway/encryption/util/RsaDecrypter.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
| import static javax.crypto.Cipher.getInstance;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.braintree.org.bouncycastle.util.encoders.Base64; | package com.braintreegateway.encryption.util;
public final class RsaDecrypter {
public static byte[] decrypt(String encryptedData, String privateKey) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchAlgorithmException,
InvalidKeyException,
IllegalBlockSizeException,
NoSuchProviderException,
NoSuchPaddingException,
BadPaddingException { | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/encoders/Base64.java
// public class Base64
// {
// private static final Encoder encoder = new Base64Encoder();
//
// /**
// * encode the input data producing a base 64 encoded byte array.
// *
// * @return a byte array containing the base 64 encoded data.
// */
// public static byte[] encode(
// byte[] data)
// {
// int len = (data.length + 2) / 3 * 4;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.encode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception encoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, 0, data.length, out);
// }
//
// /**
// * Encode the byte data to base 64 writing it to the given output stream.
// *
// * @return the number of bytes produced.
// */
// public static int encode(
// byte[] data,
// int off,
// int length,
// OutputStream out)
// throws IOException
// {
// return encoder.encode(data, off, length, out);
// }
//
// /**
// * decode the base 64 encoded input data. It is assumed the input data is valid.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// byte[] data)
// {
// int len = data.length / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, 0, data.length, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data - whitespace will be ignored.
// *
// * @return a byte array representing the decoded data.
// */
// public static byte[] decode(
// String data)
// {
// int len = data.length() / 4 * 3;
// ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
//
// try
// {
// encoder.decode(data, bOut);
// }
// catch (IOException e)
// {
// throw new RuntimeException("exception decoding base64 string: " + e);
// }
//
// return bOut.toByteArray();
// }
//
// /**
// * decode the base 64 encoded String data writing it to the given output stream,
// * whitespace characters will be ignored.
// *
// * @return the number of bytes produced.
// */
// public static int decode(
// String data,
// OutputStream out)
// throws IOException
// {
// return encoder.decode(data, out);
// }
// }
// Path: BraintreeAndroidEncryption/src/androidTest/java/com/braintreegateway/encryption/util/RsaDecrypter.java
import static javax.crypto.Cipher.getInstance;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.braintree.org.bouncycastle.util.encoders.Base64;
package com.braintreegateway.encryption.util;
public final class RsaDecrypter {
public static byte[] decrypt(String encryptedData, String privateKey) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchAlgorithmException,
InvalidKeyException,
IllegalBlockSizeException,
NoSuchProviderException,
NoSuchPaddingException,
BadPaddingException { | byte[] keyBytes = Base64.decode(privateKey); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DEREnumerated.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
| import java.io.IOException;
import java.math.BigInteger;
import com.braintree.org.bouncycastle.util.Arrays; | }
public DEREnumerated(
byte[] bytes)
{
this.bytes = bytes;
}
public BigInteger getValue()
{
return new BigInteger(bytes);
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(ENUMERATED, bytes);
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DEREnumerated))
{
return false;
}
DEREnumerated other = (DEREnumerated)o;
| // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DEREnumerated.java
import java.io.IOException;
import java.math.BigInteger;
import com.braintree.org.bouncycastle.util.Arrays;
}
public DEREnumerated(
byte[] bytes)
{
this.bytes = bytes;
}
public BigInteger getValue()
{
return new BigInteger(bytes);
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(ENUMERATED, bytes);
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DEREnumerated))
{
return false;
}
DEREnumerated other = (DEREnumerated)o;
| return Arrays.areEqual(this.bytes, other.bytes); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/ASN1InputStream.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams; | }
/**
* Create an ASN1InputStream where no DER object will be longer than limit, and constructed
* objects such as sequences will be parsed lazily.
*
* @param input stream containing ASN.1 encoded data.
* @param limit maximum size of a DER encoded object.
* @param lazyEvaluate true if parsing inside constructed objects can be delayed.
*/
public ASN1InputStream(
InputStream input,
int limit,
boolean lazyEvaluate)
{
super(input);
this.limit = limit;
this.lazyEvaluate = lazyEvaluate;
}
protected int readLength()
throws IOException
{
return readLength(this, limit);
}
protected void readFully(
byte[] bytes)
throws IOException
{ | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/ASN1InputStream.java
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams;
}
/**
* Create an ASN1InputStream where no DER object will be longer than limit, and constructed
* objects such as sequences will be parsed lazily.
*
* @param input stream containing ASN.1 encoded data.
* @param limit maximum size of a DER encoded object.
* @param lazyEvaluate true if parsing inside constructed objects can be delayed.
*/
public ASN1InputStream(
InputStream input,
int limit,
boolean lazyEvaluate)
{
super(input);
this.limit = limit;
this.lazyEvaluate = lazyEvaluate;
}
protected int readLength()
throws IOException
{
return readLength(this, limit);
}
protected void readFully(
byte[] bytes)
throws IOException
{ | if (Streams.readFully(this, bytes) != bytes.length) |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERUnknownTag.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
| import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays; |
public int getTag()
{
return tag;
}
public byte[] getData()
{
return data;
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(isConstructed ? DERTags.CONSTRUCTED : 0, tag, data);
}
public boolean equals(
Object o)
{
if (!(o instanceof DERUnknownTag))
{
return false;
}
DERUnknownTag other = (DERUnknownTag)o;
return isConstructed == other.isConstructed
&& tag == other.tag | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERUnknownTag.java
import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays;
public int getTag()
{
return tag;
}
public byte[] getData()
{
return data;
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(isConstructed ? DERTags.CONSTRUCTED : 0, tag, data);
}
public boolean equals(
Object o)
{
if (!(o instanceof DERUnknownTag))
{
return false;
}
DERUnknownTag other = (DERUnknownTag)o;
return isConstructed == other.isConstructed
&& tag == other.tag | && Arrays.areEqual(data, other.data); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/BEROctetStringParser.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams; | package com.braintree.org.bouncycastle.asn1;
public class BEROctetStringParser
implements ASN1OctetStringParser
{
private ASN1StreamParser _parser;
BEROctetStringParser(
ASN1StreamParser parser)
{
_parser = parser;
}
public InputStream getOctetStream()
{
return new ConstructedOctetStream(_parser);
}
public DERObject getLoadedObject()
throws IOException
{ | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/io/Streams.java
// public final class Streams
// {
// private static int BUFFER_SIZE = 512;
//
// public static void drain(InputStream inStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// while (inStr.read(bs, 0, bs.length) >= 0)
// {
// }
// }
//
// public static byte[] readAll(InputStream inStr)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAll(inStr, buf);
// return buf.toByteArray();
// }
//
// public static byte[] readAllLimited(InputStream inStr, int limit)
// throws IOException
// {
// ByteArrayOutputStream buf = new ByteArrayOutputStream();
// pipeAllLimited(inStr, limit, buf);
// return buf.toByteArray();
// }
//
// public static int readFully(InputStream inStr, byte[] buf)
// throws IOException
// {
// return readFully(inStr, buf, 0, buf.length);
// }
//
// public static int readFully(InputStream inStr, byte[] buf, int off, int len)
// throws IOException
// {
// int totalRead = 0;
// while (totalRead < len)
// {
// int numRead = inStr.read(buf, off + totalRead, len - totalRead);
// if (numRead < 0)
// {
// break;
// }
// totalRead += numRead;
// }
// return totalRead;
// }
//
// public static void pipeAll(InputStream inStr, OutputStream outStr)
// throws IOException
// {
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// outStr.write(bs, 0, numRead);
// }
// }
//
// public static long pipeAllLimited(InputStream inStr, long limit, OutputStream outStr)
// throws IOException
// {
// long total = 0;
// byte[] bs = new byte[BUFFER_SIZE];
// int numRead;
// while ((numRead = inStr.read(bs, 0, bs.length)) >= 0)
// {
// total += numRead;
// if (total > limit)
// {
// throw new StreamOverflowException("Data Overflow");
// }
// outStr.write(bs, 0, numRead);
// }
// return total;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/BEROctetStringParser.java
import java.io.IOException;
import java.io.InputStream;
import com.braintree.org.bouncycastle.util.io.Streams;
package com.braintree.org.bouncycastle.asn1;
public class BEROctetStringParser
implements ASN1OctetStringParser
{
private ASN1StreamParser _parser;
BEROctetStringParser(
ASN1StreamParser parser)
{
_parser = parser;
}
public InputStream getOctetStream()
{
return new ConstructedOctetStream(_parser);
}
public DERObject getLoadedObject()
throws IOException
{ | return new BERConstructedOctetString(Streams.readAll(getOctetStream())); |
braintree/braintree_android_encryption | BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERApplicationSpecific.java | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays; |
return new ASN1InputStream(tmp).readObject();
}
/* (non-Javadoc)
* @see org.bouncycastle.asn1.DERObject#encode(org.bouncycastle.asn1.DEROutputStream)
*/
void encode(DEROutputStream out) throws IOException
{
int classBits = DERTags.APPLICATION;
if (isConstructed)
{
classBits |= DERTags.CONSTRUCTED;
}
out.writeEncoded(classBits, tag, octets);
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DERApplicationSpecific))
{
return false;
}
DERApplicationSpecific other = (DERApplicationSpecific)o;
return isConstructed == other.isConstructed
&& tag == other.tag | // Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/util/Arrays.java
// public final class Arrays
// {
// private Arrays()
// {
// // static class, hide constructor
// }
//
// public static boolean areEqual(
// boolean[] a,
// boolean[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// char[] a,
// char[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static boolean areEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * A constant time equals comparison - does not terminate early if
// * test will fail.
// *
// * @param a first array
// * @param b second array
// * @return true if arrays equal, false otherwise.
// */
// public static boolean constantTimeAreEqual(
// byte[] a,
// byte[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// int nonEqual = 0;
//
// for (int i = 0; i != a.length; i++)
// {
// nonEqual |= (a[i] ^ b[i]);
// }
//
// return nonEqual == 0;
// }
//
// public static boolean areEqual(
// int[] a,
// int[] b)
// {
// if (a == b)
// {
// return true;
// }
//
// if (a == null || b == null)
// {
// return false;
// }
//
// if (a.length != b.length)
// {
// return false;
// }
//
// for (int i = 0; i != a.length; i++)
// {
// if (a[i] != b[i])
// {
// return false;
// }
// }
//
// return true;
// }
//
// public static void fill(
// byte[] array,
// byte value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// long[] array,
// long value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static void fill(
// short[] array,
// short value)
// {
// for (int i = 0; i < array.length; i++)
// {
// array[i] = value;
// }
// }
//
// public static int hashCode(byte[] data)
// {
// if (data == null)
// {
// return 0;
// }
//
// int i = data.length;
// int hc = i + 1;
//
// while (--i >= 0)
// {
// hc *= 257;
// hc ^= data[i];
// }
//
// return hc;
// }
//
// public static byte[] clone(byte[] data)
// {
// if (data == null)
// {
// return null;
// }
// byte[] copy = new byte[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
//
// public static int[] clone(int[] data)
// {
// if (data == null)
// {
// return null;
// }
// int[] copy = new int[data.length];
//
// System.arraycopy(data, 0, copy, 0, data.length);
//
// return copy;
// }
// }
// Path: BraintreeAndroidEncryption/src/main/java/com/braintree/org/bouncycastle/asn1/DERApplicationSpecific.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.braintree.org.bouncycastle.util.Arrays;
return new ASN1InputStream(tmp).readObject();
}
/* (non-Javadoc)
* @see org.bouncycastle.asn1.DERObject#encode(org.bouncycastle.asn1.DEROutputStream)
*/
void encode(DEROutputStream out) throws IOException
{
int classBits = DERTags.APPLICATION;
if (isConstructed)
{
classBits |= DERTags.CONSTRUCTED;
}
out.writeEncoded(classBits, tag, octets);
}
boolean asn1Equals(
DERObject o)
{
if (!(o instanceof DERApplicationSpecific))
{
return false;
}
DERApplicationSpecific other = (DERApplicationSpecific)o;
return isConstructed == other.isConstructed
&& tag == other.tag | && Arrays.areEqual(octets, other.octets); |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/world/environment/EnvironmentData.java | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
| import java.util.ArrayList;
import java.util.HashMap;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.logic.TheHuntRenderer;
import android.graphics.PointF;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager; | tiles.add(mTiles[j][i]);
}
}
// Log.i(TAG, "Tiles to add " + tiles.size());
return tiles;
}
// public FloatingObject removeFood(float x, float y, float radius) {
// for (FloatingObject fo: mFloatingObjects) {
// if (fo.getType().compareTo(Type.FOOD_GM) != 0) continue;
// float foX = fo.getX(), foY = fo.getY();
// if (D3Maths.circleContains(x, y, radius, foX, foY)) {//Prey.EAT_FOOD_RADIUS
// fo.clearGraphic();
// mFloatingObjects.remove(fo);
// return fo;
// }
// }
// return null;
// }
public void logFloatingObjects() {
String log = "Floating objects log: ";
for (FloatingObject fo: mFloatingObjects) {
log += fo.getType() + " " + fo.getX() + " " + fo.getY() + " ";
}
Log.v(TAG, log);
log = "Floating objects to add log: ";
for (FloatingObject fo: mFloatingObjectsToAdd) {
log += fo.getType() + " " + fo.getX() + " " + fo.getY() + " "; | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
// Path: TheHunt/src/com/primalpond/hunt/world/environment/EnvironmentData.java
import java.util.ArrayList;
import java.util.HashMap;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.logic.TheHuntRenderer;
import android.graphics.PointF;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager;
tiles.add(mTiles[j][i]);
}
}
// Log.i(TAG, "Tiles to add " + tiles.size());
return tiles;
}
// public FloatingObject removeFood(float x, float y, float radius) {
// for (FloatingObject fo: mFloatingObjects) {
// if (fo.getType().compareTo(Type.FOOD_GM) != 0) continue;
// float foX = fo.getX(), foY = fo.getY();
// if (D3Maths.circleContains(x, y, radius, foX, foY)) {//Prey.EAT_FOOD_RADIUS
// fo.clearGraphic();
// mFloatingObjects.remove(fo);
// return fo;
// }
// }
// return null;
// }
public void logFloatingObjects() {
String log = "Floating objects log: ";
for (FloatingObject fo: mFloatingObjects) {
log += fo.getType() + " " + fo.getX() + " " + fo.getY() + " ";
}
Log.v(TAG, log);
log = "Floating objects to add log: ";
for (FloatingObject fo: mFloatingObjectsToAdd) {
log += fo.getType() + " " + fo.getX() + " " + fo.getY() + " "; | if (fo.getType().equals(Type.ALGAE)) { |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/FoodTrainingDemonstrator.java | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
| import java.util.ArrayList;
import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.world.environment.FloatingObject;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.environment.NAlgae;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager; | package com.primalpond.hunt;
public class FoodTrainingDemonstrator extends Demonstrator {
private static final float PREY_FROM_FOOD_TARGET = 0.2f;
private static final String TAG = "FoodTrainingDemonstrator";
private NAlgae mAlgae;
private boolean mPutFood;
private boolean mWaitingForPrey;
private PointF mPlaceFoodAt;
private boolean initialWait; | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
// Path: TheHunt/src/com/primalpond/hunt/FoodTrainingDemonstrator.java
import java.util.ArrayList;
import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.world.environment.FloatingObject;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.environment.NAlgae;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager;
package com.primalpond.hunt;
public class FoodTrainingDemonstrator extends Demonstrator {
private static final float PREY_FROM_FOOD_TARGET = 0.2f;
private static final String TAG = "FoodTrainingDemonstrator";
private NAlgae mAlgae;
private boolean mPutFood;
private boolean mWaitingForPrey;
private PointF mPlaceFoodAt;
private boolean initialWait; | private FloatingObject mFoodFo; |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/FoodTrainingDemonstrator.java | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
| import java.util.ArrayList;
import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.world.environment.FloatingObject;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.environment.NAlgae;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager; | @Override
public void update() {
if (mIsFinished) {
if (mRenderer.mPrey.getCaught()) {
mIsSatisfied = true;
}
}
else if (!initialWait) {
if (countFinished()) {
initialWait = true;
clearCount();
}
else if (!counting()) {
countForSec(2);
}
}
else if (mAlgae != null) {
if (!mPutFood) {
if (mPutFoodTouchWait) {
if (countFinished()) {
releaseTouch(mPlaceFoodAt);
mPutFoodTouchWait = false;
mWaitingForFoodToAppear = true;
clearCount();
}
}
else if (mWaitingForFoodToAppear) {
ArrayList<FloatingObject> floatingObjects = mRenderer.mEnv.seeObjects(0, 0, 2);
for (FloatingObject fo: floatingObjects) { | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public enum Type {
// FOOD_GM, ALGAE;
// }
// Path: TheHunt/src/com/primalpond/hunt/FoodTrainingDemonstrator.java
import java.util.ArrayList;
import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.world.environment.FloatingObject;
import com.primalpond.hunt.world.environment.FloatingObject.Type;
import com.primalpond.hunt.world.environment.NAlgae;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.SpriteManager;
@Override
public void update() {
if (mIsFinished) {
if (mRenderer.mPrey.getCaught()) {
mIsSatisfied = true;
}
}
else if (!initialWait) {
if (countFinished()) {
initialWait = true;
clearCount();
}
else if (!counting()) {
countForSec(2);
}
}
else if (mAlgae != null) {
if (!mPutFood) {
if (mPutFoodTouchWait) {
if (countFinished()) {
releaseTouch(mPlaceFoodAt);
mPutFoodTouchWait = false;
mWaitingForFoodToAppear = true;
clearCount();
}
}
else if (mWaitingForFoodToAppear) {
ArrayList<FloatingObject> floatingObjects = mRenderer.mEnv.seeObjects(0, 0, 2);
for (FloatingObject fo: floatingObjects) { | if (fo.getType() == Type.FOOD_GM) { |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/d3kod/graphics/sprite/shapes/D3Shape.java | // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: TheHunt/src/d3kod/graphics/shader/programs/Program.java
// public abstract class Program {
//
// private int programHandle;
// private int vertexShaderHandle;
// private int fragmentShaderHandle;
// private boolean mInitialized;
//
// public Program() {
// mInitialized = false;
// }
//
// public void init() {
// init(null, null, null);
// }
//
// public void init(String vertexShaderCode, String fragmentShaderCode, AttribVariable[] programVariables) {
// vertexShaderHandle = Utilities.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
// fragmentShaderHandle = Utilities.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// programHandle = Utilities.createProgram(
// vertexShaderHandle, fragmentShaderHandle, programVariables);
//
// mInitialized = true;
// }
//
// public int getHandle() {
// return programHandle;
// }
//
// public void delete() {
// GLES20.glDeleteShader(vertexShaderHandle);
// GLES20.glDeleteShader(fragmentShaderHandle);
// GLES20.glDeleteProgram(programHandle);
// mInitialized = false;
// }
//
// public boolean initialized() {
// return mInitialized;
// }
//
// }
| import java.nio.FloatBuffer;
import java.util.Arrays;
import android.graphics.PointF;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.extra.Utilities;
import d3kod.graphics.shader.programs.AttribVariable;
import d3kod.graphics.shader.programs.Program;
import d3kod.graphics.sprite.SpriteManager; | package d3kod.graphics.sprite.shapes;
abstract public class D3Shape {
private int VERTICES_NUM;
protected static final int STRIDE_BYTES = SpriteManager.COORDS_PER_VERTEX * Utilities.BYTES_PER_FLOAT;
private static final String TAG = "D3Shape";
private float[] mColor = new float[4]; | // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: TheHunt/src/d3kod/graphics/shader/programs/Program.java
// public abstract class Program {
//
// private int programHandle;
// private int vertexShaderHandle;
// private int fragmentShaderHandle;
// private boolean mInitialized;
//
// public Program() {
// mInitialized = false;
// }
//
// public void init() {
// init(null, null, null);
// }
//
// public void init(String vertexShaderCode, String fragmentShaderCode, AttribVariable[] programVariables) {
// vertexShaderHandle = Utilities.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
// fragmentShaderHandle = Utilities.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// programHandle = Utilities.createProgram(
// vertexShaderHandle, fragmentShaderHandle, programVariables);
//
// mInitialized = true;
// }
//
// public int getHandle() {
// return programHandle;
// }
//
// public void delete() {
// GLES20.glDeleteShader(vertexShaderHandle);
// GLES20.glDeleteShader(fragmentShaderHandle);
// GLES20.glDeleteProgram(programHandle);
// mInitialized = false;
// }
//
// public boolean initialized() {
// return mInitialized;
// }
//
// }
// Path: TheHunt/src/d3kod/graphics/sprite/shapes/D3Shape.java
import java.nio.FloatBuffer;
import java.util.Arrays;
import android.graphics.PointF;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.extra.Utilities;
import d3kod.graphics.shader.programs.AttribVariable;
import d3kod.graphics.shader.programs.Program;
import d3kod.graphics.sprite.SpriteManager;
package d3kod.graphics.sprite.shapes;
abstract public class D3Shape {
private int VERTICES_NUM;
protected static final int STRIDE_BYTES = SpriteManager.COORDS_PER_VERTEX * Utilities.BYTES_PER_FLOAT;
private static final String TAG = "D3Shape";
private float[] mColor = new float[4]; | private Program mProgram; |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/d3kod/graphics/sprite/shapes/D3Shape.java | // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: TheHunt/src/d3kod/graphics/shader/programs/Program.java
// public abstract class Program {
//
// private int programHandle;
// private int vertexShaderHandle;
// private int fragmentShaderHandle;
// private boolean mInitialized;
//
// public Program() {
// mInitialized = false;
// }
//
// public void init() {
// init(null, null, null);
// }
//
// public void init(String vertexShaderCode, String fragmentShaderCode, AttribVariable[] programVariables) {
// vertexShaderHandle = Utilities.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
// fragmentShaderHandle = Utilities.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// programHandle = Utilities.createProgram(
// vertexShaderHandle, fragmentShaderHandle, programVariables);
//
// mInitialized = true;
// }
//
// public int getHandle() {
// return programHandle;
// }
//
// public void delete() {
// GLES20.glDeleteShader(vertexShaderHandle);
// GLES20.glDeleteShader(fragmentShaderHandle);
// GLES20.glDeleteProgram(programHandle);
// mInitialized = false;
// }
//
// public boolean initialized() {
// return mInitialized;
// }
//
// }
| import java.nio.FloatBuffer;
import java.util.Arrays;
import android.graphics.PointF;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.extra.Utilities;
import d3kod.graphics.shader.programs.AttribVariable;
import d3kod.graphics.shader.programs.Program;
import d3kod.graphics.sprite.SpriteManager; | private float[] mVMatrix = new float[16];
private FloatBuffer vertexBuffer;
private int drawType;
private float[] mMMatrix;
private float[] mCenter;
private float[] mCenterDefault;
private float mVelocityY;
private float mVelocityX;
private float mScale;
private float mAngle;
private static final float MIN_ALPHA = 0.1f;
protected D3Shape(FloatBuffer vertBuffer, float[] colorData, int drType, Program program) {
this();
setColor(colorData);
setDrawType(drType);
setVertexBuffer(vertBuffer); //TODO: make this the default constructor without the vertBuffer argument and ssetVertexBuffer abstract
setProgram(program);
mAngle = 0;
}
protected D3Shape() {
mMMatrix = new float[16];
mCenterDefault = new float[] {0.0f, 0.0f, 0.0f, 1.0f};
mCenter = new float[4];
mVelocityX = mVelocityY = 0;
Matrix.setIdentityM(getMMatrix(), 0);
mScale = 1; | // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: TheHunt/src/d3kod/graphics/shader/programs/Program.java
// public abstract class Program {
//
// private int programHandle;
// private int vertexShaderHandle;
// private int fragmentShaderHandle;
// private boolean mInitialized;
//
// public Program() {
// mInitialized = false;
// }
//
// public void init() {
// init(null, null, null);
// }
//
// public void init(String vertexShaderCode, String fragmentShaderCode, AttribVariable[] programVariables) {
// vertexShaderHandle = Utilities.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
// fragmentShaderHandle = Utilities.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// programHandle = Utilities.createProgram(
// vertexShaderHandle, fragmentShaderHandle, programVariables);
//
// mInitialized = true;
// }
//
// public int getHandle() {
// return programHandle;
// }
//
// public void delete() {
// GLES20.glDeleteShader(vertexShaderHandle);
// GLES20.glDeleteShader(fragmentShaderHandle);
// GLES20.glDeleteProgram(programHandle);
// mInitialized = false;
// }
//
// public boolean initialized() {
// return mInitialized;
// }
//
// }
// Path: TheHunt/src/d3kod/graphics/sprite/shapes/D3Shape.java
import java.nio.FloatBuffer;
import java.util.Arrays;
import android.graphics.PointF;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.extra.Utilities;
import d3kod.graphics.shader.programs.AttribVariable;
import d3kod.graphics.shader.programs.Program;
import d3kod.graphics.sprite.SpriteManager;
private float[] mVMatrix = new float[16];
private FloatBuffer vertexBuffer;
private int drawType;
private float[] mMMatrix;
private float[] mCenter;
private float[] mCenterDefault;
private float mVelocityY;
private float mVelocityX;
private float mScale;
private float mAngle;
private static final float MIN_ALPHA = 0.1f;
protected D3Shape(FloatBuffer vertBuffer, float[] colorData, int drType, Program program) {
this();
setColor(colorData);
setDrawType(drType);
setVertexBuffer(vertBuffer); //TODO: make this the default constructor without the vertBuffer argument and ssetVertexBuffer abstract
setProgram(program);
mAngle = 0;
}
protected D3Shape() {
mMMatrix = new float[16];
mCenterDefault = new float[] {0.0f, 0.0f, 0.0f, 1.0f};
mCenter = new float[4];
mVelocityX = mVelocityY = 0;
Matrix.setIdentityM(getMMatrix(), 0);
mScale = 1; | mPositionHandle = AttribVariable.A_Position.getHandle(); |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/world/tools/D3GestureActionNet.java | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
| import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.world.environment.Environment;
import com.primalpond.hunt.world.environment.FloatingObject;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.shapes.D3Circle; | setPosition(x, y);
setScale(START_RADIUS/radius);
}
public void grow() {
super.grow(mGrowSpeed);
}
@Override
public void draw(float[] mVMatrix, float[] mProjMatrix) {
if (getScale() >= 1) {
fade(FADE_SPEED);
}
super.draw(mVMatrix, mProjMatrix);
}
public boolean isFinished() {
return mFinished;
}
public void update() {
if (getScale() < 1) {
grow();
}
else {
Agent prey = mEnv.getPrey();
if (prey != null && !prey.getCaught() && !prey.isHidden() && contains(prey.getPosition())) {
Log.v(TAG, "I caught the prey!");
prey.setCaught(true);
} | // Path: TheHunt/src/com/primalpond/hunt/world/environment/FloatingObject.java
// public abstract class FloatingObject extends D3Sprite implements JSONable {
//
// public enum Type {
// FOOD_GM, ALGAE;
// }
//
// protected static final String KEY_POS_X = "pos_x";
// protected static final String KEY_POS_Y = "pos_y";
// protected static final String KEY_VX = "vx";
// protected static final String KEY_VY = "vy";
//
// private static final String TAG = "FloatingObject";
// public static final String KEY_TYPE = "type";
//
// Type mType;
//
// private boolean mRemove;
// private ArrayList<Tile> mTiles;
// private boolean mChanged;
//
// public FloatingObject(float x, float y, Type type, SpriteManager d3gles20) {
// super(new PointF(x, y), d3gles20);
// mType = type;
// mRemove = false;
// }
//
// public void update() {
// if (D3Maths.compareFloats(0, getVX()) != 0
// && D3Maths.compareFloats(0, getVY()) != 0) {
// mChanged = true;
// }
// applyFriction();
// super.update();
// }
//
// public void applyFriction() {}
//
// public Type getType() {
// return mType;
// }
//
// public boolean toRemove() {
// return mRemove;
// }
//
// public void setToRemove() {
// mRemove = true;
// }
//
// public JSONObject toJSON() throws JSONException {
// JSONObject jsonObject = new JSONObject();
// PointF pos = getPosition();
// jsonObject.put(KEY_POS_X, pos.x);
// jsonObject.put(KEY_POS_Y, pos.y);
// jsonObject.put(KEY_VX, getVX());
// jsonObject.put(KEY_VY, getVY());
// jsonObject.put(KEY_TYPE, mType);
// return jsonObject;
// }
//
// public void setTiles(ArrayList<Tile> tiles) {
// mTiles = tiles;
// }
//
// public boolean hasMoved() {
// if (mChanged) {
// mChanged = false;
// return true;
// }
// return false;
// }
//
// public void setChanged() {
// mChanged = true;
// }
//
// public ArrayList<Tile> getTiles() {
// return mTiles;
// }
//
// // public float getRadius() {
// // return mGraphic.getRadius();
// // }
// }
// Path: TheHunt/src/com/primalpond/hunt/world/tools/D3GestureActionNet.java
import android.graphics.PointF;
import android.util.Log;
import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.world.environment.Environment;
import com.primalpond.hunt.world.environment.FloatingObject;
import d3kod.graphics.extra.D3Maths;
import d3kod.graphics.sprite.shapes.D3Circle;
setPosition(x, y);
setScale(START_RADIUS/radius);
}
public void grow() {
super.grow(mGrowSpeed);
}
@Override
public void draw(float[] mVMatrix, float[] mProjMatrix) {
if (getScale() >= 1) {
fade(FADE_SPEED);
}
super.draw(mVMatrix, mProjMatrix);
}
public boolean isFinished() {
return mFinished;
}
public void update() {
if (getScale() < 1) {
grow();
}
else {
Agent prey = mEnv.getPrey();
if (prey != null && !prey.getCaught() && !prey.isHidden() && contains(prey.getPosition())) {
Log.v(TAG, "I caught the prey!");
prey.setCaught(true);
} | for (FloatingObject fo:mEnv.seeObjects(getCenterX(), getCenterY(), getRadius())) { |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/d3kod/graphics/text/Vertices.java | // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
| import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import android.opengl.GLES20;
import d3kod.graphics.shader.programs.AttribVariable;
| private int mMVPIndexHandle;
//--Constructor--//
// D: create the vertices/indices as specified (for 2d/3d)
// A: maxVertices - maximum vertices allowed in buffer
// maxIndices - maximum indices allowed in buffer
public Vertices(int maxVertices, int maxIndices) {
// this.gl = gl; // Save GL Instance
this.positionCnt = POSITION_CNT_2D; // Set Position Component Count
this.vertexStride = this.positionCnt + TEXCOORD_CNT + MVP_MATRIX_INDEX_CNT; // Calculate Vertex Stride
this.vertexSize = this.vertexStride * 4; // Calculate Vertex Byte Size
ByteBuffer buffer = ByteBuffer.allocateDirect( maxVertices * vertexSize ); // Allocate Buffer for Vertices (Max)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.vertices = buffer.asIntBuffer(); // Save Vertex Buffer
if ( maxIndices > 0 ) { // IF Indices Required
buffer = ByteBuffer.allocateDirect( maxIndices * INDEX_SIZE ); // Allocate Buffer for Indices (MAX)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.indices = buffer.asShortBuffer(); // Save Index Buffer
}
else // ELSE Indices Not Required
indices = null; // No Index Buffer
numVertices = 0; // Zero Vertices in Buffer
numIndices = 0; // Zero Indices in Buffer
this.tmpBuffer = new int[maxVertices * vertexSize / 4]; // Create Temp Buffer
// initialize the shader attribute handles
| // Path: TheHunt/src/d3kod/graphics/shader/programs/AttribVariable.java
// public enum AttribVariable {
// A_Position(1, "a_Position"),
// A_TexCoordinate(2, "a_TexCoordinate"),
// A_MVPMatrixIndex(3, "a_MVPMatrixIndex");
//
// private int mHandle;
// private String mName;
//
// private AttribVariable(int handle, String name) {
// mHandle = handle;
// mName = name;
// }
//
// public int getHandle() {
// return mHandle;
// }
//
// public String getName() {
// return mName;
// }
// }
// Path: TheHunt/src/d3kod/graphics/text/Vertices.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import android.opengl.GLES20;
import d3kod.graphics.shader.programs.AttribVariable;
private int mMVPIndexHandle;
//--Constructor--//
// D: create the vertices/indices as specified (for 2d/3d)
// A: maxVertices - maximum vertices allowed in buffer
// maxIndices - maximum indices allowed in buffer
public Vertices(int maxVertices, int maxIndices) {
// this.gl = gl; // Save GL Instance
this.positionCnt = POSITION_CNT_2D; // Set Position Component Count
this.vertexStride = this.positionCnt + TEXCOORD_CNT + MVP_MATRIX_INDEX_CNT; // Calculate Vertex Stride
this.vertexSize = this.vertexStride * 4; // Calculate Vertex Byte Size
ByteBuffer buffer = ByteBuffer.allocateDirect( maxVertices * vertexSize ); // Allocate Buffer for Vertices (Max)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.vertices = buffer.asIntBuffer(); // Save Vertex Buffer
if ( maxIndices > 0 ) { // IF Indices Required
buffer = ByteBuffer.allocateDirect( maxIndices * INDEX_SIZE ); // Allocate Buffer for Indices (MAX)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.indices = buffer.asShortBuffer(); // Save Index Buffer
}
else // ELSE Indices Not Required
indices = null; // No Index Buffer
numVertices = 0; // Zero Vertices in Buffer
numIndices = 0; // Zero Indices in Buffer
this.tmpBuffer = new int[maxVertices * vertexSize / 4]; // Create Temp Buffer
// initialize the shader attribute handles
| mTextureCoordinateHandle = AttribVariable.A_TexCoordinate.getHandle();
|
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/ParallelAction.java | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
| import com.primalpond.hunt.agent.prey.Action; | package com.primalpond.hunt.agent.prey.planner.plans;
public class ParallelAction {
private int mTicks; | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/ParallelAction.java
import com.primalpond.hunt.agent.prey.Action;
package com.primalpond.hunt.agent.prey.planner.plans;
public class ParallelAction {
private int mTicks; | private Action mAction; |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/TutorialFragment.java | // Path: TheHunt/src/com/primalpond/hunt/TutorialRenderer.java
// public enum TutorialStep {
// NET_TRAINING, FOOD_TRAINING, CUT_TRAINING;
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.primalpond.hunt.TutorialRenderer.TutorialStep; | package com.primalpond.hunt;
public class TutorialFragment extends Fragment {
protected static final String TAG = "TutorialFragment";
private TextView mText; | // Path: TheHunt/src/com/primalpond/hunt/TutorialRenderer.java
// public enum TutorialStep {
// NET_TRAINING, FOOD_TRAINING, CUT_TRAINING;
// }
// Path: TheHunt/src/com/primalpond/hunt/TutorialFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.primalpond.hunt.TutorialRenderer.TutorialStep;
package com.primalpond.hunt;
public class TutorialFragment extends Fragment {
protected static final String TAG = "TutorialFragment";
private TextView mText; | private TutorialStep mStep; |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/GoToAndEatPlan.java | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/memory/MoodLevel.java
// public enum MoodLevel {
// NEUTRAL, RISK, DESPAIR; // in incr order!
// }
| import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.agent.prey.Action;
import com.primalpond.hunt.agent.prey.memory.MoodLevel;
import com.primalpond.hunt.agent.prey.memory.StressLevel;
import com.primalpond.hunt.agent.prey.memory.WorldModel;
import com.primalpond.hunt.world.events.Event;
import android.util.Log; | package com.primalpond.hunt.agent.prey.planner.plans;
public class GoToAndEatPlan extends GoToPlan {
private static final String TAG = "GoToAndEatPlan";
private boolean ate;
public GoToAndEatPlan(float hX, float hY, float bX, float bY, Event target) {
super(hX, hY, bX, bY, target);
ate = false;
}
@Override
public void update(WorldModel mWorldModel) {
if (ate) return; | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/memory/MoodLevel.java
// public enum MoodLevel {
// NEUTRAL, RISK, DESPAIR; // in incr order!
// }
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/GoToAndEatPlan.java
import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.agent.prey.Action;
import com.primalpond.hunt.agent.prey.memory.MoodLevel;
import com.primalpond.hunt.agent.prey.memory.StressLevel;
import com.primalpond.hunt.agent.prey.memory.WorldModel;
import com.primalpond.hunt.world.events.Event;
import android.util.Log;
package com.primalpond.hunt.agent.prey.planner.plans;
public class GoToAndEatPlan extends GoToPlan {
private static final String TAG = "GoToAndEatPlan";
private boolean ate;
public GoToAndEatPlan(float hX, float hY, float bX, float bY, Event target) {
super(hX, hY, bX, bY, target);
ate = false;
}
@Override
public void update(WorldModel mWorldModel) {
if (ate) return; | if (mWorldModel.getStressLevel() == StressLevel.PLOK_CLOSE && mWorldModel.getMoodLevel() != MoodLevel.DESPAIR) { |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/GoToAndEatPlan.java | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/memory/MoodLevel.java
// public enum MoodLevel {
// NEUTRAL, RISK, DESPAIR; // in incr order!
// }
| import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.agent.prey.Action;
import com.primalpond.hunt.agent.prey.memory.MoodLevel;
import com.primalpond.hunt.agent.prey.memory.StressLevel;
import com.primalpond.hunt.agent.prey.memory.WorldModel;
import com.primalpond.hunt.world.events.Event;
import android.util.Log; | package com.primalpond.hunt.agent.prey.planner.plans;
public class GoToAndEatPlan extends GoToPlan {
private static final String TAG = "GoToAndEatPlan";
private boolean ate;
public GoToAndEatPlan(float hX, float hY, float bX, float bY, Event target) {
super(hX, hY, bX, bY, target);
ate = false;
}
@Override
public void update(WorldModel mWorldModel) {
if (ate) return;
if (mWorldModel.getStressLevel() == StressLevel.PLOK_CLOSE && mWorldModel.getMoodLevel() != MoodLevel.DESPAIR) {
Log.v(TAG, "Plok close!");
finish();
}
else super.update(mWorldModel);
if (arrived) {
finish(); | // Path: TheHunt/src/com/primalpond/hunt/agent/prey/Action.java
// public enum Action {
// TURN_LEFT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_LEFT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_LEFT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// TURN_RIGHT_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), TURN_RIGHT_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// TURN_RIGHT_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN),
// FORWARD_SMALL(PreyData.SMALL_TICKS_BACK_PER_TURN), FORWARD_MEDIUM(PreyData.MEDIUM_TICKS_BACK_PER_TURN),
// FORWARD_LARGE(PreyData.LARGE_TICKS_BACK_PER_TURN), eat(PreyData.EAT_TICKS), none(1), poop(1);
//
// private int mTicks;
//
// private Action(int ticks) {
// mTicks = ticks;
// }
//
// public int getTicks() {
// return mTicks;
// }
//
// public void tickOnce() {
// mTicks--;
// }
// }
//
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/memory/MoodLevel.java
// public enum MoodLevel {
// NEUTRAL, RISK, DESPAIR; // in incr order!
// }
// Path: TheHunt/src/com/primalpond/hunt/agent/prey/planner/plans/GoToAndEatPlan.java
import com.primalpond.hunt.agent.Agent;
import com.primalpond.hunt.agent.prey.Action;
import com.primalpond.hunt.agent.prey.memory.MoodLevel;
import com.primalpond.hunt.agent.prey.memory.StressLevel;
import com.primalpond.hunt.agent.prey.memory.WorldModel;
import com.primalpond.hunt.world.events.Event;
import android.util.Log;
package com.primalpond.hunt.agent.prey.planner.plans;
public class GoToAndEatPlan extends GoToPlan {
private static final String TAG = "GoToAndEatPlan";
private boolean ate;
public GoToAndEatPlan(float hX, float hY, float bX, float bY, Event target) {
super(hX, hY, bX, bY, target);
ate = false;
}
@Override
public void update(WorldModel mWorldModel) {
if (ate) return;
if (mWorldModel.getStressLevel() == StressLevel.PLOK_CLOSE && mWorldModel.getMoodLevel() != MoodLevel.DESPAIR) {
Log.v(TAG, "Plok close!");
finish();
}
else super.update(mWorldModel);
if (arrived) {
finish(); | addParallelAction(Action.eat); |
bekce/oauthly | app/repositories/ProviderLinkRepository.java | // Path: app/models/ProviderLink.java
// public class ProviderLink {
// @MongoId
// private String id;
// /**
// * belonging user, could be null while setting up
// */
// // @Indexed
// private String userId;
// /**
// * e.g. 'facebook' or 'twitter'
// */
// private String providerKey;
// /**
// * last retrieved token
// */
// private Token token;
// /**
// * External user id (e.g. on facebook)
// */
// // @Indexed
// private String remoteUserId;
// private String remoteUserEmail;
// private String remoteUserName;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getProviderKey() {
// return providerKey;
// }
//
// public void setProviderKey(String providerKey) {
// this.providerKey = providerKey;
// }
//
// public Token getToken() {
// return token;
// }
//
// public void setToken(Token token) {
// this.token = token;
// }
//
// public String getRemoteUserId() {
// return remoteUserId;
// }
//
// public void setRemoteUserId(String remoteUserId) {
// this.remoteUserId = remoteUserId;
// }
//
// public String getRemoteUserEmail() {
// return remoteUserEmail;
// }
//
// public void setRemoteUserEmail(String remoteUserEmail) {
// this.remoteUserEmail = remoteUserEmail;
// }
//
// public String getRemoteUserName() {
// return remoteUserName;
// }
//
// public void setRemoteUserName(String remoteUserName) {
// this.remoteUserName = remoteUserName;
// }
// }
| import models.ProviderLink;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.inject.Inject;
import javax.inject.Singleton; | package repositories;
@Singleton
public class ProviderLinkRepository {
private MongoCollection collection;
@Inject
public ProviderLinkRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("providerLink");
// collection.ensureIndex(); //providerKey & remoteUserId, unique
}
| // Path: app/models/ProviderLink.java
// public class ProviderLink {
// @MongoId
// private String id;
// /**
// * belonging user, could be null while setting up
// */
// // @Indexed
// private String userId;
// /**
// * e.g. 'facebook' or 'twitter'
// */
// private String providerKey;
// /**
// * last retrieved token
// */
// private Token token;
// /**
// * External user id (e.g. on facebook)
// */
// // @Indexed
// private String remoteUserId;
// private String remoteUserEmail;
// private String remoteUserName;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getProviderKey() {
// return providerKey;
// }
//
// public void setProviderKey(String providerKey) {
// this.providerKey = providerKey;
// }
//
// public Token getToken() {
// return token;
// }
//
// public void setToken(Token token) {
// this.token = token;
// }
//
// public String getRemoteUserId() {
// return remoteUserId;
// }
//
// public void setRemoteUserId(String remoteUserId) {
// this.remoteUserId = remoteUserId;
// }
//
// public String getRemoteUserEmail() {
// return remoteUserEmail;
// }
//
// public void setRemoteUserEmail(String remoteUserEmail) {
// this.remoteUserEmail = remoteUserEmail;
// }
//
// public String getRemoteUserName() {
// return remoteUserName;
// }
//
// public void setRemoteUserName(String remoteUserName) {
// this.remoteUserName = remoteUserName;
// }
// }
// Path: app/repositories/ProviderLinkRepository.java
import models.ProviderLink;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.inject.Inject;
import javax.inject.Singleton;
package repositories;
@Singleton
public class ProviderLinkRepository {
private MongoCollection collection;
@Inject
public ProviderLinkRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("providerLink");
// collection.ensureIndex(); //providerKey & remoteUserId, unique
}
| public ProviderLink findById(String id) { |
bekce/oauthly | app/repositories/UserRepository.java | // Path: app/config/Utils.java
// public class Utils {
// public static String normalizeUsername(String username){
// if(username == null) return null;
// return username.replaceAll("[^A-Za-z0-9]","_").toLowerCase(Locale.ENGLISH);
// }
//
// public static String normalizeEmail(String email){
// if(email == null) return null;
// return email.toLowerCase(Locale.ENGLISH);
// }
//
// private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// private static final SecureRandom rnd = new SecureRandom();
//
// private static String randomString( int len ){
// StringBuilder sb = new StringBuilder( len );
// for( int i = 0; i < len; i++ )
// sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
// return sb.toString();
// }
//
// public static String newId() {
// return randomString(20);
// // return RandomStringUtils.randomAlphanumeric(20);
// }
// public static String newSecret() {
// return randomString(32);
// }
// }
//
// Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
| import config.Utils;
import models.User;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; | package repositories;
@Singleton
public class UserRepository {
private MongoCollection collection;
@Inject
public UserRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("user");
}
| // Path: app/config/Utils.java
// public class Utils {
// public static String normalizeUsername(String username){
// if(username == null) return null;
// return username.replaceAll("[^A-Za-z0-9]","_").toLowerCase(Locale.ENGLISH);
// }
//
// public static String normalizeEmail(String email){
// if(email == null) return null;
// return email.toLowerCase(Locale.ENGLISH);
// }
//
// private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// private static final SecureRandom rnd = new SecureRandom();
//
// private static String randomString( int len ){
// StringBuilder sb = new StringBuilder( len );
// for( int i = 0; i < len; i++ )
// sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
// return sb.toString();
// }
//
// public static String newId() {
// return randomString(20);
// // return RandomStringUtils.randomAlphanumeric(20);
// }
// public static String newSecret() {
// return randomString(32);
// }
// }
//
// Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
// Path: app/repositories/UserRepository.java
import config.Utils;
import models.User;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
package repositories;
@Singleton
public class UserRepository {
private MongoCollection collection;
@Inject
public UserRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("user");
}
| public User findById(String id) { |
bekce/oauthly | app/repositories/UserRepository.java | // Path: app/config/Utils.java
// public class Utils {
// public static String normalizeUsername(String username){
// if(username == null) return null;
// return username.replaceAll("[^A-Za-z0-9]","_").toLowerCase(Locale.ENGLISH);
// }
//
// public static String normalizeEmail(String email){
// if(email == null) return null;
// return email.toLowerCase(Locale.ENGLISH);
// }
//
// private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// private static final SecureRandom rnd = new SecureRandom();
//
// private static String randomString( int len ){
// StringBuilder sb = new StringBuilder( len );
// for( int i = 0; i < len; i++ )
// sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
// return sb.toString();
// }
//
// public static String newId() {
// return randomString(20);
// // return RandomStringUtils.randomAlphanumeric(20);
// }
// public static String newSecret() {
// return randomString(32);
// }
// }
//
// Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
| import config.Utils;
import models.User;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; | package repositories;
@Singleton
public class UserRepository {
private MongoCollection collection;
@Inject
public UserRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("user");
}
public User findById(String id) {
return collection.findOne("{_id:#}", id).as(User.class);
}
public void save(User u){
collection.save(u);
}
public User findByUsernameNormalized(String usernameNormalized) {
return collection.findOne("{usernameNormalized:#}",usernameNormalized).as(User.class);
}
public User findByEmail(String email) {
return collection.findOne("{email:#}",email).as(User.class);
}
public User findByUsernameOrEmail(String login) { | // Path: app/config/Utils.java
// public class Utils {
// public static String normalizeUsername(String username){
// if(username == null) return null;
// return username.replaceAll("[^A-Za-z0-9]","_").toLowerCase(Locale.ENGLISH);
// }
//
// public static String normalizeEmail(String email){
// if(email == null) return null;
// return email.toLowerCase(Locale.ENGLISH);
// }
//
// private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// private static final SecureRandom rnd = new SecureRandom();
//
// private static String randomString( int len ){
// StringBuilder sb = new StringBuilder( len );
// for( int i = 0; i < len; i++ )
// sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
// return sb.toString();
// }
//
// public static String newId() {
// return randomString(20);
// // return RandomStringUtils.randomAlphanumeric(20);
// }
// public static String newSecret() {
// return randomString(32);
// }
// }
//
// Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
// Path: app/repositories/UserRepository.java
import config.Utils;
import models.User;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
package repositories;
@Singleton
public class UserRepository {
private MongoCollection collection;
@Inject
public UserRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("user");
}
public User findById(String id) {
return collection.findOne("{_id:#}", id).as(User.class);
}
public void save(User u){
collection.save(u);
}
public User findByUsernameNormalized(String usernameNormalized) {
return collection.findOne("{usernameNormalized:#}",usernameNormalized).as(User.class);
}
public User findByEmail(String email) {
return collection.findOne("{email:#}",email).as(User.class);
}
public User findByUsernameOrEmail(String login) { | String normalizedUsername = Utils.normalizeUsername(login); |
bekce/oauthly | app/repositories/ClientRepository.java | // Path: app/models/Client.java
// public class Client {
// @MongoId
// private String id;
// private String secret;
// private String name;
// private String logoUrl;
// /**
// * If true, then all grants shall automatically be given without user consent
// */
// private boolean trusted;
// /**
// * Origin of redirect uri for each request shall match this.
// * e.g. 'http://localhost:8080'
// */
// private String redirectUri;
// /**
// * The id of the managing user of this client
// */
// private String ownerId;
// /**
// * Contains the allowed origin for using the JS authentication. Must match incoming Origin header 1-1 else the request will not be allowed.
// */
// private String allowedOrigin;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLogoUrl() {
// return logoUrl;
// }
//
// public void setLogoUrl(String logoUrl) {
// this.logoUrl = logoUrl;
// }
//
// public boolean isTrusted() {
// return trusted;
// }
//
// public void setTrusted(boolean trusted) {
// this.trusted = trusted;
// }
//
// public String getRedirectUri() {
// return redirectUri;
// }
//
// public void setRedirectUri(String redirectUri) {
// this.redirectUri = redirectUri;
// }
//
// public String getOwnerId() {
// return ownerId;
// }
//
// public void setOwnerId(String ownerId) {
// this.ownerId = ownerId;
// }
//
// public String getAllowedOrigin() {
// return allowedOrigin;
// }
//
// public void setAllowedOrigin(String allowedOrigin) {
// this.allowedOrigin = allowedOrigin;
// }
// }
| import models.Client;
import org.jongo.MongoCollection;
import org.jongo.MongoCursor;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport; | package repositories;
@Singleton
public class ClientRepository {
private MongoCollection collection;
@Inject
public ClientRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("client");
}
| // Path: app/models/Client.java
// public class Client {
// @MongoId
// private String id;
// private String secret;
// private String name;
// private String logoUrl;
// /**
// * If true, then all grants shall automatically be given without user consent
// */
// private boolean trusted;
// /**
// * Origin of redirect uri for each request shall match this.
// * e.g. 'http://localhost:8080'
// */
// private String redirectUri;
// /**
// * The id of the managing user of this client
// */
// private String ownerId;
// /**
// * Contains the allowed origin for using the JS authentication. Must match incoming Origin header 1-1 else the request will not be allowed.
// */
// private String allowedOrigin;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLogoUrl() {
// return logoUrl;
// }
//
// public void setLogoUrl(String logoUrl) {
// this.logoUrl = logoUrl;
// }
//
// public boolean isTrusted() {
// return trusted;
// }
//
// public void setTrusted(boolean trusted) {
// this.trusted = trusted;
// }
//
// public String getRedirectUri() {
// return redirectUri;
// }
//
// public void setRedirectUri(String redirectUri) {
// this.redirectUri = redirectUri;
// }
//
// public String getOwnerId() {
// return ownerId;
// }
//
// public void setOwnerId(String ownerId) {
// this.ownerId = ownerId;
// }
//
// public String getAllowedOrigin() {
// return allowedOrigin;
// }
//
// public void setAllowedOrigin(String allowedOrigin) {
// this.allowedOrigin = allowedOrigin;
// }
// }
// Path: app/repositories/ClientRepository.java
import models.Client;
import org.jongo.MongoCollection;
import org.jongo.MongoCursor;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
package repositories;
@Singleton
public class ClientRepository {
private MongoCollection collection;
@Inject
public ClientRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("client");
}
| public Client findById(String id) { |
bekce/oauthly | app/config/AuthorizationServerSecure.java | // Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
| import models.User;
import play.libs.typedmap.TypedKey;
import play.mvc.With;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package config;
@With(AuthorizationServerAuthAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthorizationServerSecure { | // Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
// Path: app/config/AuthorizationServerSecure.java
import models.User;
import play.libs.typedmap.TypedKey;
import play.mvc.With;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package config;
@With(AuthorizationServerAuthAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthorizationServerSecure { | TypedKey<User> USER = TypedKey.create("user_a"); |
bekce/oauthly | app/config/global/OauthlyModule.java | // Path: app/config/MailService.java
// public interface MailService {
// CompletableFuture<String> sendEmail(String to, String subject, String content);
// }
//
// Path: app/config/MailServiceImplementationType.java
// public enum MailServiceImplementationType {
//
// mailer("config.MailerService"),
// mailgun("config.MailgunService");
//
// private String clazz;
//
// MailServiceImplementationType(String clazz) {
// this.clazz = clazz;
// }
//
// public String getClazz() {
// return clazz;
// }
//
// public MailServiceImplementationType setClazz(String clazz) {
// this.clazz = clazz;
// return this;
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.typesafe.config.Config;
import config.MailService;
import config.MailServiceImplementationType;
import play.Environment;
import play.libs.akka.AkkaGuiceSupport;
import java.util.Optional; | package config.global;
public class OauthlyModule extends AbstractModule implements AkkaGuiceSupport {
private final Environment environment;
private final Config config;
@Inject
public OauthlyModule(Environment environment, Config config) {
this.environment = environment;
this.config = config;
}
@Override
protected void configure() {
bindMailService();
}
private void bindMailService() {
final String mailServiceImplementationConf = Optional
.ofNullable(config.getString("mail.service.implementation"))
.orElse("mailer");
try { | // Path: app/config/MailService.java
// public interface MailService {
// CompletableFuture<String> sendEmail(String to, String subject, String content);
// }
//
// Path: app/config/MailServiceImplementationType.java
// public enum MailServiceImplementationType {
//
// mailer("config.MailerService"),
// mailgun("config.MailgunService");
//
// private String clazz;
//
// MailServiceImplementationType(String clazz) {
// this.clazz = clazz;
// }
//
// public String getClazz() {
// return clazz;
// }
//
// public MailServiceImplementationType setClazz(String clazz) {
// this.clazz = clazz;
// return this;
// }
// }
// Path: app/config/global/OauthlyModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.typesafe.config.Config;
import config.MailService;
import config.MailServiceImplementationType;
import play.Environment;
import play.libs.akka.AkkaGuiceSupport;
import java.util.Optional;
package config.global;
public class OauthlyModule extends AbstractModule implements AkkaGuiceSupport {
private final Environment environment;
private final Config config;
@Inject
public OauthlyModule(Environment environment, Config config) {
this.environment = environment;
this.config = config;
}
@Override
protected void configure() {
bindMailService();
}
private void bindMailService() {
final String mailServiceImplementationConf = Optional
.ofNullable(config.getString("mail.service.implementation"))
.orElse("mailer");
try { | MailServiceImplementationType type = |
bekce/oauthly | app/config/global/OauthlyModule.java | // Path: app/config/MailService.java
// public interface MailService {
// CompletableFuture<String> sendEmail(String to, String subject, String content);
// }
//
// Path: app/config/MailServiceImplementationType.java
// public enum MailServiceImplementationType {
//
// mailer("config.MailerService"),
// mailgun("config.MailgunService");
//
// private String clazz;
//
// MailServiceImplementationType(String clazz) {
// this.clazz = clazz;
// }
//
// public String getClazz() {
// return clazz;
// }
//
// public MailServiceImplementationType setClazz(String clazz) {
// this.clazz = clazz;
// return this;
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.typesafe.config.Config;
import config.MailService;
import config.MailServiceImplementationType;
import play.Environment;
import play.libs.akka.AkkaGuiceSupport;
import java.util.Optional; | package config.global;
public class OauthlyModule extends AbstractModule implements AkkaGuiceSupport {
private final Environment environment;
private final Config config;
@Inject
public OauthlyModule(Environment environment, Config config) {
this.environment = environment;
this.config = config;
}
@Override
protected void configure() {
bindMailService();
}
private void bindMailService() {
final String mailServiceImplementationConf = Optional
.ofNullable(config.getString("mail.service.implementation"))
.orElse("mailer");
try {
MailServiceImplementationType type =
Enum.valueOf(MailServiceImplementationType.class, mailServiceImplementationConf);
| // Path: app/config/MailService.java
// public interface MailService {
// CompletableFuture<String> sendEmail(String to, String subject, String content);
// }
//
// Path: app/config/MailServiceImplementationType.java
// public enum MailServiceImplementationType {
//
// mailer("config.MailerService"),
// mailgun("config.MailgunService");
//
// private String clazz;
//
// MailServiceImplementationType(String clazz) {
// this.clazz = clazz;
// }
//
// public String getClazz() {
// return clazz;
// }
//
// public MailServiceImplementationType setClazz(String clazz) {
// this.clazz = clazz;
// return this;
// }
// }
// Path: app/config/global/OauthlyModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.typesafe.config.Config;
import config.MailService;
import config.MailServiceImplementationType;
import play.Environment;
import play.libs.akka.AkkaGuiceSupport;
import java.util.Optional;
package config.global;
public class OauthlyModule extends AbstractModule implements AkkaGuiceSupport {
private final Environment environment;
private final Config config;
@Inject
public OauthlyModule(Environment environment, Config config) {
this.environment = environment;
this.config = config;
}
@Override
protected void configure() {
bindMailService();
}
private void bindMailService() {
final String mailServiceImplementationConf = Optional
.ofNullable(config.getString("mail.service.implementation"))
.orElse("mailer");
try {
MailServiceImplementationType type =
Enum.valueOf(MailServiceImplementationType.class, mailServiceImplementationConf);
| Class<? extends MailService> bindingClass = environment |
bekce/oauthly | app/repositories/SettingRepository.java | // Path: app/models/Setting.java
// public abstract class Setting {
// @MongoId
// protected String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
| import models.Setting;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton; | package repositories;
@Singleton
public class SettingRepository {
private MongoCollection collection;
@Inject
public SettingRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("setting");
}
public <T> T findById(Class<T> clazz) {
return collection.findOne("{_id:#}", clazz.getSimpleName()).as(clazz);
// return setting != null ? (T) setting.getValue() : null;
}
| // Path: app/models/Setting.java
// public abstract class Setting {
// @MongoId
// protected String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
// Path: app/repositories/SettingRepository.java
import models.Setting;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
package repositories;
@Singleton
public class SettingRepository {
private MongoCollection collection;
@Inject
public SettingRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("setting");
}
public <T> T findById(Class<T> clazz) {
return collection.findOne("{_id:#}", clazz.getSimpleName()).as(clazz);
// return setting != null ? (T) setting.getValue() : null;
}
| public void save(Setting u){ |
bekce/oauthly | app/config/AuthorizationServerAuthAction.java | // Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
| import controllers.routes;
import models.User;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import javax.inject.Inject;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import static play.mvc.Controller.flash; | package config;
public class AuthorizationServerAuthAction extends play.mvc.Action<AuthorizationServerSecure> {
private final JwtUtils jwtUtils;
@Inject
public AuthorizationServerAuthAction(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.Cookie ltat = ctx.request().cookie("ltat");
boolean valid = configuration.optional();
if(ltat != null) { | // Path: app/models/User.java
// public class User {
// @MongoId
// private String id;
// // @Indexed
// private String username;
// // @Indexed
// private String usernameNormalized;
// // @Indexed
// private String email;
// private String password;
// /**
// * Can create his/her own clients
// */
// private boolean admin;
// /**
// * Last update time to important changes like email and password in millis
// */
// private long lastUpdateTime;
// /**
// * User creation time in millis
// */
// private long creationTime;
// /**
// * If the user's email address verified with confirmation link, value will be true.
// * Value can only be false if this user was imported from another system.
// */
// private boolean emailVerified;
// /**
// * If the user is disabled, this field will contain the reason, else it will be null.
// * Disabled users are not able to login.
// */
// private String disabledReason;
//
// public void encryptThenSetPassword(String password_plaintext){
// String salt = BCrypt.gensalt(12);
// this.password = BCrypt.hashpw(password_plaintext, salt);
// this.lastUpdateTime = System.currentTimeMillis();
// }
//
// public boolean checkPassword(String password_plaintext){
// if(this.password == null || password_plaintext == null)
// return false;
// if(!this.password.startsWith("$2a$"))
// throw new IllegalArgumentException("Invalid hash provided for comparison");
// return BCrypt.checkpw(password_plaintext, password);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getUsernameNormalized() {
// return usernameNormalized;
// }
//
// public void setUsernameNormalized(String usernameNormalized) {
// this.usernameNormalized = usernameNormalized;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
//
// public long getLastUpdateTime() {
// return lastUpdateTime;
// }
//
// public void setLastUpdateTime(long lastUpdateTime) {
// this.lastUpdateTime = lastUpdateTime;
// }
//
// public long getCreationTime() {
// return creationTime;
// }
//
// public void setCreationTime(long creationTime) {
// this.creationTime = creationTime;
// }
//
// public boolean isEmailVerified() {
// return emailVerified;
// }
//
// public void setEmailVerified(boolean emailVerified) {
// this.emailVerified = emailVerified;
// }
//
// public boolean isDisabled(){
// return disabledReason != null;
// }
//
// public String getDisabledReason() {
// return disabledReason;
// }
//
// public void setDisabledReason(String disabledReason) {
// this.disabledReason = disabledReason;
// }
// }
// Path: app/config/AuthorizationServerAuthAction.java
import controllers.routes;
import models.User;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import javax.inject.Inject;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import static play.mvc.Controller.flash;
package config;
public class AuthorizationServerAuthAction extends play.mvc.Action<AuthorizationServerSecure> {
private final JwtUtils jwtUtils;
@Inject
public AuthorizationServerAuthAction(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.Cookie ltat = ctx.request().cookie("ltat");
boolean valid = configuration.optional();
if(ltat != null) { | User user = jwtUtils.validateCookie(ltat.value()); |
bekce/oauthly | app/repositories/GrantRepository.java | // Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
| import models.Grant;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton; | package repositories;
@Singleton
public class GrantRepository {
private MongoCollection collection;
@Inject
public GrantRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("grant");
}
| // Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
// Path: app/repositories/GrantRepository.java
import models.Grant;
import org.jongo.MongoCollection;
import uk.co.panaxiom.playjongo.PlayJongo;
import javax.inject.Inject;
import javax.inject.Singleton;
package repositories;
@Singleton
public class GrantRepository {
private MongoCollection collection;
@Inject
public GrantRepository(PlayJongo playJongo) {
this.collection = playJongo.jongo().getCollection("grant");
}
| public Grant findById(String id) { |
bekce/oauthly | app/models/ProviderLink.java | // Path: app/dtos/Token.java
// @JsonInclude(JsonInclude.Include.NON_NULL)
// public class Token {
// @JsonProperty("access_token")
// private String accessToken;
// @JsonProperty("refresh_token")
// private String refreshToken;
// @JsonProperty("token_type")
// private String tokenType;
// @JsonProperty("created_at")
// private Long createdAt;
// @JsonProperty("expires_in")
// private Long expiresIn;
// @JsonProperty("scope")
// private String scope;
//
// public Token() {
// }
//
// public Token(String accessToken, String refreshToken, String tokenType, long expires_in, String scope) {
// this.accessToken = accessToken;
// this.refreshToken = refreshToken;
// this.tokenType = tokenType;
// this.expiresIn = expires_in;
// this.scope = scope;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
//
// public String getRefreshToken() {
// return refreshToken;
// }
//
// public void setRefreshToken(String refreshToken) {
// this.refreshToken = refreshToken;
// }
//
// public String getTokenType() {
// return tokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.tokenType = tokenType;
// }
//
// public Long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Long createdAt) {
// this.createdAt = createdAt;
// }
//
// public Long getExpiresIn() {
// return expiresIn;
// }
//
// public void setExpiresIn(Long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// public String getScope() {
// return scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Token token = (Token) o;
// return Objects.equals(accessToken, token.accessToken) &&
// Objects.equals(refreshToken, token.refreshToken) &&
// Objects.equals(tokenType, token.tokenType) &&
// Objects.equals(createdAt, token.createdAt) &&
// Objects.equals(expiresIn, token.expiresIn) &&
// Objects.equals(scope, token.scope);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(accessToken, refreshToken, tokenType, createdAt, expiresIn, scope);
// }
//
// @Override
// public String toString() {
// return "Token{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshToken='" + refreshToken + '\'' +
// ", tokenType='" + tokenType + '\'' +
// ", createdAt=" + createdAt +
// ", expiresIn=" + expiresIn +
// ", scope='" + scope + '\'' +
// '}';
// }
// }
| import dtos.Token;
import org.jongo.marshall.jackson.oid.MongoId; | package models;
/**
* Models an authorization from an oauth provider (facebook, twitter, etc)
* to one of oauthly users.
* Created by Selim Eren Bekçe on 15.08.2017.
*/
public class ProviderLink {
@MongoId
private String id;
/**
* belonging user, could be null while setting up
*/
// @Indexed
private String userId;
/**
* e.g. 'facebook' or 'twitter'
*/
private String providerKey;
/**
* last retrieved token
*/ | // Path: app/dtos/Token.java
// @JsonInclude(JsonInclude.Include.NON_NULL)
// public class Token {
// @JsonProperty("access_token")
// private String accessToken;
// @JsonProperty("refresh_token")
// private String refreshToken;
// @JsonProperty("token_type")
// private String tokenType;
// @JsonProperty("created_at")
// private Long createdAt;
// @JsonProperty("expires_in")
// private Long expiresIn;
// @JsonProperty("scope")
// private String scope;
//
// public Token() {
// }
//
// public Token(String accessToken, String refreshToken, String tokenType, long expires_in, String scope) {
// this.accessToken = accessToken;
// this.refreshToken = refreshToken;
// this.tokenType = tokenType;
// this.expiresIn = expires_in;
// this.scope = scope;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
//
// public String getRefreshToken() {
// return refreshToken;
// }
//
// public void setRefreshToken(String refreshToken) {
// this.refreshToken = refreshToken;
// }
//
// public String getTokenType() {
// return tokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.tokenType = tokenType;
// }
//
// public Long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Long createdAt) {
// this.createdAt = createdAt;
// }
//
// public Long getExpiresIn() {
// return expiresIn;
// }
//
// public void setExpiresIn(Long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// public String getScope() {
// return scope;
// }
//
// public void setScope(String scope) {
// this.scope = scope;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// Token token = (Token) o;
// return Objects.equals(accessToken, token.accessToken) &&
// Objects.equals(refreshToken, token.refreshToken) &&
// Objects.equals(tokenType, token.tokenType) &&
// Objects.equals(createdAt, token.createdAt) &&
// Objects.equals(expiresIn, token.expiresIn) &&
// Objects.equals(scope, token.scope);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(accessToken, refreshToken, tokenType, createdAt, expiresIn, scope);
// }
//
// @Override
// public String toString() {
// return "Token{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshToken='" + refreshToken + '\'' +
// ", tokenType='" + tokenType + '\'' +
// ", createdAt=" + createdAt +
// ", expiresIn=" + expiresIn +
// ", scope='" + scope + '\'' +
// '}';
// }
// }
// Path: app/models/ProviderLink.java
import dtos.Token;
import org.jongo.marshall.jackson.oid.MongoId;
package models;
/**
* Models an authorization from an oauth provider (facebook, twitter, etc)
* to one of oauthly users.
* Created by Selim Eren Bekçe on 15.08.2017.
*/
public class ProviderLink {
@MongoId
private String id;
/**
* belonging user, could be null while setting up
*/
// @Indexed
private String userId;
/**
* e.g. 'facebook' or 'twitter'
*/
private String providerKey;
/**
* last retrieved token
*/ | private Token token; |
bekce/oauthly | app/config/ResourceServerSecure.java | // Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
| import models.Grant;
import play.libs.typedmap.TypedKey;
import play.mvc.With;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package config;
@With(ResourceServerAuthAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResourceServerSecure { | // Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
// Path: app/config/ResourceServerSecure.java
import models.Grant;
import play.libs.typedmap.TypedKey;
import play.mvc.With;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package config;
@With(ResourceServerAuthAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResourceServerSecure { | TypedKey<Grant> GRANT = TypedKey.create("grant_r"); |
bekce/oauthly | app/config/ResourceServerAuthAction.java | // Path: app/dtos/TokenStatus.java
// public enum TokenStatus {
// /**
// * Token is invalid
// */
// INVALID,
// /**
// * Token is a valid access token
// */
// VALID_ACCESS,
// /**
// * Token is a valid refresh token. Does not qualify for an access token!
// */
// VALID_REFRESH
// }
//
// Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
| import dtos.TokenStatus;
import models.Grant;
import org.apache.commons.lang3.StringUtils;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import scala.Tuple2;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage; | package config;
public class ResourceServerAuthAction extends play.mvc.Action<ResourceServerSecure> {
@Inject
private JwtUtils jwtUtils;
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.RequestHeader requestHeader = ctx._requestHeader().asJava();
String token = requestHeader.header("Authorization")
.filter(s -> StringUtils.startsWithIgnoreCase(s, "Bearer "))
.map(s -> s.substring("Bearer ".length()).trim())
.orElseGet(() -> requestHeader.getQueryString("access_token"));
| // Path: app/dtos/TokenStatus.java
// public enum TokenStatus {
// /**
// * Token is invalid
// */
// INVALID,
// /**
// * Token is a valid access token
// */
// VALID_ACCESS,
// /**
// * Token is a valid refresh token. Does not qualify for an access token!
// */
// VALID_REFRESH
// }
//
// Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
// Path: app/config/ResourceServerAuthAction.java
import dtos.TokenStatus;
import models.Grant;
import org.apache.commons.lang3.StringUtils;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import scala.Tuple2;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
package config;
public class ResourceServerAuthAction extends play.mvc.Action<ResourceServerSecure> {
@Inject
private JwtUtils jwtUtils;
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.RequestHeader requestHeader = ctx._requestHeader().asJava();
String token = requestHeader.header("Authorization")
.filter(s -> StringUtils.startsWithIgnoreCase(s, "Bearer "))
.map(s -> s.substring("Bearer ".length()).trim())
.orElseGet(() -> requestHeader.getQueryString("access_token"));
| Tuple2<Grant, TokenStatus> tuple = jwtUtils.getTokenStatus(token); |
bekce/oauthly | app/config/ResourceServerAuthAction.java | // Path: app/dtos/TokenStatus.java
// public enum TokenStatus {
// /**
// * Token is invalid
// */
// INVALID,
// /**
// * Token is a valid access token
// */
// VALID_ACCESS,
// /**
// * Token is a valid refresh token. Does not qualify for an access token!
// */
// VALID_REFRESH
// }
//
// Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
| import dtos.TokenStatus;
import models.Grant;
import org.apache.commons.lang3.StringUtils;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import scala.Tuple2;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage; | package config;
public class ResourceServerAuthAction extends play.mvc.Action<ResourceServerSecure> {
@Inject
private JwtUtils jwtUtils;
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.RequestHeader requestHeader = ctx._requestHeader().asJava();
String token = requestHeader.header("Authorization")
.filter(s -> StringUtils.startsWithIgnoreCase(s, "Bearer "))
.map(s -> s.substring("Bearer ".length()).trim())
.orElseGet(() -> requestHeader.getQueryString("access_token"));
| // Path: app/dtos/TokenStatus.java
// public enum TokenStatus {
// /**
// * Token is invalid
// */
// INVALID,
// /**
// * Token is a valid access token
// */
// VALID_ACCESS,
// /**
// * Token is a valid refresh token. Does not qualify for an access token!
// */
// VALID_REFRESH
// }
//
// Path: app/models/Grant.java
// public class Grant {
// @MongoId
// private String id;
// private String userId;
// private String clientId;
// private Set<String> scopes = new HashSet<>();
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public Set<String> getScopes() {
// return scopes;
// }
//
// public void setScopes(Set<String> scopes) {
// this.scopes = scopes;
// }
// }
// Path: app/config/ResourceServerAuthAction.java
import dtos.TokenStatus;
import models.Grant;
import org.apache.commons.lang3.StringUtils;
import play.libs.Json;
import play.mvc.Http;
import play.mvc.Result;
import scala.Tuple2;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
package config;
public class ResourceServerAuthAction extends play.mvc.Action<ResourceServerSecure> {
@Inject
private JwtUtils jwtUtils;
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Http.RequestHeader requestHeader = ctx._requestHeader().asJava();
String token = requestHeader.header("Authorization")
.filter(s -> StringUtils.startsWithIgnoreCase(s, "Bearer "))
.map(s -> s.substring("Bearer ".length()).trim())
.orElseGet(() -> requestHeader.getQueryString("access_token"));
| Tuple2<Grant, TokenStatus> tuple = jwtUtils.getTokenStatus(token); |
idega/com.idega.block.datareport | src/java/com/idega/block/datareport/presentation/ReportQueryOverview.java | // Path: src/java/com/idega/block/datareport/business/JasperReportBusiness.java
// public interface JasperReportBusiness extends com.idega.business.IBOService, UserGroupPlugInBusiness
// {
// public JasperDesign generateLayout(JRDataSource p0)throws java.io.IOException,JRException, java.rmi.RemoteException;
// public com.idega.block.datareport.data.DesignBox getDesignBox(int p0) throws java.rmi.RemoteException;
// public JasperDesign getDesignFromBundle(com.idega.idegaweb.IWBundle p0,java.lang.String p1) throws java.rmi.RemoteException;
// public com.idega.block.datareport.data.DesignBox getDynamicDesignBox(com.idega.block.dataquery.data.sql.SQLQuery p0,com.idega.idegaweb.IWResourceBundle p1,com.idega.presentation.IWContext p2)throws java.io.IOException,JRException, java.rmi.RemoteException;
// public java.lang.String getExcelReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getHtmlReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getXmlReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getPdfReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public JasperPrint getReport(JRDataSource p0,java.util.Map p1,JasperDesign p2)throws JRException, java.rmi.RemoteException;
// public String getSynchronizedSimpleExcelReport(com.idega.block.dataquery.data.QueryResult p0,com.idega.block.datareport.data.DesignBox p2,java.lang.String p3) throws java.rmi.RemoteException;
// public JasperPrint printSynchronizedReport(com.idega.block.dataquery.data.QueryResult p0,com.idega.block.datareport.data.DesignBox p2) throws java.rmi.RemoteException;
// public String getSimpleExcelReport(JRDataSource reportData, String nameOfReport, ReportDescription description);
// }
| import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import com.idega.block.dataquery.business.QueryService;
import com.idega.block.dataquery.business.QueryToSQLBridge;
import com.idega.block.dataquery.data.QueryRepresentation;
import com.idega.block.dataquery.presentation.ReportQueryBuilder;
import com.idega.block.datareport.business.JasperReportBusiness;
import com.idega.block.entity.business.EntityToPresentationObjectConverter;
import com.idega.block.entity.data.EntityPath;
import com.idega.block.entity.data.EntityPathValueContainer;
import com.idega.block.entity.presentation.EntityBrowser;
import com.idega.block.entity.presentation.converter.ButtonConverter;
import com.idega.block.entity.presentation.converter.CheckBoxConverter;
import com.idega.block.entity.presentation.converter.editable.DropDownMenuConverter;
import com.idega.block.entity.presentation.converter.editable.OptionProvider;
import com.idega.business.IBOLookup;
import com.idega.core.file.data.ICFile;
import com.idega.core.file.data.ICFileHome;
import com.idega.data.EntityRepresentation;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.SubmitButton;
import com.idega.user.data.User; | Integer id = (Integer) iterator.next();
queryService.removeUserQuery(id, currentUser);
}
}
// some get service methods
private QueryService getQueryService(IWContext iwc) {
try {
return (QueryService) IBOLookup.getServiceInstance( iwc.getApplicationContext() ,QueryService.class);
}
catch (RemoteException ex) {
System.err.println("[ReportOverview]: Can't retrieve QueryService. Message is: " + ex.getMessage());
throw new RuntimeException("[ReportOverview]: Can't retrieve QueryService");
}
}
public QueryToSQLBridge getQueryToSQLBridge() {
try {
return (QueryToSQLBridge) IBOLookup.getServiceInstance( getIWApplicationContext() ,QueryToSQLBridge.class);
}
catch (RemoteException ex) {
System.err.println("[ReportOverview]: Can't retrieve QueryToSqlBridge. Message is: " + ex.getMessage());
throw new RuntimeException("[ReportOverview]: Can't retrieve QueryToSQLBridge");
}
}
| // Path: src/java/com/idega/block/datareport/business/JasperReportBusiness.java
// public interface JasperReportBusiness extends com.idega.business.IBOService, UserGroupPlugInBusiness
// {
// public JasperDesign generateLayout(JRDataSource p0)throws java.io.IOException,JRException, java.rmi.RemoteException;
// public com.idega.block.datareport.data.DesignBox getDesignBox(int p0) throws java.rmi.RemoteException;
// public JasperDesign getDesignFromBundle(com.idega.idegaweb.IWBundle p0,java.lang.String p1) throws java.rmi.RemoteException;
// public com.idega.block.datareport.data.DesignBox getDynamicDesignBox(com.idega.block.dataquery.data.sql.SQLQuery p0,com.idega.idegaweb.IWResourceBundle p1,com.idega.presentation.IWContext p2)throws java.io.IOException,JRException, java.rmi.RemoteException;
// public java.lang.String getExcelReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getHtmlReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getXmlReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public java.lang.String getPdfReport(JasperPrint p0,java.lang.String p1) throws java.rmi.RemoteException;
// public JasperPrint getReport(JRDataSource p0,java.util.Map p1,JasperDesign p2)throws JRException, java.rmi.RemoteException;
// public String getSynchronizedSimpleExcelReport(com.idega.block.dataquery.data.QueryResult p0,com.idega.block.datareport.data.DesignBox p2,java.lang.String p3) throws java.rmi.RemoteException;
// public JasperPrint printSynchronizedReport(com.idega.block.dataquery.data.QueryResult p0,com.idega.block.datareport.data.DesignBox p2) throws java.rmi.RemoteException;
// public String getSimpleExcelReport(JRDataSource reportData, String nameOfReport, ReportDescription description);
// }
// Path: src/java/com/idega/block/datareport/presentation/ReportQueryOverview.java
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import com.idega.block.dataquery.business.QueryService;
import com.idega.block.dataquery.business.QueryToSQLBridge;
import com.idega.block.dataquery.data.QueryRepresentation;
import com.idega.block.dataquery.presentation.ReportQueryBuilder;
import com.idega.block.datareport.business.JasperReportBusiness;
import com.idega.block.entity.business.EntityToPresentationObjectConverter;
import com.idega.block.entity.data.EntityPath;
import com.idega.block.entity.data.EntityPathValueContainer;
import com.idega.block.entity.presentation.EntityBrowser;
import com.idega.block.entity.presentation.converter.ButtonConverter;
import com.idega.block.entity.presentation.converter.CheckBoxConverter;
import com.idega.block.entity.presentation.converter.editable.DropDownMenuConverter;
import com.idega.block.entity.presentation.converter.editable.OptionProvider;
import com.idega.business.IBOLookup;
import com.idega.core.file.data.ICFile;
import com.idega.core.file.data.ICFileHome;
import com.idega.data.EntityRepresentation;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.SubmitButton;
import com.idega.user.data.User;
Integer id = (Integer) iterator.next();
queryService.removeUserQuery(id, currentUser);
}
}
// some get service methods
private QueryService getQueryService(IWContext iwc) {
try {
return (QueryService) IBOLookup.getServiceInstance( iwc.getApplicationContext() ,QueryService.class);
}
catch (RemoteException ex) {
System.err.println("[ReportOverview]: Can't retrieve QueryService. Message is: " + ex.getMessage());
throw new RuntimeException("[ReportOverview]: Can't retrieve QueryService");
}
}
public QueryToSQLBridge getQueryToSQLBridge() {
try {
return (QueryToSQLBridge) IBOLookup.getServiceInstance( getIWApplicationContext() ,QueryToSQLBridge.class);
}
catch (RemoteException ex) {
System.err.println("[ReportOverview]: Can't retrieve QueryToSqlBridge. Message is: " + ex.getMessage());
throw new RuntimeException("[ReportOverview]: Can't retrieve QueryToSQLBridge");
}
}
| public JasperReportBusiness getReportBusiness() { |
jweese/thrax | src/edu/jhu/thrax/hadoop/features/mapred/MapReduceFeature.java | // Path: src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java
// public class ExtractionJob implements ThraxJob {
//
// public Set<Class<? extends ThraxJob>> getPrerequisites() {
// Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
// result.add(VocabularyJob.class);
// return result;
// }
//
// public Job getJob(Configuration conf) throws IOException {
// Job job = new Job(conf, "extraction");
// job.setJarByClass(ExtractionMapper.class);
//
// job.setMapperClass(ExtractionMapper.class);
// job.setCombinerClass(ExtractionCombiner.class);
// job.setReducerClass(ExtractionReducer.class);
//
// job.setSortComparatorClass(AlignedRuleWritable.RuleYieldComparator.class);
// job.setPartitionerClass(AlignedRuleWritable.RuleYieldPartitioner.class);
//
// job.setMapOutputKeyClass(AlignedRuleWritable.class);
// job.setMapOutputValueClass(Annotation.class);
// job.setOutputKeyClass(RuleWritable.class);
// job.setOutputValueClass(Annotation.class);
//
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
//
// int numReducers = conf.getInt("thrax.reducers", 4);
// job.setNumReduceTasks(numReducers);
//
// FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file")));
// int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
// if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize);
//
// FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "rules"));
//
// return job;
// }
//
// // TODO: unify names of jobs and their output directories
//
// public String getName() {
// return "extraction";
// }
//
// public String getOutputSuffix() {
// return "rules";
// }
// }
| import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.features.Feature;
import edu.jhu.thrax.hadoop.jobs.ExtractionJob;
import edu.jhu.thrax.hadoop.jobs.ThraxJob; | public abstract Class<? extends Reducer> reducerClass();
public Job getJob(Configuration conf) throws IOException {
String name = getName();
Job job = new Job(conf, name);
job.setJarByClass(this.getClass());
job.setMapperClass(this.mapperClass());
job.setCombinerClass(this.combinerClass());
job.setSortComparatorClass(this.sortComparatorClass());
job.setPartitionerClass(this.partitionerClass());
job.setReducerClass(this.reducerClass());
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputKeyClass(RuleWritable.class);
job.setOutputValueClass(FeaturePair.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
setMapOutputFormat(job);
int num_reducers = conf.getInt("thrax.reducers", 4);
job.setNumReduceTasks(num_reducers);
FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.work-dir") + "rules"));
FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + name));
return job;
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>(); | // Path: src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java
// public class ExtractionJob implements ThraxJob {
//
// public Set<Class<? extends ThraxJob>> getPrerequisites() {
// Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
// result.add(VocabularyJob.class);
// return result;
// }
//
// public Job getJob(Configuration conf) throws IOException {
// Job job = new Job(conf, "extraction");
// job.setJarByClass(ExtractionMapper.class);
//
// job.setMapperClass(ExtractionMapper.class);
// job.setCombinerClass(ExtractionCombiner.class);
// job.setReducerClass(ExtractionReducer.class);
//
// job.setSortComparatorClass(AlignedRuleWritable.RuleYieldComparator.class);
// job.setPartitionerClass(AlignedRuleWritable.RuleYieldPartitioner.class);
//
// job.setMapOutputKeyClass(AlignedRuleWritable.class);
// job.setMapOutputValueClass(Annotation.class);
// job.setOutputKeyClass(RuleWritable.class);
// job.setOutputValueClass(Annotation.class);
//
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
//
// int numReducers = conf.getInt("thrax.reducers", 4);
// job.setNumReduceTasks(numReducers);
//
// FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file")));
// int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
// if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize);
//
// FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "rules"));
//
// return job;
// }
//
// // TODO: unify names of jobs and their output directories
//
// public String getName() {
// return "extraction";
// }
//
// public String getOutputSuffix() {
// return "rules";
// }
// }
// Path: src/edu/jhu/thrax/hadoop/features/mapred/MapReduceFeature.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.features.Feature;
import edu.jhu.thrax.hadoop.jobs.ExtractionJob;
import edu.jhu.thrax.hadoop.jobs.ThraxJob;
public abstract Class<? extends Reducer> reducerClass();
public Job getJob(Configuration conf) throws IOException {
String name = getName();
Job job = new Job(conf, name);
job.setJarByClass(this.getClass());
job.setMapperClass(this.mapperClass());
job.setCombinerClass(this.combinerClass());
job.setSortComparatorClass(this.sortComparatorClass());
job.setPartitionerClass(this.partitionerClass());
job.setReducerClass(this.reducerClass());
job.setInputFormatClass(SequenceFileInputFormat.class);
job.setOutputKeyClass(RuleWritable.class);
job.setOutputValueClass(FeaturePair.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
setMapOutputFormat(job);
int num_reducers = conf.getInt("thrax.reducers", 4);
job.setNumReduceTasks(num_reducers);
FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.work-dir") + "rules"));
FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + name));
return job;
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>(); | result.add(ExtractionJob.class); |
jweese/thrax | src/edu/jhu/thrax/hadoop/features/annotation/AnnotationFeatureJob.java | // Path: src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java
// public class ExtractionJob implements ThraxJob {
//
// public Set<Class<? extends ThraxJob>> getPrerequisites() {
// Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
// result.add(VocabularyJob.class);
// return result;
// }
//
// public Job getJob(Configuration conf) throws IOException {
// Job job = new Job(conf, "extraction");
// job.setJarByClass(ExtractionMapper.class);
//
// job.setMapperClass(ExtractionMapper.class);
// job.setCombinerClass(ExtractionCombiner.class);
// job.setReducerClass(ExtractionReducer.class);
//
// job.setSortComparatorClass(AlignedRuleWritable.RuleYieldComparator.class);
// job.setPartitionerClass(AlignedRuleWritable.RuleYieldPartitioner.class);
//
// job.setMapOutputKeyClass(AlignedRuleWritable.class);
// job.setMapOutputValueClass(Annotation.class);
// job.setOutputKeyClass(RuleWritable.class);
// job.setOutputValueClass(Annotation.class);
//
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
//
// int numReducers = conf.getInt("thrax.reducers", 4);
// job.setNumReduceTasks(numReducers);
//
// FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file")));
// int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
// if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize);
//
// FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "rules"));
//
// return job;
// }
//
// // TODO: unify names of jobs and their output directories
//
// public String getName() {
// return "extraction";
// }
//
// public String getOutputSuffix() {
// return "rules";
// }
// }
| import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.Annotation;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.jobs.ExtractionJob;
import edu.jhu.thrax.hadoop.jobs.ThraxJob; | package edu.jhu.thrax.hadoop.features.annotation;
public class AnnotationFeatureJob implements ThraxJob {
public AnnotationFeatureJob() {}
protected static HashSet<Class<? extends ThraxJob>> prereqs =
new HashSet<Class<? extends ThraxJob>>();
public Set<Class<? extends ThraxJob>> getPrerequisites() { | // Path: src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java
// public class ExtractionJob implements ThraxJob {
//
// public Set<Class<? extends ThraxJob>> getPrerequisites() {
// Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
// result.add(VocabularyJob.class);
// return result;
// }
//
// public Job getJob(Configuration conf) throws IOException {
// Job job = new Job(conf, "extraction");
// job.setJarByClass(ExtractionMapper.class);
//
// job.setMapperClass(ExtractionMapper.class);
// job.setCombinerClass(ExtractionCombiner.class);
// job.setReducerClass(ExtractionReducer.class);
//
// job.setSortComparatorClass(AlignedRuleWritable.RuleYieldComparator.class);
// job.setPartitionerClass(AlignedRuleWritable.RuleYieldPartitioner.class);
//
// job.setMapOutputKeyClass(AlignedRuleWritable.class);
// job.setMapOutputValueClass(Annotation.class);
// job.setOutputKeyClass(RuleWritable.class);
// job.setOutputValueClass(Annotation.class);
//
// job.setOutputFormatClass(SequenceFileOutputFormat.class);
//
// int numReducers = conf.getInt("thrax.reducers", 4);
// job.setNumReduceTasks(numReducers);
//
// FileInputFormat.setInputPaths(job, new Path(conf.get("thrax.input-file")));
// int maxSplitSize = conf.getInt("thrax.max-split-size", 0);
// if (maxSplitSize != 0) FileInputFormat.setMaxInputSplitSize(job, maxSplitSize);
//
// FileOutputFormat.setOutputPath(job, new Path(conf.get("thrax.work-dir") + "rules"));
//
// return job;
// }
//
// // TODO: unify names of jobs and their output directories
//
// public String getName() {
// return "extraction";
// }
//
// public String getOutputSuffix() {
// return "rules";
// }
// }
// Path: src/edu/jhu/thrax/hadoop/features/annotation/AnnotationFeatureJob.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.Annotation;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.jobs.ExtractionJob;
import edu.jhu.thrax.hadoop.jobs.ThraxJob;
package edu.jhu.thrax.hadoop.features.annotation;
public class AnnotationFeatureJob implements ThraxJob {
public AnnotationFeatureJob() {}
protected static HashSet<Class<? extends ThraxJob>> prereqs =
new HashSet<Class<? extends ThraxJob>>();
public Set<Class<? extends ThraxJob>> getPrerequisites() { | prereqs.add(ExtractionJob.class); |
jweese/thrax | src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java | // Path: src/edu/jhu/thrax/hadoop/extraction/ExtractionReducer.java
// public class ExtractionReducer
// extends Reducer<AlignedRuleWritable, Annotation, RuleWritable, Annotation> {
//
// private RuleWritable currentRule = null;
// private Annotation currentAnnotation = null;
// private AlignmentWritable maxAlignment = null;
// private int alignmentCount;
//
// private int minCount;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// minCount = conf.getInt("thrax.min-rule-count", 1);
// }
//
// protected void reduce(AlignedRuleWritable key, Iterable<Annotation> values, Context context)
// throws IOException, InterruptedException {
// RuleWritable rule = key.getRule();
// AlignmentWritable alignment = key.getAlignment();
//
// Annotation merged = new Annotation();
// for (Annotation a : values)
// merged.merge(a);
//
// if (!rule.equals(currentRule)) {
// if (currentRule != null
// && (currentAnnotation.count() >= minCount || isUnigramRule(currentRule))) {
// currentAnnotation.setAlignment(maxAlignment);
// context.write(currentRule, currentAnnotation);
// context.progress();
// }
// currentRule = new RuleWritable(rule);
// currentAnnotation = new Annotation();
// alignmentCount = 0;
// maxAlignment = null;
// }
// currentAnnotation.merge(merged);
// if (alignmentCount < merged.count()) {
// maxAlignment = new AlignmentWritable(alignment);
// alignmentCount = merged.count();
// }
// }
//
// protected void cleanup(Context context) throws IOException, InterruptedException {
// if (currentRule != null) {
// if (currentAnnotation.count() >= minCount || isUnigramRule(currentRule)) {
// currentAnnotation.setAlignment(maxAlignment);
// context.write(currentRule, currentAnnotation);
// context.progress();
// }
// }
// }
//
// private static boolean isUnigramRule(RuleWritable rule) {
// if (rule.source.length == 1) return !Vocabulary.nt(rule.source[0]);
// return rule.target.length == 1 && !Vocabulary.nt(rule.target[0]);
// }
// }
| import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.AlignedRuleWritable;
import edu.jhu.thrax.hadoop.datatypes.Annotation;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.extraction.ExtractionCombiner;
import edu.jhu.thrax.hadoop.extraction.ExtractionMapper;
import edu.jhu.thrax.hadoop.extraction.ExtractionReducer; | package edu.jhu.thrax.hadoop.jobs;
public class ExtractionJob implements ThraxJob {
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
result.add(VocabularyJob.class);
return result;
}
public Job getJob(Configuration conf) throws IOException {
Job job = new Job(conf, "extraction");
job.setJarByClass(ExtractionMapper.class);
job.setMapperClass(ExtractionMapper.class);
job.setCombinerClass(ExtractionCombiner.class); | // Path: src/edu/jhu/thrax/hadoop/extraction/ExtractionReducer.java
// public class ExtractionReducer
// extends Reducer<AlignedRuleWritable, Annotation, RuleWritable, Annotation> {
//
// private RuleWritable currentRule = null;
// private Annotation currentAnnotation = null;
// private AlignmentWritable maxAlignment = null;
// private int alignmentCount;
//
// private int minCount;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// minCount = conf.getInt("thrax.min-rule-count", 1);
// }
//
// protected void reduce(AlignedRuleWritable key, Iterable<Annotation> values, Context context)
// throws IOException, InterruptedException {
// RuleWritable rule = key.getRule();
// AlignmentWritable alignment = key.getAlignment();
//
// Annotation merged = new Annotation();
// for (Annotation a : values)
// merged.merge(a);
//
// if (!rule.equals(currentRule)) {
// if (currentRule != null
// && (currentAnnotation.count() >= minCount || isUnigramRule(currentRule))) {
// currentAnnotation.setAlignment(maxAlignment);
// context.write(currentRule, currentAnnotation);
// context.progress();
// }
// currentRule = new RuleWritable(rule);
// currentAnnotation = new Annotation();
// alignmentCount = 0;
// maxAlignment = null;
// }
// currentAnnotation.merge(merged);
// if (alignmentCount < merged.count()) {
// maxAlignment = new AlignmentWritable(alignment);
// alignmentCount = merged.count();
// }
// }
//
// protected void cleanup(Context context) throws IOException, InterruptedException {
// if (currentRule != null) {
// if (currentAnnotation.count() >= minCount || isUnigramRule(currentRule)) {
// currentAnnotation.setAlignment(maxAlignment);
// context.write(currentRule, currentAnnotation);
// context.progress();
// }
// }
// }
//
// private static boolean isUnigramRule(RuleWritable rule) {
// if (rule.source.length == 1) return !Vocabulary.nt(rule.source[0]);
// return rule.target.length == 1 && !Vocabulary.nt(rule.target[0]);
// }
// }
// Path: src/edu/jhu/thrax/hadoop/jobs/ExtractionJob.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.AlignedRuleWritable;
import edu.jhu.thrax.hadoop.datatypes.Annotation;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.extraction.ExtractionCombiner;
import edu.jhu.thrax.hadoop.extraction.ExtractionMapper;
import edu.jhu.thrax.hadoop.extraction.ExtractionReducer;
package edu.jhu.thrax.hadoop.jobs;
public class ExtractionJob implements ThraxJob {
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
result.add(VocabularyJob.class);
return result;
}
public Job getJob(Configuration conf) throws IOException {
Job job = new Job(conf, "extraction");
job.setJarByClass(ExtractionMapper.class);
job.setMapperClass(ExtractionMapper.class);
job.setCombinerClass(ExtractionCombiner.class); | job.setReducerClass(ExtractionReducer.class); |
jweese/thrax | src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java | // Path: src/edu/jhu/thrax/hadoop/features/WordLexicalProbabilityCalculator.java
// public class WordLexicalProbabilityCalculator extends Configured {
// public static final long UNALIGNED = 0x0000000000000000L;
// public static final long MARGINAL = 0x0000000000000000L;
//
// public static class Map extends Mapper<LongWritable, Text, LongWritable, IntWritable> {
// private HashMap<Long, Integer> counts = new HashMap<Long, Integer>();
// private boolean sourceParsed;
// private boolean targetParsed;
// private boolean reverse;
// private boolean sourceGivenTarget;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
//
// sourceParsed = conf.getBoolean("thrax.source-is-parsed", false);
// targetParsed = conf.getBoolean("thrax.target-is-parsed", false);
// reverse = conf.getBoolean("thrax.reverse", false);
// sourceGivenTarget = conf.getBoolean(WordLexprobJob.SOURCE_GIVEN_TARGET, false);
// }
//
// public void map(LongWritable key, Text value, Context context) throws IOException,
// InterruptedException {
// counts.clear();
// String line = value.toString();
// AlignedSentencePair sentencePair;
// try {
// sentencePair =
// InputUtilities.alignedSentencePair(line, sourceParsed, targetParsed,
// !(reverse ^ sourceGivenTarget));
// } catch (MalformedInputException e) {
// context.getCounter("input errors", e.getMessage()).increment(1);
// return;
// }
// int[] source = sentencePair.source;
// int[] target = sentencePair.target;
// Alignment alignment = sentencePair.alignment;
//
// for (int i = 0; i < source.length; i++) {
// int src = source[i];
// if (alignment.sourceIndexIsAligned(i)) {
// Iterator<Integer> target_indices = alignment.targetIndicesAlignedTo(i);
// while (target_indices.hasNext()) {
// int tgt = target[target_indices.next()];
// long pair = ((long) tgt << 32) + src;
// long marginal = ((long) tgt << 32) + MARGINAL;
// counts.put(pair, counts.containsKey(pair) ? counts.get(pair) + 1 : 1);
// counts.put(marginal, counts.containsKey(marginal) ? counts.get(marginal) + 1 : 1);
// }
// } else {
// long pair = UNALIGNED | ((long) src);
// long marginal = UNALIGNED;
// counts.put(pair, counts.containsKey(pair) ? counts.get(pair) + 1 : 1);
// counts.put(marginal, counts.containsKey(marginal) ? counts.get(marginal) + 1 : 1);
// }
// }
// for (long pair : counts.keySet())
// context.write(new LongWritable(pair), new IntWritable(counts.get(pair)));
// }
// }
//
// public static class Reduce
// extends Reducer<LongWritable, IntWritable, LongWritable, FloatWritable> {
// private int current = -1;
// private int marginalCount;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
//
// // TODO: remove unnecessary vocabulary loads?
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// }
//
// protected void reduce(LongWritable key, Iterable<IntWritable> values, Context context)
// throws IOException, InterruptedException {
// long pair = key.get();
// int tgt = (int) (pair >> 32);
// int src = (int) (pair & 0xFFFFFFFFL);
//
// if (tgt != current) {
// if (src != MARGINAL) throw new RuntimeException("Sorting something before marginal.");
// current = tgt;
// marginalCount = 0;
// for (IntWritable x : values)
// marginalCount += x.get();
// return;
// }
// // Control only gets here if we are using the same marginal
// int my_count = 0;
// for (IntWritable x : values)
// my_count += x.get();
// context.write(key, new FloatWritable(my_count / (float) marginalCount));
// }
// }
//
// public static class Partition extends Partitioner<LongWritable, IntWritable> {
// public int getPartition(LongWritable key, IntWritable value, int numPartitions) {
// return ((int) (key.get() >> 32) & Integer.MAX_VALUE) % numPartitions;
// }
// }
// }
| import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import edu.jhu.thrax.hadoop.features.WordLexicalProbabilityCalculator; | package edu.jhu.thrax.hadoop.jobs;
public abstract class WordLexprobJob implements ThraxJob {
public static final String SOURCE_GIVEN_TARGET = "thrax.__wordlexprob_sgt";
private boolean isSourceGivenTarget;
public WordLexprobJob(boolean isSrcGivenTgt) {
isSourceGivenTarget = isSrcGivenTgt;
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
result.add(VocabularyJob.class);
return result;
}
public Job getJob(Configuration conf) throws IOException {
Configuration theConf = new Configuration(conf);
theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget);
Job job = new Job(theConf, getName()); | // Path: src/edu/jhu/thrax/hadoop/features/WordLexicalProbabilityCalculator.java
// public class WordLexicalProbabilityCalculator extends Configured {
// public static final long UNALIGNED = 0x0000000000000000L;
// public static final long MARGINAL = 0x0000000000000000L;
//
// public static class Map extends Mapper<LongWritable, Text, LongWritable, IntWritable> {
// private HashMap<Long, Integer> counts = new HashMap<Long, Integer>();
// private boolean sourceParsed;
// private boolean targetParsed;
// private boolean reverse;
// private boolean sourceGivenTarget;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
//
// sourceParsed = conf.getBoolean("thrax.source-is-parsed", false);
// targetParsed = conf.getBoolean("thrax.target-is-parsed", false);
// reverse = conf.getBoolean("thrax.reverse", false);
// sourceGivenTarget = conf.getBoolean(WordLexprobJob.SOURCE_GIVEN_TARGET, false);
// }
//
// public void map(LongWritable key, Text value, Context context) throws IOException,
// InterruptedException {
// counts.clear();
// String line = value.toString();
// AlignedSentencePair sentencePair;
// try {
// sentencePair =
// InputUtilities.alignedSentencePair(line, sourceParsed, targetParsed,
// !(reverse ^ sourceGivenTarget));
// } catch (MalformedInputException e) {
// context.getCounter("input errors", e.getMessage()).increment(1);
// return;
// }
// int[] source = sentencePair.source;
// int[] target = sentencePair.target;
// Alignment alignment = sentencePair.alignment;
//
// for (int i = 0; i < source.length; i++) {
// int src = source[i];
// if (alignment.sourceIndexIsAligned(i)) {
// Iterator<Integer> target_indices = alignment.targetIndicesAlignedTo(i);
// while (target_indices.hasNext()) {
// int tgt = target[target_indices.next()];
// long pair = ((long) tgt << 32) + src;
// long marginal = ((long) tgt << 32) + MARGINAL;
// counts.put(pair, counts.containsKey(pair) ? counts.get(pair) + 1 : 1);
// counts.put(marginal, counts.containsKey(marginal) ? counts.get(marginal) + 1 : 1);
// }
// } else {
// long pair = UNALIGNED | ((long) src);
// long marginal = UNALIGNED;
// counts.put(pair, counts.containsKey(pair) ? counts.get(pair) + 1 : 1);
// counts.put(marginal, counts.containsKey(marginal) ? counts.get(marginal) + 1 : 1);
// }
// }
// for (long pair : counts.keySet())
// context.write(new LongWritable(pair), new IntWritable(counts.get(pair)));
// }
// }
//
// public static class Reduce
// extends Reducer<LongWritable, IntWritable, LongWritable, FloatWritable> {
// private int current = -1;
// private int marginalCount;
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
//
// // TODO: remove unnecessary vocabulary loads?
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// }
//
// protected void reduce(LongWritable key, Iterable<IntWritable> values, Context context)
// throws IOException, InterruptedException {
// long pair = key.get();
// int tgt = (int) (pair >> 32);
// int src = (int) (pair & 0xFFFFFFFFL);
//
// if (tgt != current) {
// if (src != MARGINAL) throw new RuntimeException("Sorting something before marginal.");
// current = tgt;
// marginalCount = 0;
// for (IntWritable x : values)
// marginalCount += x.get();
// return;
// }
// // Control only gets here if we are using the same marginal
// int my_count = 0;
// for (IntWritable x : values)
// my_count += x.get();
// context.write(key, new FloatWritable(my_count / (float) marginalCount));
// }
// }
//
// public static class Partition extends Partitioner<LongWritable, IntWritable> {
// public int getPartition(LongWritable key, IntWritable value, int numPartitions) {
// return ((int) (key.get() >> 32) & Integer.MAX_VALUE) % numPartitions;
// }
// }
// }
// Path: src/edu/jhu/thrax/hadoop/jobs/WordLexprobJob.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import edu.jhu.thrax.hadoop.features.WordLexicalProbabilityCalculator;
package edu.jhu.thrax.hadoop.jobs;
public abstract class WordLexprobJob implements ThraxJob {
public static final String SOURCE_GIVEN_TARGET = "thrax.__wordlexprob_sgt";
private boolean isSourceGivenTarget;
public WordLexprobJob(boolean isSrcGivenTgt) {
isSourceGivenTarget = isSrcGivenTgt;
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
Set<Class<? extends ThraxJob>> result = new HashSet<Class<? extends ThraxJob>>();
result.add(VocabularyJob.class);
return result;
}
public Job getJob(Configuration conf) throws IOException {
Configuration theConf = new Configuration(conf);
theConf.setBoolean(SOURCE_GIVEN_TARGET, isSourceGivenTarget);
Job job = new Job(theConf, getName()); | job.setJarByClass(WordLexicalProbabilityCalculator.class); |
jweese/thrax | src/edu/jhu/thrax/hadoop/jobs/FeatureCollectionJob.java | // Path: src/edu/jhu/thrax/hadoop/paraphrasing/FeatureCollectionReducer.java
// public class FeatureCollectionReducer
// extends Reducer<RuleWritable, FeaturePair, RuleWritable, FeatureMap> {
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// }
//
// protected void reduce(RuleWritable key, Iterable<FeaturePair> values, Context context)
// throws IOException, InterruptedException {
// FeatureMap features = new FeatureMap();
// for (FeaturePair fp : values)
// features.put(fp.key, fp.val.get());
// context.write(key, features);
// }
// }
| import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.FeatureMap;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.paraphrasing.FeatureCollectionReducer; | package edu.jhu.thrax.hadoop.jobs;
public class FeatureCollectionJob implements ThraxJob {
private static HashSet<Class<? extends ThraxJob>> prereqs =
new HashSet<Class<? extends ThraxJob>>();
private static HashSet<String> prereq_names = new HashSet<String>();
public static void addPrerequisite(Class<? extends ThraxJob> c) {
prereqs.add(c);
try {
ThraxJob prereq;
prereq = c.newInstance();
prereq_names.add(prereq.getOutputSuffix());
} catch (Exception e) {
e.printStackTrace();
}
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
prereqs.add(ExtractionJob.class);
return prereqs;
}
public Job getJob(Configuration conf) throws IOException {
Job job = new Job(conf, "collect");
String workDir = conf.get("thrax.work-dir");
| // Path: src/edu/jhu/thrax/hadoop/paraphrasing/FeatureCollectionReducer.java
// public class FeatureCollectionReducer
// extends Reducer<RuleWritable, FeaturePair, RuleWritable, FeatureMap> {
//
// protected void setup(Context context) throws IOException, InterruptedException {
// Configuration conf = context.getConfiguration();
// String vocabulary_path = conf.getRaw("thrax.work-dir") + "vocabulary/part-*";
// Vocabulary.initialize(conf, vocabulary_path);
// }
//
// protected void reduce(RuleWritable key, Iterable<FeaturePair> values, Context context)
// throws IOException, InterruptedException {
// FeatureMap features = new FeatureMap();
// for (FeaturePair fp : values)
// features.put(fp.key, fp.val.get());
// context.write(key, features);
// }
// }
// Path: src/edu/jhu/thrax/hadoop/jobs/FeatureCollectionJob.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import edu.jhu.thrax.hadoop.datatypes.FeatureMap;
import edu.jhu.thrax.hadoop.datatypes.FeaturePair;
import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.hadoop.paraphrasing.FeatureCollectionReducer;
package edu.jhu.thrax.hadoop.jobs;
public class FeatureCollectionJob implements ThraxJob {
private static HashSet<Class<? extends ThraxJob>> prereqs =
new HashSet<Class<? extends ThraxJob>>();
private static HashSet<String> prereq_names = new HashSet<String>();
public static void addPrerequisite(Class<? extends ThraxJob> c) {
prereqs.add(c);
try {
ThraxJob prereq;
prereq = c.newInstance();
prereq_names.add(prereq.getOutputSuffix());
} catch (Exception e) {
e.printStackTrace();
}
}
public Set<Class<? extends ThraxJob>> getPrerequisites() {
prereqs.add(ExtractionJob.class);
return prereqs;
}
public Job getJob(Configuration conf) throws IOException {
Job job = new Job(conf, "collect");
String workDir = conf.get("thrax.work-dir");
| job.setJarByClass(FeatureCollectionReducer.class); |
eriq-augustine/jocr | src/com/eriqaugustine/ocr/image/ImageText.java | // Path: src/com/eriqaugustine/ocr/utils/ListUtils.java
// public class ListUtils {
// public static <T> void append(List<T> list, T[] toAdd) {
// for (T toAddElement : toAdd) {
// list.add(toAddElement);
// }
// }
//
// public static void append(List<Integer> list, int[] toAdd) {
// for (int toAddElement : toAdd) {
// list.add(new Integer(toAddElement));
// }
// }
//
// public static int[] toIntArray(List<Integer> list) {
// int[] rtn = new int[list.size()];
// for (int i = 0; i < list.size(); i++) {
// rtn[i] = list.get(i).intValue();
// }
// return rtn;
// }
//
// /**
// * Fill |base| with elements from |content|.
// * Start filling |base| at offset.
// * |base| must be large enough to fit all of |content|.
// */
// public static <T> void fill(T[] base, T[]content, int offset) {
// assert(base.length - offset + 1 >= content.length);
//
// for (int i = 0; i < content.length; i++) {
// base[i + offset] = content[i];
// }
// }
// }
| import com.eriqaugustine.ocr.utils.ListUtils;
import java.util.ArrayList;
import java.util.List; | package com.eriqaugustine.ocr.image;
/**
* Hold the image and text for a specific character.
* We want to use this intermediary container so we can do pre and post classification heuristics.
* It is the caller's responsibility to check for null and sizes.
*/
public class ImageText {
public List<WrapImage> images;
public String text;
public ImageText() {
images = new ArrayList<WrapImage>();
text = null;
}
public ImageText(WrapImage image) {
this();
images.add(image);
}
public ImageText(List<WrapImage> images) {
this();
this.images.addAll(images);
}
public ImageText(WrapImage[] images) {
this(); | // Path: src/com/eriqaugustine/ocr/utils/ListUtils.java
// public class ListUtils {
// public static <T> void append(List<T> list, T[] toAdd) {
// for (T toAddElement : toAdd) {
// list.add(toAddElement);
// }
// }
//
// public static void append(List<Integer> list, int[] toAdd) {
// for (int toAddElement : toAdd) {
// list.add(new Integer(toAddElement));
// }
// }
//
// public static int[] toIntArray(List<Integer> list) {
// int[] rtn = new int[list.size()];
// for (int i = 0; i < list.size(); i++) {
// rtn[i] = list.get(i).intValue();
// }
// return rtn;
// }
//
// /**
// * Fill |base| with elements from |content|.
// * Start filling |base| at offset.
// * |base| must be large enough to fit all of |content|.
// */
// public static <T> void fill(T[] base, T[]content, int offset) {
// assert(base.length - offset + 1 >= content.length);
//
// for (int i = 0; i < content.length; i++) {
// base[i + offset] = content[i];
// }
// }
// }
// Path: src/com/eriqaugustine/ocr/image/ImageText.java
import com.eriqaugustine.ocr.utils.ListUtils;
import java.util.ArrayList;
import java.util.List;
package com.eriqaugustine.ocr.image;
/**
* Hold the image and text for a specific character.
* We want to use this intermediary container so we can do pre and post classification heuristics.
* It is the caller's responsibility to check for null and sizes.
*/
public class ImageText {
public List<WrapImage> images;
public String text;
public ImageText() {
images = new ArrayList<WrapImage>();
text = null;
}
public ImageText(WrapImage image) {
this();
images.add(image);
}
public ImageText(List<WrapImage> images) {
this();
this.images.addAll(images);
}
public ImageText(WrapImage[] images) {
this(); | ListUtils.append(this.images, images); |
eriq-augustine/jocr | src/com/eriqaugustine/ocr/image/BubbleDetector.java | // Path: src/com/eriqaugustine/ocr/image/WrapImage.java
// public static class Pixel {
// public byte red;
// public byte green;
// public byte blue;
//
// public Pixel(byte red, byte green, byte blue) {
// this.red = red;
// this.green = green;
// this.blue = blue;
// }
//
// /**
// * Just a white pixel.
// */
// public Pixel() {
// this(0xFF, 0xFF, 0xFF);
// }
//
// public Pixel(int red, int green, int blue) {
// this((byte)red, (byte)green, (byte)blue);
// }
//
// public Pixel(Pixel pixel) {
// this(pixel.red, pixel.green, pixel.blue);
// }
//
// public Pixel(Color color) {
// this(color.getRed(), color.getGreen(), color.getBlue());
// }
//
// public Pixel(PixelPacket pixelPacket) {
// this(pixelPacket.getRed(), pixelPacket.getGreen(), pixelPacket.getBlue());
// }
//
// /**
// * Get the average intensity value for this pixel.
// * Return is byte, and not float on purpose.
// */
// public byte average() {
// return (byte)((red + green + blue) / 3);
// }
// }
//
// Path: src/com/eriqaugustine/ocr/utils/ColorUtils.java
// public class ColorUtils {
// private static ColorGenerator internalColorGen = new ColorGenerator();
//
// private static final double GOLDEN_RATIO_CONJUGATE = 0.618033988749895;
//
// private static final double SATURATION = 0.5;
//
// private static final double BRIGHTNESS = 0.95;
//
// /**
// * Testing main.
// */
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// System.out.println(nextColor());
// }
// }
//
// /**
// * Use the internal color generator to get a new color.
// */
// public static Color nextColor() {
// return internalColorGen.next();
// }
//
// /**
// * Generates random, readable colors.
// */
// public static class ColorGenerator {
// private Random rand;
//
// public ColorGenerator() {
// rand = new Random();
// }
//
// /**
// * Use HSV (HSB) instead of RGB to generate random colors so we can use a
// * constant saturation and value (brightness).
// */
// public Color next() {
// double hue = (rand.nextDouble() + GOLDEN_RATIO_CONJUGATE) % 1;
// return Color.getHSBColor((float)hue, (float)SATURATION, (float)BRIGHTNESS);
// }
// }
// }
| import static com.eriqaugustine.ocr.image.WrapImage.Pixel;
import com.eriqaugustine.ocr.utils.ColorUtils;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List; | package com.eriqaugustine.ocr.image;
/**
* The interface to detecting callouts (speech bubbles).
*/
public abstract class BubbleDetector {
/**
* Get the raw blobs that represent the bubbles.
*/
public abstract List<Blob> getBubbles(WrapImage image);
public abstract BubbleInfo[] extractBubblesWithInfo(WrapImage image);
/**
* Extract the pixels for each bubble and convert them to an image.
*/
public WrapImage[] extractBubbles(WrapImage image) {
BubbleInfo[] bubbles = extractBubblesWithInfo(image);
WrapImage[] images = new WrapImage[bubbles.length];
for (int i = 0; i < bubbles.length; i++) {
images[i] = bubbles[i].image;
}
return images;
}
public WrapImage colorBubbles(WrapImage image) {
List<Blob> bubbles = getBubbles(image);
return colorBubbles(image, bubbles);
}
public WrapImage colorBubbles(WrapImage image, BubbleInfo[] bubbleInfos) {
List<Blob> blobs = new ArrayList<Blob>(bubbleInfos.length);
for (BubbleInfo info : bubbleInfos) {
blobs.add(info.blob);
}
return colorBubbles(image, blobs);
}
/**
* Color all the text bubbles in a copy of |image|.
* It is assumed that |image| has been edged, and that it has
* only two colors, true black and true white.
* White pixels are edges.
*/
public WrapImage colorBubbles(WrapImage image, List<Blob> bubbles) { | // Path: src/com/eriqaugustine/ocr/image/WrapImage.java
// public static class Pixel {
// public byte red;
// public byte green;
// public byte blue;
//
// public Pixel(byte red, byte green, byte blue) {
// this.red = red;
// this.green = green;
// this.blue = blue;
// }
//
// /**
// * Just a white pixel.
// */
// public Pixel() {
// this(0xFF, 0xFF, 0xFF);
// }
//
// public Pixel(int red, int green, int blue) {
// this((byte)red, (byte)green, (byte)blue);
// }
//
// public Pixel(Pixel pixel) {
// this(pixel.red, pixel.green, pixel.blue);
// }
//
// public Pixel(Color color) {
// this(color.getRed(), color.getGreen(), color.getBlue());
// }
//
// public Pixel(PixelPacket pixelPacket) {
// this(pixelPacket.getRed(), pixelPacket.getGreen(), pixelPacket.getBlue());
// }
//
// /**
// * Get the average intensity value for this pixel.
// * Return is byte, and not float on purpose.
// */
// public byte average() {
// return (byte)((red + green + blue) / 3);
// }
// }
//
// Path: src/com/eriqaugustine/ocr/utils/ColorUtils.java
// public class ColorUtils {
// private static ColorGenerator internalColorGen = new ColorGenerator();
//
// private static final double GOLDEN_RATIO_CONJUGATE = 0.618033988749895;
//
// private static final double SATURATION = 0.5;
//
// private static final double BRIGHTNESS = 0.95;
//
// /**
// * Testing main.
// */
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// System.out.println(nextColor());
// }
// }
//
// /**
// * Use the internal color generator to get a new color.
// */
// public static Color nextColor() {
// return internalColorGen.next();
// }
//
// /**
// * Generates random, readable colors.
// */
// public static class ColorGenerator {
// private Random rand;
//
// public ColorGenerator() {
// rand = new Random();
// }
//
// /**
// * Use HSV (HSB) instead of RGB to generate random colors so we can use a
// * constant saturation and value (brightness).
// */
// public Color next() {
// double hue = (rand.nextDouble() + GOLDEN_RATIO_CONJUGATE) % 1;
// return Color.getHSBColor((float)hue, (float)SATURATION, (float)BRIGHTNESS);
// }
// }
// }
// Path: src/com/eriqaugustine/ocr/image/BubbleDetector.java
import static com.eriqaugustine.ocr.image.WrapImage.Pixel;
import com.eriqaugustine.ocr.utils.ColorUtils;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
package com.eriqaugustine.ocr.image;
/**
* The interface to detecting callouts (speech bubbles).
*/
public abstract class BubbleDetector {
/**
* Get the raw blobs that represent the bubbles.
*/
public abstract List<Blob> getBubbles(WrapImage image);
public abstract BubbleInfo[] extractBubblesWithInfo(WrapImage image);
/**
* Extract the pixels for each bubble and convert them to an image.
*/
public WrapImage[] extractBubbles(WrapImage image) {
BubbleInfo[] bubbles = extractBubblesWithInfo(image);
WrapImage[] images = new WrapImage[bubbles.length];
for (int i = 0; i < bubbles.length; i++) {
images[i] = bubbles[i].image;
}
return images;
}
public WrapImage colorBubbles(WrapImage image) {
List<Blob> bubbles = getBubbles(image);
return colorBubbles(image, bubbles);
}
public WrapImage colorBubbles(WrapImage image, BubbleInfo[] bubbleInfos) {
List<Blob> blobs = new ArrayList<Blob>(bubbleInfos.length);
for (BubbleInfo info : bubbleInfos) {
blobs.add(info.blob);
}
return colorBubbles(image, blobs);
}
/**
* Color all the text bubbles in a copy of |image|.
* It is assumed that |image| has been edged, and that it has
* only two colors, true black and true white.
* White pixels are edges.
*/
public WrapImage colorBubbles(WrapImage image, List<Blob> bubbles) { | Pixel[] pixels = image.getPixels(); |
eriq-augustine/jocr | src/com/eriqaugustine/ocr/image/BubbleDetector.java | // Path: src/com/eriqaugustine/ocr/image/WrapImage.java
// public static class Pixel {
// public byte red;
// public byte green;
// public byte blue;
//
// public Pixel(byte red, byte green, byte blue) {
// this.red = red;
// this.green = green;
// this.blue = blue;
// }
//
// /**
// * Just a white pixel.
// */
// public Pixel() {
// this(0xFF, 0xFF, 0xFF);
// }
//
// public Pixel(int red, int green, int blue) {
// this((byte)red, (byte)green, (byte)blue);
// }
//
// public Pixel(Pixel pixel) {
// this(pixel.red, pixel.green, pixel.blue);
// }
//
// public Pixel(Color color) {
// this(color.getRed(), color.getGreen(), color.getBlue());
// }
//
// public Pixel(PixelPacket pixelPacket) {
// this(pixelPacket.getRed(), pixelPacket.getGreen(), pixelPacket.getBlue());
// }
//
// /**
// * Get the average intensity value for this pixel.
// * Return is byte, and not float on purpose.
// */
// public byte average() {
// return (byte)((red + green + blue) / 3);
// }
// }
//
// Path: src/com/eriqaugustine/ocr/utils/ColorUtils.java
// public class ColorUtils {
// private static ColorGenerator internalColorGen = new ColorGenerator();
//
// private static final double GOLDEN_RATIO_CONJUGATE = 0.618033988749895;
//
// private static final double SATURATION = 0.5;
//
// private static final double BRIGHTNESS = 0.95;
//
// /**
// * Testing main.
// */
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// System.out.println(nextColor());
// }
// }
//
// /**
// * Use the internal color generator to get a new color.
// */
// public static Color nextColor() {
// return internalColorGen.next();
// }
//
// /**
// * Generates random, readable colors.
// */
// public static class ColorGenerator {
// private Random rand;
//
// public ColorGenerator() {
// rand = new Random();
// }
//
// /**
// * Use HSV (HSB) instead of RGB to generate random colors so we can use a
// * constant saturation and value (brightness).
// */
// public Color next() {
// double hue = (rand.nextDouble() + GOLDEN_RATIO_CONJUGATE) % 1;
// return Color.getHSBColor((float)hue, (float)SATURATION, (float)BRIGHTNESS);
// }
// }
// }
| import static com.eriqaugustine.ocr.image.WrapImage.Pixel;
import com.eriqaugustine.ocr.utils.ColorUtils;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List; |
/**
* Color all the text bubbles in a copy of |image|.
* It is assumed that |image| has been edged, and that it has
* only two colors, true black and true white.
* White pixels are edges.
*/
public WrapImage colorBubbles(WrapImage image, List<Blob> bubbles) {
Pixel[] pixels = image.getPixels();
// Fill the blobs.
fillBlobs(pixels, bubbles, null);
WrapImage newImage = WrapImage.getImageFromPixels(pixels, image.width(), image.height());
return newImage;
}
/**
* Modify |pixels| to fill in all the blobs as red.
*/
private void fillBlobs(Pixel[] pixels, List<Blob> blobs) {
fillBlobs(pixels, blobs, new Color(255, 0, 0));
}
/**
* If |color| is null, then pick a different colot every time.
*/
private void fillBlobs(Pixel[] pixels, List<Blob> blobs, Color color) {
for (Blob blob : blobs) { | // Path: src/com/eriqaugustine/ocr/image/WrapImage.java
// public static class Pixel {
// public byte red;
// public byte green;
// public byte blue;
//
// public Pixel(byte red, byte green, byte blue) {
// this.red = red;
// this.green = green;
// this.blue = blue;
// }
//
// /**
// * Just a white pixel.
// */
// public Pixel() {
// this(0xFF, 0xFF, 0xFF);
// }
//
// public Pixel(int red, int green, int blue) {
// this((byte)red, (byte)green, (byte)blue);
// }
//
// public Pixel(Pixel pixel) {
// this(pixel.red, pixel.green, pixel.blue);
// }
//
// public Pixel(Color color) {
// this(color.getRed(), color.getGreen(), color.getBlue());
// }
//
// public Pixel(PixelPacket pixelPacket) {
// this(pixelPacket.getRed(), pixelPacket.getGreen(), pixelPacket.getBlue());
// }
//
// /**
// * Get the average intensity value for this pixel.
// * Return is byte, and not float on purpose.
// */
// public byte average() {
// return (byte)((red + green + blue) / 3);
// }
// }
//
// Path: src/com/eriqaugustine/ocr/utils/ColorUtils.java
// public class ColorUtils {
// private static ColorGenerator internalColorGen = new ColorGenerator();
//
// private static final double GOLDEN_RATIO_CONJUGATE = 0.618033988749895;
//
// private static final double SATURATION = 0.5;
//
// private static final double BRIGHTNESS = 0.95;
//
// /**
// * Testing main.
// */
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// System.out.println(nextColor());
// }
// }
//
// /**
// * Use the internal color generator to get a new color.
// */
// public static Color nextColor() {
// return internalColorGen.next();
// }
//
// /**
// * Generates random, readable colors.
// */
// public static class ColorGenerator {
// private Random rand;
//
// public ColorGenerator() {
// rand = new Random();
// }
//
// /**
// * Use HSV (HSB) instead of RGB to generate random colors so we can use a
// * constant saturation and value (brightness).
// */
// public Color next() {
// double hue = (rand.nextDouble() + GOLDEN_RATIO_CONJUGATE) % 1;
// return Color.getHSBColor((float)hue, (float)SATURATION, (float)BRIGHTNESS);
// }
// }
// }
// Path: src/com/eriqaugustine/ocr/image/BubbleDetector.java
import static com.eriqaugustine.ocr.image.WrapImage.Pixel;
import com.eriqaugustine.ocr.utils.ColorUtils;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
/**
* Color all the text bubbles in a copy of |image|.
* It is assumed that |image| has been edged, and that it has
* only two colors, true black and true white.
* White pixels are edges.
*/
public WrapImage colorBubbles(WrapImage image, List<Blob> bubbles) {
Pixel[] pixels = image.getPixels();
// Fill the blobs.
fillBlobs(pixels, bubbles, null);
WrapImage newImage = WrapImage.getImageFromPixels(pixels, image.width(), image.height());
return newImage;
}
/**
* Modify |pixels| to fill in all the blobs as red.
*/
private void fillBlobs(Pixel[] pixels, List<Blob> blobs) {
fillBlobs(pixels, blobs, new Color(255, 0, 0));
}
/**
* If |color| is null, then pick a different colot every time.
*/
private void fillBlobs(Pixel[] pixels, List<Blob> blobs, Color color) {
for (Blob blob : blobs) { | Color activeColor = color != null ? color : ColorUtils.nextColor(); |
oliviercailloux/java-course | Java EE/CDI/sample-service-dependency/src/main/java/io/github/oliviercailloux/sample_service_dependency/Voter.java | // Path: Java EE/CDI/sample-service-dependency/src/main/java/io/github/oliviercailloux/sample_service_dependency/service/Randomizer.java
// public class Randomizer implements IRandomizer {
// @Override
// public String pickCandidate() {
// return "Batman";
// }
// }
| import io.github.oliviercailloux.sample_service_dependency.service.IRandomizer;
import io.github.oliviercailloux.sample_service_dependency.service.Randomizer; | package io.github.oliviercailloux.sample_service_dependency;
public class Voter {
public String castVote() { | // Path: Java EE/CDI/sample-service-dependency/src/main/java/io/github/oliviercailloux/sample_service_dependency/service/Randomizer.java
// public class Randomizer implements IRandomizer {
// @Override
// public String pickCandidate() {
// return "Batman";
// }
// }
// Path: Java EE/CDI/sample-service-dependency/src/main/java/io/github/oliviercailloux/sample_service_dependency/Voter.java
import io.github.oliviercailloux.sample_service_dependency.service.IRandomizer;
import io.github.oliviercailloux.sample_service_dependency.service.Randomizer;
package io.github.oliviercailloux.sample_service_dependency;
public class Voter {
public String castVote() { | final IRandomizer randomizer = new Randomizer(); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java | // Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/DrawPage.java
// public class DrawPage {
// private final HtmlPage page;
//
// public DrawPage(HtmlPage page) {
// this.page = page;
// verify();
// }
//
// private void verify() {
// assertThat(page.getBody().asNormalizedText())
// .describedAs("successful draw")
// .contains("The lucky numbers are");
// }
//
// public LogoutPage logout() throws IOException {
// return new LogoutPage(page.getAnchorByName("logout").click());
// }
//
// public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
// throws IOException {
// WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
// List<NameValuePair> parameters = new ArrayList<>();
// parameters.add(new NameValuePair("date", "2015-01-01"));
// request.setRequestParameters(parameters);
// return new LoginPage<>(webClient.getPage(request), DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
| import com.gargoylesoftware.htmlunit.WebClient;
import de.ahus1.lottery.adapter.dropwizard.pages.DrawPage;
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplicationTest {
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
new File("../config.yml").getAbsolutePath()
);
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/DrawPage.java
// public class DrawPage {
// private final HtmlPage page;
//
// public DrawPage(HtmlPage page) {
// this.page = page;
// verify();
// }
//
// private void verify() {
// assertThat(page.getBody().asNormalizedText())
// .describedAs("successful draw")
// .contains("The lucky numbers are");
// }
//
// public LogoutPage logout() throws IOException {
// return new LogoutPage(page.getAnchorByName("logout").click());
// }
//
// public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
// throws IOException {
// WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
// List<NameValuePair> parameters = new ArrayList<>();
// parameters.add(new NameValuePair("date", "2015-01-01"));
// request.setRequestParameters(parameters);
// return new LoginPage<>(webClient.getPage(request), DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
// Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java
import com.gargoylesoftware.htmlunit.WebClient;
import de.ahus1.lottery.adapter.dropwizard.pages.DrawPage;
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplicationTest {
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
new File("../config.yml").getAbsolutePath()
);
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort()); | StartPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java | // Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/DrawPage.java
// public class DrawPage {
// private final HtmlPage page;
//
// public DrawPage(HtmlPage page) {
// this.page = page;
// verify();
// }
//
// private void verify() {
// assertThat(page.getBody().asNormalizedText())
// .describedAs("successful draw")
// .contains("The lucky numbers are");
// }
//
// public LogoutPage logout() throws IOException {
// return new LogoutPage(page.getAnchorByName("logout").click());
// }
//
// public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
// throws IOException {
// WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
// List<NameValuePair> parameters = new ArrayList<>();
// parameters.add(new NameValuePair("date", "2015-01-01"));
// request.setRequestParameters(parameters);
// return new LoginPage<>(webClient.getPage(request), DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
| import com.gargoylesoftware.htmlunit.WebClient;
import de.ahus1.lottery.adapter.dropwizard.pages.DrawPage;
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplicationTest {
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
new File("../config.yml").getAbsolutePath()
);
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort());
StartPage
.openWithoutLogin(webClient, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
}
@Test
@Ignore("No longer supported starting with Dropwizard 2.0 - see README.adoc at top of project")
public void shouldLoginFromPost() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/DrawPage.java
// public class DrawPage {
// private final HtmlPage page;
//
// public DrawPage(HtmlPage page) {
// this.page = page;
// verify();
// }
//
// private void verify() {
// assertThat(page.getBody().asNormalizedText())
// .describedAs("successful draw")
// .contains("The lucky numbers are");
// }
//
// public LogoutPage logout() throws IOException {
// return new LogoutPage(page.getAnchorByName("logout").click());
// }
//
// public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
// throws IOException {
// WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
// List<NameValuePair> parameters = new ArrayList<>();
// parameters.add(new NameValuePair("date", "2015-01-01"));
// request.setRequestParameters(parameters);
// return new LoginPage<>(webClient.getPage(request), DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
// Path: keycloak-dropwizard-jetty/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java
import com.gargoylesoftware.htmlunit.WebClient;
import de.ahus1.lottery.adapter.dropwizard.pages.DrawPage;
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplicationTest {
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
new File("../config.yml").getAbsolutePath()
);
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort());
StartPage
.openWithoutLogin(webClient, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
}
@Test
@Ignore("No longer supported starting with Dropwizard 2.0 - see README.adoc at top of project")
public void shouldLoginFromPost() throws IOException, ReflectiveOperationException {
try (WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false);
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort()); | DrawPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearer/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTest {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
// Path: keycloak-dropwizard-bearer/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTest.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTest {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | StartPage |
ahus1/keycloak-dropwizard-integration | simple-war/src/main/java/de/ahus1/lottery/adapter/servlet/DrawServlet.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.lottery.domain.DrawingService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.servlet;
@WebServlet(urlPatterns = "/")
public class DrawServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/index.ftl").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LocalDate date = LocalDate.parse(request.getParameter("date")); | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: simple-war/src/main/java/de/ahus1/lottery/adapter/servlet/DrawServlet.java
import de.ahus1.lottery.domain.DrawingService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.servlet;
@WebServlet(urlPatterns = "/")
public class DrawServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/index.ftl").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LocalDate date = LocalDate.parse(request.getParameter("date")); | request.setAttribute("draw", DrawingService.drawNumbers(date)); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawBean.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
| import de.ahus1.lottery.domain.Draw;
import org.keycloak.representations.IDToken; | package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawBean {
private IDToken idToken; | // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
// Path: keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawBean.java
import de.ahus1.lottery.domain.Draw;
import org.keycloak.representations.IDToken;
package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawBean {
private IDToken idToken; | private Draw draw; |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard.resource;
// tag::ressource[]
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
// end::ressource[]
@GET
@RolesAllowed("user") | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard.resource;
// tag::ressource[]
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
// end::ressource[]
@GET
@RolesAllowed("user") | public DrawView show(@Auth User auth) { |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard.resource;
// tag::ressource[]
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
// end::ressource[]
@GET
@RolesAllowed("user")
public DrawView show(@Auth User auth) {
DrawBean bean = new DrawBean();
DrawView view = new DrawView(bean);
bean.setName(auth.getName());
return view;
}
// tag::ressource[]
@POST
@Path("/draw")
@RolesAllowed("user")
public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
DrawBean bean = new DrawBean();
LocalDate date = LocalDate.parse(dateAsString); | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard.resource;
// tag::ressource[]
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
// end::ressource[]
@GET
@RolesAllowed("user")
public DrawView show(@Auth User auth) {
DrawBean bean = new DrawBean();
DrawView view = new DrawView(bean);
bean.setName(auth.getName());
return view;
}
// tag::ressource[]
@POST
@Path("/draw")
@RolesAllowed("user")
public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
DrawBean bean = new DrawBean();
LocalDate date = LocalDate.parse(dateAsString); | bean.setDraw(DrawingService.drawNumbers(date)); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java | // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/util/DropwizardBearerTokenFilterImpl.java
// @PreMatching
// @Priority(Priorities.AUTHENTICATION)
// public class DropwizardBearerTokenFilterImpl extends JaxrsBearerTokenFilterImpl {
//
// public DropwizardBearerTokenFilterImpl(KeycloakDeployment keycloakDeployment) {
// deploymentContext = new AdapterDeploymentContext(keycloakDeployment);
// nodesRegistrationManagement = new NodesRegistrationManagement();
// }
// }
| import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import de.ahus1.lottery.adapter.dropwizard.util.DropwizardBearerTokenFilterImpl;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.jaxrs.JaxrsBearerTokenFilterImpl; | package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplication extends Application<LotteryConfiguration> {
public static void main(String[] args) throws Exception {
new LotteryApplication().run(args);
}
@Override
public String getName() {
return "lottery";
}
@Override
public void initialize(Bootstrap<LotteryConfiguration> bootstrap) {
// set up folders for static content
bootstrap.addBundle(new AssetsBundle("/assets/ajax", "/ajax", null, "ajax"));
}
@Override
public void run(LotteryConfiguration configuration, Environment environment) {
// tag::keycloak[]
KeycloakDeployment keycloakDeployment =
KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration()); | // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/util/DropwizardBearerTokenFilterImpl.java
// @PreMatching
// @Priority(Priorities.AUTHENTICATION)
// public class DropwizardBearerTokenFilterImpl extends JaxrsBearerTokenFilterImpl {
//
// public DropwizardBearerTokenFilterImpl(KeycloakDeployment keycloakDeployment) {
// deploymentContext = new AdapterDeploymentContext(keycloakDeployment);
// nodesRegistrationManagement = new NodesRegistrationManagement();
// }
// }
// Path: keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java
import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import de.ahus1.lottery.adapter.dropwizard.util.DropwizardBearerTokenFilterImpl;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.jaxrs.JaxrsBearerTokenFilterImpl;
package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplication extends Application<LotteryConfiguration> {
public static void main(String[] args) throws Exception {
new LotteryApplication().run(args);
}
@Override
public String getName() {
return "lottery";
}
@Override
public void initialize(Bootstrap<LotteryConfiguration> bootstrap) {
// set up folders for static content
bootstrap.addBundle(new AssetsBundle("/assets/ajax", "/ajax", null, "ajax"));
}
@Override
public void run(LotteryConfiguration configuration, Environment environment) {
// tag::keycloak[]
KeycloakDeployment keycloakDeployment =
KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration()); | JaxrsBearerTokenFilterImpl filter = new DropwizardBearerTokenFilterImpl(keycloakDeployment); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java | // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/util/DropwizardBearerTokenFilterImpl.java
// @PreMatching
// @Priority(Priorities.AUTHENTICATION)
// public class DropwizardBearerTokenFilterImpl extends JaxrsBearerTokenFilterImpl {
//
// public DropwizardBearerTokenFilterImpl(KeycloakDeployment keycloakDeployment) {
// deploymentContext = new AdapterDeploymentContext(keycloakDeployment);
// nodesRegistrationManagement = new NodesRegistrationManagement();
// }
// }
| import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import de.ahus1.lottery.adapter.dropwizard.util.DropwizardBearerTokenFilterImpl;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.jaxrs.JaxrsBearerTokenFilterImpl; | package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplication extends Application<LotteryConfiguration> {
public static void main(String[] args) throws Exception {
new LotteryApplication().run(args);
}
@Override
public String getName() {
return "lottery";
}
@Override
public void initialize(Bootstrap<LotteryConfiguration> bootstrap) {
// set up folders for static content
bootstrap.addBundle(new AssetsBundle("/assets/ajax", "/ajax", null, "ajax"));
}
@Override
public void run(LotteryConfiguration configuration, Environment environment) {
// tag::keycloak[]
KeycloakDeployment keycloakDeployment =
KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration());
JaxrsBearerTokenFilterImpl filter = new DropwizardBearerTokenFilterImpl(keycloakDeployment);
environment.jersey().register(filter);
// end::keycloak[]
| // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/util/DropwizardBearerTokenFilterImpl.java
// @PreMatching
// @Priority(Priorities.AUTHENTICATION)
// public class DropwizardBearerTokenFilterImpl extends JaxrsBearerTokenFilterImpl {
//
// public DropwizardBearerTokenFilterImpl(KeycloakDeployment keycloakDeployment) {
// deploymentContext = new AdapterDeploymentContext(keycloakDeployment);
// nodesRegistrationManagement = new NodesRegistrationManagement();
// }
// }
// Path: keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java
import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import de.ahus1.lottery.adapter.dropwizard.util.DropwizardBearerTokenFilterImpl;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.keycloak.jaxrs.JaxrsBearerTokenFilterImpl;
package de.ahus1.lottery.adapter.dropwizard;
public class LotteryApplication extends Application<LotteryConfiguration> {
public static void main(String[] args) throws Exception {
new LotteryApplication().run(args);
}
@Override
public String getName() {
return "lottery";
}
@Override
public void initialize(Bootstrap<LotteryConfiguration> bootstrap) {
// set up folders for static content
bootstrap.addBundle(new AssetsBundle("/assets/ajax", "/ajax", null, "ajax"));
}
@Override
public void run(LotteryConfiguration configuration, Environment environment) {
// tag::keycloak[]
KeycloakDeployment keycloakDeployment =
KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration());
JaxrsBearerTokenFilterImpl filter = new DropwizardBearerTokenFilterImpl(keycloakDeployment);
environment.jersey().register(filter);
// end::keycloak[]
| environment.jersey().register(new DrawRessource()); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawResponse.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
| import com.fasterxml.jackson.annotation.JsonFormat;
import de.ahus1.lottery.domain.Draw;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set; | package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawResponse {
private Set<Integer> numbers;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate date;
public DrawResponse() {
}
| // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawResponse.java
import com.fasterxml.jackson.annotation.JsonFormat;
import de.ahus1.lottery.domain.Draw;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawResponse {
private Set<Integer> numbers;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate date;
public DrawResponse() {
}
| public DrawResponse(Draw draw) { |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/WhoamiRessource.java | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
| import de.ahus1.keycloak.dropwizard.User;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.*; | package de.ahus1.lottery.adapter.dropwizard.resource;
/**
* Ressourcce to show the name of the user ("Who am I").
* This is a simple resource that offers a GET request to test the redirect on accessing a protected resource.
* This will work only in non-bearer-only mode.
*/
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class WhoamiRessource {
private final boolean logoutShouldRemoveCookie;
public WhoamiRessource(boolean logoutShouldRemoveCookie) {
this.logoutShouldRemoveCookie = logoutShouldRemoveCookie;
}
@Context
private HttpServletRequest request;
@GET
@Path("/whoami")
@RolesAllowed("user") | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/WhoamiRessource.java
import de.ahus1.keycloak.dropwizard.User;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.*;
package de.ahus1.lottery.adapter.dropwizard.resource;
/**
* Ressourcce to show the name of the user ("Who am I").
* This is a simple resource that offers a GET request to test the redirect on accessing a protected resource.
* This will work only in non-bearer-only mode.
*/
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class WhoamiRessource {
private final boolean logoutShouldRemoveCookie;
public WhoamiRessource(boolean logoutShouldRemoveCookie) {
this.logoutShouldRemoveCookie = logoutShouldRemoveCookie;
}
@Context
private HttpServletRequest request;
@GET
@Path("/whoami")
@RolesAllowed("user") | public WhoamiView whoami(@Auth User user) { |
ahus1/keycloak-dropwizard-integration | keycloak-war/src/main/java/de/ahus1/lottery/adapter/servlet/DrawServlet.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.lottery.domain.DrawingService;
import org.keycloak.KeycloakPrincipal;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.servlet;
@WebServlet(urlPatterns = "/")
public class DrawServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// tag::principal[]
request.setAttribute("idToken", ((KeycloakPrincipal) request.getUserPrincipal())
.getKeycloakSecurityContext().getIdToken());
// end::principal[]
request.getRequestDispatcher("/index.ftl").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LocalDate date = LocalDate.parse(request.getParameter("date")); | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-war/src/main/java/de/ahus1/lottery/adapter/servlet/DrawServlet.java
import de.ahus1.lottery.domain.DrawingService;
import org.keycloak.KeycloakPrincipal;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.servlet;
@WebServlet(urlPatterns = "/")
public class DrawServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// tag::principal[]
request.setAttribute("idToken", ((KeycloakPrincipal) request.getUserPrincipal())
.getKeycloakSecurityContext().getIdToken());
// end::principal[]
request.getRequestDispatcher("/index.ftl").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LocalDate date = LocalDate.parse(request.getParameter("date")); | request.setAttribute("draw", DrawingService.drawNumbers(date)); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithPolicyEnforcer.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithPolicyEnforcer {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer-enforcer.yml");
if (!file.exists()) {
file = new File("../config-bearer-enforcer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithPolicyEnforcer.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithPolicyEnforcer {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer-enforcer.yml");
if (!file.exists()) {
file = new File("../config-bearer-enforcer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | StartPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithPolicyEnforcer.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithPolicyEnforcer {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer-enforcer.yml");
if (!file.exists()) {
file = new File("../config-bearer-enforcer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldDenyAccessWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithPolicyEnforcer.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithPolicyEnforcer {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer-enforcer.yml");
if (!file.exists()) {
file = new File("../config-bearer-enforcer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldDenyAccessWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | new DrawResourceState(baseUrl) |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user") | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user") | public DrawResponse draw(@Valid DrawRequest input, @Auth User user) { |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
public DrawResponse draw(@Valid DrawRequest input, @Auth User user) { | // Path: keycloak-dropwizard/src/main/java/de/ahus1/keycloak/dropwizard/User.java
// public class User extends AbstractUser {
//
// public User(KeycloakSecurityContext securityContext, HttpServletRequest request,
// KeycloakConfiguration keycloakConfiguration) {
// super(request, securityContext, keycloakConfiguration);
// }
//
// public void checkUserInRole(String role) {
// if (!getRoles().contains(role)) {
// throw new ForbiddenException();
// }
// }
//
// @Override
// public String getName() {
// return securityContext.getToken().getName();
// }
//
// }
//
// Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.keycloak.dropwizard.User;
import de.ahus1.lottery.domain.DrawingService;
import io.dropwizard.auth.Auth;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
public DrawResponse draw(@Valid DrawRequest input, @Auth User user) { | return new DrawResponse(DrawingService.drawNumbers(input.getDate())); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithSessionStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithSessionStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | StartPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithSessionStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithSessionStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami"); | WhoamiPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami");
WhoamiPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo");
}
@Test
public void shouldRedirectToLoginScreenWhenAccessedWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithSessionStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
File file = new File("config.yml");
if (!file.exists()) {
file = new File("../config.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami");
WhoamiPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo");
}
@Test
public void shouldRedirectToLoginScreenWhenAccessedWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | new DrawResourceState(baseUrl) |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java | // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jersey.sessions.HttpSessionFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.views.ViewBundle;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.jetty.KeycloakJettyAuthenticator;
import java.io.IOException; | securityHandler.addRole("user");
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setPathSpec("/*");
Constraint constraint = new Constraint();
// end::constraint[]
/* if I put false here, there will be deferred authentication. This will
not work when using oAuth redirects (as they will not make it to the front end).
The DeferredAuthentication will swallow them.
This might be different with a bearer token?!
*/
// tag::constraint[]
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{"user"});
constraintMapping.setConstraint(constraint);
securityHandler.addConstraintMapping(constraintMapping);
// end::constraint[]
// tag::keycloak[]
KeycloakJettyAuthenticator keycloak = new KeycloakJettyAuthenticator();
environment.getApplicationContext().getSecurityHandler().setAuthenticator(keycloak);
keycloak.setAdapterConfig(configuration.getKeycloakConfiguration());
// end::keycloak[]
// allow (stateful) sessions in Dropwizard, needed for Keycloak
environment.jersey().register(HttpSessionFactory.class);
environment.servlets().setSessionHandler(new SessionHandler());
// register web resources. | // Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
// @Path("/")
// @Produces(MediaType.TEXT_HTML)
// public class DrawRessource {
//
// @Context
// private HttpServletRequest request;
//
// // end::ressource[]
// @GET
// @RolesAllowed("user")
// public DrawView show(@Auth User auth) {
// DrawBean bean = new DrawBean();
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// // tag::ressource[]
// @POST
// @Path("/draw")
// @RolesAllowed("user")
// public DrawView draw(@FormParam("date") String dateAsString, @Auth User auth) { // <1>
// DrawBean bean = new DrawBean();
// LocalDate date = LocalDate.parse(dateAsString);
// bean.setDraw(DrawingService.drawNumbers(date));
// DrawView view = new DrawView(bean);
// bean.setName(auth.getName());
// return view;
// }
//
// @GET
// @Path("/logout")
// public LogoutView logout(@Context SecurityContext context) throws ServletException { // <2>
// if (context.getUserPrincipal() != null) {
// request.logout();
// }
// return new LogoutView();
// }
//
// }
// Path: keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplication.java
import de.ahus1.lottery.adapter.dropwizard.resource.DrawRessource;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.jersey.sessions.HttpSessionFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.views.ViewBundle;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.keycloak.adapters.jetty.KeycloakJettyAuthenticator;
import java.io.IOException;
securityHandler.addRole("user");
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setPathSpec("/*");
Constraint constraint = new Constraint();
// end::constraint[]
/* if I put false here, there will be deferred authentication. This will
not work when using oAuth redirects (as they will not make it to the front end).
The DeferredAuthentication will swallow them.
This might be different with a bearer token?!
*/
// tag::constraint[]
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{"user"});
constraintMapping.setConstraint(constraint);
securityHandler.addConstraintMapping(constraintMapping);
// end::constraint[]
// tag::keycloak[]
KeycloakJettyAuthenticator keycloak = new KeycloakJettyAuthenticator();
environment.getApplicationContext().getSecurityHandler().setAuthenticator(keycloak);
keycloak.setAdapterConfig(configuration.getKeycloakConfiguration());
// end::keycloak[]
// allow (stateful) sessions in Dropwizard, needed for Keycloak
environment.jersey().register(HttpSessionFactory.class);
environment.servlets().setSessionHandler(new SessionHandler());
// register web resources. | environment.jersey().register(DrawRessource.class); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.lottery.domain.DrawingService;
import org.keycloak.KeycloakSecurityContext;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
@GET
// @RolesAllowed("user")
public DrawView show() {
KeycloakSecurityContext session =
(KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
DrawBean bean = new DrawBean();
DrawView view = new DrawView(bean);
bean.setIdToken(session.getIdToken());
return view;
}
@POST
@Path("/draw")
@RolesAllowed("user")
public DrawView draw(@FormParam("date") String dateAsString) {
KeycloakSecurityContext session =
(KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
DrawBean bean = new DrawBean();
LocalDate date = LocalDate.parse(dateAsString); | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-jetty/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.lottery.domain.DrawingService;
import org.keycloak.KeycloakSecurityContext;
import javax.annotation.security.RolesAllowed;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class DrawRessource {
@Context
private HttpServletRequest request;
@GET
// @RolesAllowed("user")
public DrawView show() {
KeycloakSecurityContext session =
(KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
DrawBean bean = new DrawBean();
DrawView view = new DrawView(bean);
bean.setIdToken(session.getIdToken());
return view;
}
@POST
@Path("/draw")
@RolesAllowed("user")
public DrawView draw(@FormParam("date") String dateAsString) {
KeycloakSecurityContext session =
(KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
DrawBean bean = new DrawBean();
LocalDate date = LocalDate.parse(dateAsString); | bean.setDraw(DrawingService.drawNumbers(date)); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithBearerOnly.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithBearerOnly {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer.yml");
if (!file.exists()) {
file = new File("../config-bearer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithBearerOnly.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithBearerOnly {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer.yml");
if (!file.exists()) {
file = new File("../config-bearer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | StartPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithBearerOnly.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithBearerOnly {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer.yml");
if (!file.exists()) {
file = new File("../config-bearer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldDenyAccessWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithBearerOnly.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithBearerOnly {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-bearer.yml");
if (!file.exists()) {
file = new File("../config-bearer.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException, ReflectiveOperationException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldDenyAccessWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | new DrawResourceState(baseUrl) |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
| import de.ahus1.lottery.domain.DrawingService;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
public DrawResponse draw(@Valid DrawRequest input) { | // Path: domain/src/main/java/de/ahus1/lottery/domain/DrawingService.java
// public class DrawingService {
//
// public static final int MAX_NUMBER_IN_DRAW = 49;
// public static final int MIN_NUMBER_IN_DRAW = 1;
//
// public static Draw drawNumbers(LocalDate date) {
// Random random = new Random(date.toEpochDay());
// Draw.DrawBuilder builder = Draw.builder().withDate(date);
// do {
// Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1);
// if (number < MIN_NUMBER_IN_DRAW) {
// continue;
// }
// if (builder.contains(number)) {
// continue;
// }
// builder.withNumber(number);
// } while (!builder.isComplete());
// return builder.build();
// }
// }
// Path: keycloak-dropwizard-bearer/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRessource.java
import de.ahus1.lottery.domain.DrawingService;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package de.ahus1.lottery.adapter.dropwizard.resource;
@Path("/draw")
public class DrawRessource {
@POST
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
public DrawResponse draw(@Valid DrawRequest input) { | return new DrawResponse(DrawingService.drawNumbers(input.getDate())); |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithCookieStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithCookieStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html"); | StartPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithCookieStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami"); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
package de.ahus1.lottery.adapter.dropwizard;
@RunWith(Arquillian.class)
public class LotteryApplicationTestWithCookieStore {
@Drone
private WebDriver browser;
@ClassRule
public static final DropwizardAppRule<LotteryConfiguration> RULE =
new DropwizardAppRule<>(LotteryApplication.class,
getConfig()
);
private static String getConfig() {
File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami"); | WhoamiPage |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
| import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate; | File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami");
WhoamiPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo");
}
@Test
public void shouldRedirectToLoginScreenWhenAccessedWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | // Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/StartPage.java
// public class StartPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @FindBy(name = "date")
// private WebElement fieldDate;
//
// @FindBy(name = "draw")
// private WebElement buttonDraw;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Lottery Calculator");
// }
//
// public static LoginPage<StartPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// if (webClient.getCurrentUrl().equals(url.toString())) {
// // if we end up at the target page, the browser was still logged in
// webClient.navigate()
// .to("http://localhost:8080/auth/realms/test/protocol/openid-connect/logout?redirect_uri=" + url);
// }
// LoginPage<StartPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(StartPage.class);
// return loginPage;
// }
//
// public DrawPage draw(LocalDate date) {
// fieldDate.sendKeys(date.toString());
// buttonDraw.click();
// return createPage(DrawPage.class);
// }
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/pages/WhoamiPage.java
// public class WhoamiPage extends Page {
//
// @Drone
// private WebDriver browser;
//
// @Override
// public void verify() {
// assertThat(browser.getTitle()).isEqualTo("Who Am I");
// }
//
// public static LoginPage<WhoamiPage> openWithoutLogin(WebDriver webClient, URL url) {
// webClient.get(url.toString());
// LoginPage<WhoamiPage> loginPage = Page.createPage(LoginPage.class, webClient);
// loginPage.setReturnPage(WhoamiPage.class);
// return loginPage;
// }
//
// }
//
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
// public class DrawResourceState {
// private final URI baseUrl;
// private Response response;
// private String accessToken;
//
// public DrawResourceState(URI baseUrl) {
// this.baseUrl = baseUrl;
// }
//
// public DrawResourceState givenNoToken() {
// accessToken = null;
// return this;
// }
//
// public DrawResourceState givenToken(String accessToken) {
// this.accessToken = accessToken;
// return this;
// }
//
// public DrawResourceState whenOpened() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.FOLLOW_REDIRECTS, false);
// WebTarget target = client.target(baseUrl).path("/draw");
// DrawRequest request = new DrawRequest();
// request.setDate(LocalDate.parse("2015-01-01"));
// Invocation.Builder builder = target.request();
// if (accessToken != null) {
// builder.header("Authorization", "Bearer " + accessToken);
// }
// response = builder.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// return this;
// }
//
// public void thenAccessDenied() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenForbidden() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.FORBIDDEN);
// }
//
// public void thenUnauthorized() {
// assertThat(response.getStatusInfo()).isEqualTo(Response.Status.UNAUTHORIZED);
// }
//
// public void thenRedirectedToLoginScreen() {
// assertThat(response.getLocation().getPath()).startsWith("/auth/realms");
// }
//
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/LotteryApplicationTestWithCookieStore.java
import de.ahus1.lottery.adapter.dropwizard.pages.StartPage;
import de.ahus1.lottery.adapter.dropwizard.pages.WhoamiPage;
import de.ahus1.lottery.adapter.dropwizard.state.DrawResourceState;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDate;
File file = new File("config-cookiestore.yml");
if (!file.exists()) {
file = new File("../config-cookiestore.yml");
}
return file.getAbsolutePath();
}
@Test
public void shouldCalculateDraw() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/ajax/index.html");
StartPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo")
.draw(LocalDate.parse("2015-01-01"))
.logout();
}
@Test
public void shouldShowWhoiam() throws IOException {
// load initial page, will redirect to keycloak
URL baseUrl = new URL("http://localhost:" + RULE.getLocalPort() + "/whoami");
WhoamiPage
.openWithoutLogin(browser, baseUrl)
.login("demo", "demo");
}
@Test
public void shouldRedirectToLoginScreenWhenAccessedWithoutBearerToken() throws URISyntaxException {
URI baseUrl = new URI("http://localhost:" + RULE.getLocalPort()); | new DrawResourceState(baseUrl) |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawBean.java | // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
| import de.ahus1.lottery.domain.Draw; | package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawBean {
private String name; | // Path: domain/src/main/java/de/ahus1/lottery/domain/Draw.java
// public class Draw {
//
// private final LocalDate date;
// private Set<Integer> numbers;
//
// private Draw(LocalDate aDate, Set<Integer> someNumbers) {
// numbers = someNumbers;
// date = aDate;
// }
//
// public Set<Integer> getNumbers() {
// return numbers;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public static class DrawBuilder {
// public static final int DRAW_SIZE = 6;
// private Set<Integer> numbers = new HashSet<>();
// private LocalDate date;
//
// public DrawBuilder withNumber(Integer aNumber) {
// if (numbers.contains(aNumber)) {
// throw new IllegalArgumentException("you must not add the same number twice ("
// + aNumber + ")");
// }
// numbers.add(aNumber);
// return this;
// }
//
// public boolean contains(Integer aNumber) {
// return numbers.contains(aNumber);
// }
//
// public int size() {
// return numbers.size();
// }
//
// public DrawBuilder withNumbers(Integer... someNumbers) {
// List<Integer> list = Arrays.asList(someNumbers);
// list.forEach(this::withNumber);
// return this;
// }
//
// public Draw build() {
// if (numbers.size() != DRAW_SIZE) {
// throw new IllegalStateException("you need " + DRAW_SIZE + " numbers in a draw!");
// }
// return new Draw(date, numbers);
// }
//
// public boolean isComplete() {
// return numbers.size() == DRAW_SIZE;
// }
//
// public DrawBuilder withDate(LocalDate aDate) {
// date = aDate;
// return this;
// }
// }
//
// public static DrawBuilder builder() {
// return new DrawBuilder();
// }
//
// }
// Path: keycloak-dropwizard-jaxrs-example/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawBean.java
import de.ahus1.lottery.domain.Draw;
package de.ahus1.lottery.adapter.dropwizard.resource;
public class DrawBean {
private String name; | private Draw draw; |
ahus1/keycloak-dropwizard-integration | keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java | // Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRequest.java
// public class DrawRequest {
//
// @NotNull
// private LocalDate date;
//
// public LocalDate getDate() {
// return date;
// }
//
// public void setDate(LocalDate date) {
// this.date = date;
// }
// }
| import de.ahus1.lottery.adapter.dropwizard.resource.DrawRequest;
import org.glassfish.jersey.client.ClientProperties;
import javax.ws.rs.client.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat; | package de.ahus1.lottery.adapter.dropwizard.state;
public class DrawResourceState {
private final URI baseUrl;
private Response response;
private String accessToken;
public DrawResourceState(URI baseUrl) {
this.baseUrl = baseUrl;
}
public DrawResourceState givenNoToken() {
accessToken = null;
return this;
}
public DrawResourceState givenToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
public DrawResourceState whenOpened() {
Client client = ClientBuilder.newClient();
client.property(ClientProperties.FOLLOW_REDIRECTS, false);
WebTarget target = client.target(baseUrl).path("/draw"); | // Path: keycloak-dropwizard-bearermodule/src/main/java/de/ahus1/lottery/adapter/dropwizard/resource/DrawRequest.java
// public class DrawRequest {
//
// @NotNull
// private LocalDate date;
//
// public LocalDate getDate() {
// return date;
// }
//
// public void setDate(LocalDate date) {
// this.date = date;
// }
// }
// Path: keycloak-dropwizard-bearermodule/src/test/java/de/ahus1/lottery/adapter/dropwizard/state/DrawResourceState.java
import de.ahus1.lottery.adapter.dropwizard.resource.DrawRequest;
import org.glassfish.jersey.client.ClientProperties;
import javax.ws.rs.client.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
package de.ahus1.lottery.adapter.dropwizard.state;
public class DrawResourceState {
private final URI baseUrl;
private Response response;
private String accessToken;
public DrawResourceState(URI baseUrl) {
this.baseUrl = baseUrl;
}
public DrawResourceState givenNoToken() {
accessToken = null;
return this;
}
public DrawResourceState givenToken(String accessToken) {
this.accessToken = accessToken;
return this;
}
public DrawResourceState whenOpened() {
Client client = ClientBuilder.newClient();
client.property(ClientProperties.FOLLOW_REDIRECTS, false);
WebTarget target = client.target(baseUrl).path("/draw"); | DrawRequest request = new DrawRequest(); |
evernote/android-state | library-lint/src/test/resources/java/InvalidActivityNoRestoreDirectImport.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
| import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver.saveInstanceState; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoRestoreDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
// Path: library-lint/src/test/resources/java/InvalidActivityNoRestoreDirectImport.java
import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver.saveInstanceState;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoRestoreDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | saveInstanceState(this, outState); |
evernote/android-state | library-lint/src/test/resources/java/InvalidActivityOtherMethod.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityOtherMethod extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library-lint/src/test/resources/java/InvalidActivityOtherMethod.java
import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityOtherMethod extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | StateSaver.saveInstanceState(this, outState); |
evernote/android-state | library/src/test/java/com/evernote/android/state/test/TestView.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.content.Context;
import android.os.Parcelable;
import android.view.View;
import com.evernote.android.state.State;
import com.evernote.android.state.StateSaver; | package com.evernote.android.state.test;
public class TestView extends View {
@State
public int mState;
public TestView(Context context) {
super(context);
}
@Override
protected Parcelable onSaveInstanceState() { | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library/src/test/java/com/evernote/android/state/test/TestView.java
import android.content.Context;
import android.os.Parcelable;
import android.view.View;
import com.evernote.android.state.State;
import com.evernote.android.state.StateSaver;
package com.evernote.android.state.test;
public class TestView extends View {
@State
public int mState;
public TestView(Context context) {
super(context);
}
@Override
protected Parcelable onSaveInstanceState() { | return StateSaver.saveInstanceState(this, super.onSaveInstanceState()); |
evernote/android-state | demo/src/main/java/com/evernote/android/state/test/lint/LintFailingActivityJava.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.evernote.android.state.StateSaver; | package com.evernote.android.state.test.lint;
/**
* @author rwondratschek
*/
public class LintFailingActivityJava extends Activity {
@SuppressLint("NonMatchingStateSaverCalls")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: demo/src/main/java/com/evernote/android/state/test/lint/LintFailingActivityJava.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.evernote.android.state.StateSaver;
package com.evernote.android.state.test.lint;
/**
* @author rwondratschek
*/
public class LintFailingActivityJava extends Activity {
@SuppressLint("NonMatchingStateSaverCalls")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | StateSaver.restoreInstanceState(this, savedInstanceState); |
evernote/android-state | library-lint/src/test/resources/java/InvalidActivityNoSave.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoSave extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library-lint/src/test/resources/java/InvalidActivityNoSave.java
import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoSave extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | StateSaver.restoreInstanceState(this, savedInstanceState); |
evernote/android-state | demo-java-8/src/main/java/com/evernote/different/TestProguardBundler.java | // Path: library/src/main/java/com/evernote/android/state/Bundler.java
// public interface Bundler<T> {
//
// /**
// * Save the given value inside of the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param value The object which should be saved in the bundle.
// * @param bundle The bundle where the value should be stored.
// */
// void put(@NonNull String key, @NonNull T value, @NonNull Bundle bundle);
//
// /**
// * Restore the value from the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param bundle The bundle in which the value is stored.
// * @return The object restored from the bundle.
// */
// @Nullable
// T get(@NonNull String key, @NonNull Bundle bundle);
// }
| import android.os.Bundle;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.evernote.android.state.Bundler;
import com.evernote.android.state.State;
import com.evernote.android.state.StateReflection; |
@Keep
public void setValue(int value) {
mData2.int1 = value;
mData2.int2 = value;
mDataReflOtherName.int1 = value;
mDataReflOtherName.int2 = value;
}
@Keep
public void verifyValue(int value) {
if (mData2.int1 != value) {
throw new IllegalStateException();
}
if (mData2.int2 != value) {
throw new IllegalStateException();
}
if (mDataReflOtherName.int1 != value) {
throw new IllegalStateException();
}
if (mDataReflOtherName.int2 != value) {
throw new IllegalStateException();
}
}
public static final class Data {
public int int1;
public int int2;
}
| // Path: library/src/main/java/com/evernote/android/state/Bundler.java
// public interface Bundler<T> {
//
// /**
// * Save the given value inside of the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param value The object which should be saved in the bundle.
// * @param bundle The bundle where the value should be stored.
// */
// void put(@NonNull String key, @NonNull T value, @NonNull Bundle bundle);
//
// /**
// * Restore the value from the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param bundle The bundle in which the value is stored.
// * @return The object restored from the bundle.
// */
// @Nullable
// T get(@NonNull String key, @NonNull Bundle bundle);
// }
// Path: demo-java-8/src/main/java/com/evernote/different/TestProguardBundler.java
import android.os.Bundle;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.evernote.android.state.Bundler;
import com.evernote.android.state.State;
import com.evernote.android.state.StateReflection;
@Keep
public void setValue(int value) {
mData2.int1 = value;
mData2.int2 = value;
mDataReflOtherName.int1 = value;
mDataReflOtherName.int2 = value;
}
@Keep
public void verifyValue(int value) {
if (mData2.int1 != value) {
throw new IllegalStateException();
}
if (mData2.int2 != value) {
throw new IllegalStateException();
}
if (mDataReflOtherName.int1 != value) {
throw new IllegalStateException();
}
if (mDataReflOtherName.int2 != value) {
throw new IllegalStateException();
}
}
public static final class Data {
public int int1;
public int int2;
}
| public static final class MyBundler implements Bundler<Data> { |
evernote/android-state | library/src/test/java/com/evernote/android/state/test/BundlingTest.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.os.Bundle;
import android.os.Parcelable;
import android.test.mock.MockContext;
import com.evernote.android.state.StateSaver;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import java.util.ArrayList;
import static org.assertj.core.api.Java6Assertions.assertThat; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
@FixMethodOrder(MethodSorters.JVM)
public class BundlingTest {
private Bundle mBundle;
@Before
public void setUp() {
mBundle = new Bundle();
}
@Test
public void testSimple() {
TestSimple object = createSavedInstance(TestSimple.class);
object.field = 5;
| // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library/src/test/java/com/evernote/android/state/test/BundlingTest.java
import android.os.Bundle;
import android.os.Parcelable;
import android.test.mock.MockContext;
import com.evernote.android.state.StateSaver;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import java.util.ArrayList;
import static org.assertj.core.api.Java6Assertions.assertThat;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
@FixMethodOrder(MethodSorters.JVM)
public class BundlingTest {
private Bundle mBundle;
@Before
public void setUp() {
mBundle = new Bundle();
}
@Test
public void testSimple() {
TestSimple object = createSavedInstance(TestSimple.class);
object.field = 5;
| StateSaver.restoreInstanceState(object, mBundle); |
evernote/android-state | library/src/test/java/com/evernote/android/state/test/TestBundler.java | // Path: library/src/main/java/com/evernote/android/state/Bundler.java
// public interface Bundler<T> {
//
// /**
// * Save the given value inside of the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param value The object which should be saved in the bundle.
// * @param bundle The bundle where the value should be stored.
// */
// void put(@NonNull String key, @NonNull T value, @NonNull Bundle bundle);
//
// /**
// * Restore the value from the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param bundle The bundle in which the value is stored.
// * @return The object restored from the bundle.
// */
// @Nullable
// T get(@NonNull String key, @NonNull Bundle bundle);
// }
| import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.evernote.android.state.Bundler;
import com.evernote.android.state.State;
import com.evernote.android.state.StateReflection; | package com.evernote.android.state.test;
public class TestBundler {
@State(MyBundler.class)
private Data mData2;
@StateReflection(value = MyBundler.class)
private Data mDataReflOtherName;
public Data getData2() {
return mData2;
}
public void setData2(Data data2) {
mData2 = data2;
}
public Data getDataRefl() {
return mDataReflOtherName;
}
public void setDataRefl(Data data) {
mDataReflOtherName = data;
}
public static final class Data {
public int int1;
public int int2;
}
| // Path: library/src/main/java/com/evernote/android/state/Bundler.java
// public interface Bundler<T> {
//
// /**
// * Save the given value inside of the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param value The object which should be saved in the bundle.
// * @param bundle The bundle where the value should be stored.
// */
// void put(@NonNull String key, @NonNull T value, @NonNull Bundle bundle);
//
// /**
// * Restore the value from the bundle.
// *
// * @param key The base key for this value. Each field of the value should have a separate key with this prefix.
// * @param bundle The bundle in which the value is stored.
// * @return The object restored from the bundle.
// */
// @Nullable
// T get(@NonNull String key, @NonNull Bundle bundle);
// }
// Path: library/src/test/java/com/evernote/android/state/test/TestBundler.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.evernote.android.state.Bundler;
import com.evernote.android.state.State;
import com.evernote.android.state.StateReflection;
package com.evernote.android.state.test;
public class TestBundler {
@State(MyBundler.class)
private Data mData2;
@StateReflection(value = MyBundler.class)
private Data mDataReflOtherName;
public Data getData2() {
return mData2;
}
public void setData2(Data data2) {
mData2 = data2;
}
public Data getDataRefl() {
return mDataReflOtherName;
}
public void setDataRefl(Data data) {
mDataReflOtherName = data;
}
public static final class Data {
public int int1;
public int int2;
}
| public static final class MyBundler implements Bundler<Data> { |
evernote/android-state | library-lint/src/test/resources/java/ValidActivityDirectImport.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
| import static com.evernote.android.state.StateSaver.saveInstanceState;
import android.app.Activity;
import android.os.Bundle;
import static com.evernote.android.state.StateSaver.restoreInstanceState; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivityDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
// Path: library-lint/src/test/resources/java/ValidActivityDirectImport.java
import static com.evernote.android.state.StateSaver.saveInstanceState;
import android.app.Activity;
import android.os.Bundle;
import static com.evernote.android.state.StateSaver.restoreInstanceState;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivityDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | restoreInstanceState(this, savedInstanceState); |
evernote/android-state | library-lint/src/test/resources/java/ValidActivityDirectImport.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
| import static com.evernote.android.state.StateSaver.saveInstanceState;
import android.app.Activity;
import android.os.Bundle;
import static com.evernote.android.state.StateSaver.restoreInstanceState; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivityDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState(this, savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
// Path: library-lint/src/test/resources/java/ValidActivityDirectImport.java
import static com.evernote.android.state.StateSaver.saveInstanceState;
import android.app.Activity;
import android.os.Bundle;
import static com.evernote.android.state.StateSaver.restoreInstanceState;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivityDirectImport extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreInstanceState(this, savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | saveInstanceState(this, outState); |
evernote/android-state | library/src/test/java/com/evernote/android/state/test/TestJavaList.java | // Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListInteger.java
// public class BundlerListInteger implements Bundler<List<Integer>> {
// @Override
// public void put(@NonNull String key, @NonNull List<Integer> value, @NonNull Bundle bundle) {
// ArrayList<Integer> arrayList = value instanceof ArrayList ? (ArrayList<Integer>) value : new ArrayList<>(value);
// bundle.putIntegerArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<Integer> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getIntegerArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListParcelable.java
// public class BundlerListParcelable implements Bundler<List<? extends Parcelable>> {
// @SuppressWarnings("unchecked")
// @Override
// public void put(@NonNull String key, @NonNull List<? extends Parcelable> value, @NonNull Bundle bundle) {
// ArrayList<? extends Parcelable> arrayList = value instanceof ArrayList ? (ArrayList<? extends Parcelable>) value : new ArrayList<>(value);
// bundle.putParcelableArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<? extends Parcelable> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getParcelableArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListString.java
// public class BundlerListString implements Bundler<List<String>> {
// @Override
// public void put(@NonNull String key, @NonNull List<String> value, @NonNull Bundle bundle) {
// ArrayList<String> arrayList = value instanceof ArrayList ? (ArrayList<String>) value : new ArrayList<>(value);
// bundle.putStringArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<String> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getStringArrayList(key);
// }
// }
| import com.evernote.android.state.State;
import com.evernote.android.state.bundlers.BundlerListInteger;
import com.evernote.android.state.bundlers.BundlerListParcelable;
import com.evernote.android.state.bundlers.BundlerListString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
public class TestJavaList {
@State(BundlerListString.class)
private List<String> stringList = Collections.unmodifiableList(new ArrayList<String>(){{
add("Hello");
add("World");
}});
| // Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListInteger.java
// public class BundlerListInteger implements Bundler<List<Integer>> {
// @Override
// public void put(@NonNull String key, @NonNull List<Integer> value, @NonNull Bundle bundle) {
// ArrayList<Integer> arrayList = value instanceof ArrayList ? (ArrayList<Integer>) value : new ArrayList<>(value);
// bundle.putIntegerArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<Integer> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getIntegerArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListParcelable.java
// public class BundlerListParcelable implements Bundler<List<? extends Parcelable>> {
// @SuppressWarnings("unchecked")
// @Override
// public void put(@NonNull String key, @NonNull List<? extends Parcelable> value, @NonNull Bundle bundle) {
// ArrayList<? extends Parcelable> arrayList = value instanceof ArrayList ? (ArrayList<? extends Parcelable>) value : new ArrayList<>(value);
// bundle.putParcelableArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<? extends Parcelable> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getParcelableArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListString.java
// public class BundlerListString implements Bundler<List<String>> {
// @Override
// public void put(@NonNull String key, @NonNull List<String> value, @NonNull Bundle bundle) {
// ArrayList<String> arrayList = value instanceof ArrayList ? (ArrayList<String>) value : new ArrayList<>(value);
// bundle.putStringArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<String> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getStringArrayList(key);
// }
// }
// Path: library/src/test/java/com/evernote/android/state/test/TestJavaList.java
import com.evernote.android.state.State;
import com.evernote.android.state.bundlers.BundlerListInteger;
import com.evernote.android.state.bundlers.BundlerListParcelable;
import com.evernote.android.state.bundlers.BundlerListString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
public class TestJavaList {
@State(BundlerListString.class)
private List<String> stringList = Collections.unmodifiableList(new ArrayList<String>(){{
add("Hello");
add("World");
}});
| @State(BundlerListInteger.class) |
evernote/android-state | library/src/test/java/com/evernote/android/state/test/TestJavaList.java | // Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListInteger.java
// public class BundlerListInteger implements Bundler<List<Integer>> {
// @Override
// public void put(@NonNull String key, @NonNull List<Integer> value, @NonNull Bundle bundle) {
// ArrayList<Integer> arrayList = value instanceof ArrayList ? (ArrayList<Integer>) value : new ArrayList<>(value);
// bundle.putIntegerArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<Integer> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getIntegerArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListParcelable.java
// public class BundlerListParcelable implements Bundler<List<? extends Parcelable>> {
// @SuppressWarnings("unchecked")
// @Override
// public void put(@NonNull String key, @NonNull List<? extends Parcelable> value, @NonNull Bundle bundle) {
// ArrayList<? extends Parcelable> arrayList = value instanceof ArrayList ? (ArrayList<? extends Parcelable>) value : new ArrayList<>(value);
// bundle.putParcelableArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<? extends Parcelable> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getParcelableArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListString.java
// public class BundlerListString implements Bundler<List<String>> {
// @Override
// public void put(@NonNull String key, @NonNull List<String> value, @NonNull Bundle bundle) {
// ArrayList<String> arrayList = value instanceof ArrayList ? (ArrayList<String>) value : new ArrayList<>(value);
// bundle.putStringArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<String> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getStringArrayList(key);
// }
// }
| import com.evernote.android.state.State;
import com.evernote.android.state.bundlers.BundlerListInteger;
import com.evernote.android.state.bundlers.BundlerListParcelable;
import com.evernote.android.state.bundlers.BundlerListString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
public class TestJavaList {
@State(BundlerListString.class)
private List<String> stringList = Collections.unmodifiableList(new ArrayList<String>(){{
add("Hello");
add("World");
}});
@State(BundlerListInteger.class)
private List<Integer> emptyList = Collections.emptyList();
| // Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListInteger.java
// public class BundlerListInteger implements Bundler<List<Integer>> {
// @Override
// public void put(@NonNull String key, @NonNull List<Integer> value, @NonNull Bundle bundle) {
// ArrayList<Integer> arrayList = value instanceof ArrayList ? (ArrayList<Integer>) value : new ArrayList<>(value);
// bundle.putIntegerArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<Integer> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getIntegerArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListParcelable.java
// public class BundlerListParcelable implements Bundler<List<? extends Parcelable>> {
// @SuppressWarnings("unchecked")
// @Override
// public void put(@NonNull String key, @NonNull List<? extends Parcelable> value, @NonNull Bundle bundle) {
// ArrayList<? extends Parcelable> arrayList = value instanceof ArrayList ? (ArrayList<? extends Parcelable>) value : new ArrayList<>(value);
// bundle.putParcelableArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<? extends Parcelable> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getParcelableArrayList(key);
// }
// }
//
// Path: library/src/main/java/com/evernote/android/state/bundlers/BundlerListString.java
// public class BundlerListString implements Bundler<List<String>> {
// @Override
// public void put(@NonNull String key, @NonNull List<String> value, @NonNull Bundle bundle) {
// ArrayList<String> arrayList = value instanceof ArrayList ? (ArrayList<String>) value : new ArrayList<>(value);
// bundle.putStringArrayList(key, arrayList);
// }
//
// @Nullable
// @Override
// public List<String> get(@NonNull String key, @NonNull Bundle bundle) {
// return bundle.getStringArrayList(key);
// }
// }
// Path: library/src/test/java/com/evernote/android/state/test/TestJavaList.java
import com.evernote.android.state.State;
import com.evernote.android.state.bundlers.BundlerListInteger;
import com.evernote.android.state.bundlers.BundlerListParcelable;
import com.evernote.android.state.bundlers.BundlerListString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test;
/**
* @author rwondratschek
*/
public class TestJavaList {
@State(BundlerListString.class)
private List<String> stringList = Collections.unmodifiableList(new ArrayList<String>(){{
add("Hello");
add("World");
}});
@State(BundlerListInteger.class)
private List<Integer> emptyList = Collections.emptyList();
| @State(BundlerListParcelable.class) |
evernote/android-state | library-lint/src/test/resources/java/ValidActivity.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library-lint/src/test/resources/java/ValidActivity.java
import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class ValidActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | StateSaver.restoreInstanceState(this, savedInstanceState); |
evernote/android-state | demo-java-8/src/test/java/com/evernote/android/state/test/java8/Java8BundlingTest.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.os.Bundle;
import com.evernote.android.state.StateSaver;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test.java8;
/**
* @author rwondratschek
*/
@FixMethodOrder(MethodSorters.JVM)
public class Java8BundlingTest {
private Bundle mBundle;
@Before
public void setUp() {
mBundle = new Bundle();
}
@Test
public void testTypes() {
TestTypes object = createSavedInstance(TestTypes.class);
object.mBooleanObj = Boolean.FALSE;
| // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: demo-java-8/src/test/java/com/evernote/android/state/test/java8/Java8BundlingTest.java
import android.os.Bundle;
import com.evernote.android.state.StateSaver;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek
*******************************************************************************/
package com.evernote.android.state.test.java8;
/**
* @author rwondratschek
*/
@FixMethodOrder(MethodSorters.JVM)
public class Java8BundlingTest {
private Bundle mBundle;
@Before
public void setUp() {
mBundle = new Bundle();
}
@Test
public void testTypes() {
TestTypes object = createSavedInstance(TestTypes.class);
object.mBooleanObj = Boolean.FALSE;
| StateSaver.restoreInstanceState(object, mBundle); |
evernote/android-state | library-lint/src/test/resources/java/InvalidActivityNoRestore.java | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver; | /* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoRestore extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | // Path: library/src/main/java/com/evernote/android/state/StateSaver.java
// @SuppressWarnings({"WeakerAccess", "unused"})
// public final class StateSaver {
//
// public static final String SUFFIX = "$$StateSaver";
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// private static final StateSaverImpl IMPL = new StateSaverImpl(new LinkedHashMap<Class<?>, Injector>());
//
// /**
// * Save the given {@code target} in the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is saved into this bundle.
// */
// public static <T> void saveInstanceState(@NonNull T target, @NonNull Bundle state) {
// IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the given {@code target} from the passed in {@link Bundle}.
// *
// * @param target The object containing fields annotated with {@link State}.
// * @param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}.
// */
// public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
// IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Save the state of the given view and the other state inside of the returned {@link Parcelable}.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The super state of the parent class of the view. Usually it isn't {@code null}.
// * @return A parcelable containing the view's state and its super state.
// */
// @NonNull
// public static <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.saveInstanceState(target, state);
// }
//
// /**
// * Restore the sate of the given view and return the super state of the parent class.
// *
// * @param target The view containing fields annotated with {@link State}.
// * @param state The parcelable containing the view's state and its super sate.
// * @return The super state of teh parent class of the view. Usually it isn't {@code null}.
// */
// @Nullable
// public static <T extends View> Parcelable restoreInstanceState(@NonNull T target, @Nullable Parcelable state) {
// return IMPL.restoreInstanceState(target, state);
// }
//
// /**
// * Turns automatic instance saving on or off for all activities and fragments from the support library. This avoids
// * manual calls of {@link #saveInstanceState(Object, Bundle)} and {@link #restoreInstanceState(Object, Bundle)}, instead
// * the library is doing this automatically for you. It's still necessary to annotate fields with {@link State}, though.
// * <br>
// * <br>
// * The best place to turn on this feature is in your {@link Application#onCreate()} method.
// *
// * @param application Your application instance.
// * @param enabled Whether this feature should be enabled.
// */
// public static void setEnabledForAllActivitiesAndSupportFragments(@NonNull Application application, boolean enabled) {
// IMPL.setEnabledForAllActivitiesAndSupportFragments(application, enabled);
// }
//
// private StateSaver() {
// throw new UnsupportedOperationException();
// }
// }
// Path: library-lint/src/test/resources/java/InvalidActivityNoRestore.java
import android.app.Activity;
import android.os.Bundle;
import com.evernote.android.state.StateSaver;
/* *****************************************************************************
* Copyright (c) 2017 Evernote Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ralf Wondratschek - initial version
*******************************************************************************/
package com.evernote.android.state.lint;
/**
* @author rwondratschek
*/
public class InvalidActivityNoRestore extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); | StateSaver.saveInstanceState(this, outState); |
jhalterman/sarge | src/main/java/net/jodah/sarge/Directive.java | // Path: src/main/java/net/jodah/sarge/internal/RetryDirective.java
// public class RetryDirective extends Directive {
// private final int maxRetries;
// private final Duration retryWindow;
// private final boolean backoff;
// private Duration initialRetryInterval;
// private double backoffExponent;
// private Duration maxRetryInterval;
//
// public RetryDirective(int maxRetries, Duration retryWindow) {
// this.maxRetries = maxRetries;
// this.retryWindow = retryWindow;
// backoff = false;
// }
//
// public RetryDirective(int maxRetries, Duration retryWindow, Duration initialRetryInterval,
// double backoffExponent, Duration maxRetryInterval) {
// this.maxRetries = maxRetries;
// this.retryWindow = retryWindow;
// backoff = true;
// this.initialRetryInterval = initialRetryInterval;
// this.backoffExponent = backoffExponent;
// this.maxRetryInterval = maxRetryInterval;
// }
//
// public double getBackoffExponent() {
// return backoffExponent;
// }
//
// public Duration getInitialRetryInterval() {
// return initialRetryInterval;
// }
//
// public int getMaxRetries() {
// return maxRetries;
// }
//
// public Duration getMaxRetryInterval() {
// return maxRetryInterval;
// }
//
// public Duration getRetryWindow() {
// return retryWindow;
// }
//
// public boolean shouldBackoff() {
// return backoff;
// }
//
// @Override
// public String toString() {
// return "Retry Directive";
// }
// }
| import net.jodah.sarge.internal.RetryDirective;
import java.time.Duration; | package net.jodah.sarge;
/**
* Determine how failures should be handled.
*
* @author Jonathan Halterman
*/
public class Directive {
/**
* Resume supervision, re-throwing the failure from the point of invocation if a result is
* expected.
*/
public static final Directive Resume = new Directive() {
@Override
public String toString() {
return "Resume Directive";
}
};
/** Re-throws the failure from the point of invocation. */
public static final Directive Rethrow = new Directive() {
@Override
public String toString() {
return "Rethrow Directive";
}
};
/** Escalates the failure to the supervisor of the supervisor. */
public static final Directive Escalate = new Directive() {
@Override
public String toString() {
return "Escalate Directive";
}
};
/** Retries the method invocation. */
public static Directive Retry(int maxRetries, Duration retryWindow) { | // Path: src/main/java/net/jodah/sarge/internal/RetryDirective.java
// public class RetryDirective extends Directive {
// private final int maxRetries;
// private final Duration retryWindow;
// private final boolean backoff;
// private Duration initialRetryInterval;
// private double backoffExponent;
// private Duration maxRetryInterval;
//
// public RetryDirective(int maxRetries, Duration retryWindow) {
// this.maxRetries = maxRetries;
// this.retryWindow = retryWindow;
// backoff = false;
// }
//
// public RetryDirective(int maxRetries, Duration retryWindow, Duration initialRetryInterval,
// double backoffExponent, Duration maxRetryInterval) {
// this.maxRetries = maxRetries;
// this.retryWindow = retryWindow;
// backoff = true;
// this.initialRetryInterval = initialRetryInterval;
// this.backoffExponent = backoffExponent;
// this.maxRetryInterval = maxRetryInterval;
// }
//
// public double getBackoffExponent() {
// return backoffExponent;
// }
//
// public Duration getInitialRetryInterval() {
// return initialRetryInterval;
// }
//
// public int getMaxRetries() {
// return maxRetries;
// }
//
// public Duration getMaxRetryInterval() {
// return maxRetryInterval;
// }
//
// public Duration getRetryWindow() {
// return retryWindow;
// }
//
// public boolean shouldBackoff() {
// return backoff;
// }
//
// @Override
// public String toString() {
// return "Retry Directive";
// }
// }
// Path: src/main/java/net/jodah/sarge/Directive.java
import net.jodah.sarge.internal.RetryDirective;
import java.time.Duration;
package net.jodah.sarge;
/**
* Determine how failures should be handled.
*
* @author Jonathan Halterman
*/
public class Directive {
/**
* Resume supervision, re-throwing the failure from the point of invocation if a result is
* expected.
*/
public static final Directive Resume = new Directive() {
@Override
public String toString() {
return "Resume Directive";
}
};
/** Re-throws the failure from the point of invocation. */
public static final Directive Rethrow = new Directive() {
@Override
public String toString() {
return "Rethrow Directive";
}
};
/** Escalates the failure to the supervisor of the supervisor. */
public static final Directive Escalate = new Directive() {
@Override
public String toString() {
return "Escalate Directive";
}
};
/** Retries the method invocation. */
public static Directive Retry(int maxRetries, Duration retryWindow) { | return new RetryDirective(maxRetries, retryWindow); |
jhalterman/sarge | src/test/java/net/jodah/sarge/functional/BackoffTest.java | // Path: src/test/java/net/jodah/sarge/AbstractTest.java
// public abstract class AbstractTest {
// protected Sarge sarge;
//
// @BeforeMethod
// protected void beforeMethod() {
// sarge = new Sarge();
// }
// }
//
// Path: src/main/java/net/jodah/sarge/Plans.java
// public final class Plans {
// private Plans() {
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker escalateOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Escalate, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker escalateOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Escalate, causeTypes);
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker onFailure(Class<? extends Throwable> causeType, Directive directive) {
// return new PlanMaker().addDirective(directive, causeType);
// }
//
// @SuppressWarnings("unchecked")
// public static PlanMaker resumeOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Resume, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker resumeOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Resume, causeTypes);
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker rethrowOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Rethrow, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker rethrowOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Rethrow, causeTypes);
// }
//
// /**
// * Create a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow} with zero wait time between retries.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, retryWindow), causeType);
// }
//
// /**
// * Performs a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow}, backing off and waiting between each retry according to
// * the {@code backoffExponent} up to {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, double backoffExponent,
// Duration maxRetryInterval) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, retryWindow,
// initialRetryInterval, backoffExponent, maxRetryInterval), causeType);
// }
//
// /**
// * Performs a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow}, backing off and waiting between each retry up to
// * {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, Duration maxRetryInterval) {
// return new PlanMaker().addDirective(
// Directive.Retry(maxRetries, retryWindow, initialRetryInterval, 2, maxRetryInterval),
// causeType);
// }
//
// /**
// * Perform a retry when a failure of any of the {@code causeTypes} occurs, retrying up to
// * {@code maxRetries} times within the {@code timeRange} with zero wait time between retries.
// *
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker retryOn(Class<? extends Throwable>[] causeTypes, int maxRetries,
// Duration timeRange) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, timeRange), causeTypes);
// }
//
// /**
// * Perform a retry when a failure of any of the {@code causeTypes} occurs, retrying up to
// * {@code maxRetries} times within the {@code retryWindow}, backing off and waiting between each
// * retry up to {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// public static PlanMaker retryOn(Class<? extends Throwable>[] causeTypes, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, Duration maxRetryInterval) {
// return new PlanMaker().addDirective(
// Directive.Retry(maxRetries, retryWindow, initialRetryInterval, 2, maxRetryInterval),
// causeTypes);
// }
// }
| import net.jodah.sarge.AbstractTest;
import net.jodah.sarge.Plans;
import org.testng.annotations.Test;
import java.time.Duration;
import static org.testng.Assert.*; | package net.jodah.sarge.functional;
/**
* @author Jonathan Halterman
*/
@Test(groups = "slow")
public class BackoffTest extends AbstractTest {
private static int counter;
static class Foo {
void doSomething() {
counter++;
throw new IllegalStateException();
}
}
public void shouldBackoff() { | // Path: src/test/java/net/jodah/sarge/AbstractTest.java
// public abstract class AbstractTest {
// protected Sarge sarge;
//
// @BeforeMethod
// protected void beforeMethod() {
// sarge = new Sarge();
// }
// }
//
// Path: src/main/java/net/jodah/sarge/Plans.java
// public final class Plans {
// private Plans() {
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker escalateOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Escalate, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker escalateOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Escalate, causeTypes);
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker onFailure(Class<? extends Throwable> causeType, Directive directive) {
// return new PlanMaker().addDirective(directive, causeType);
// }
//
// @SuppressWarnings("unchecked")
// public static PlanMaker resumeOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Resume, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker resumeOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Resume, causeTypes);
// }
//
// /**
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker rethrowOn(Class<? extends Throwable> causeType) {
// return new PlanMaker().addDirective(Directive.Rethrow, causeType);
// }
//
// /**
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker rethrowOn(Class<? extends Throwable>... causeTypes) {
// return new PlanMaker().addDirective(Directive.Rethrow, causeTypes);
// }
//
// /**
// * Create a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow} with zero wait time between retries.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, retryWindow), causeType);
// }
//
// /**
// * Performs a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow}, backing off and waiting between each retry according to
// * the {@code backoffExponent} up to {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, double backoffExponent,
// Duration maxRetryInterval) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, retryWindow,
// initialRetryInterval, backoffExponent, maxRetryInterval), causeType);
// }
//
// /**
// * Performs a retry when a failure of {@code causeType} occurs, retrying up to {@code maxRetries}
// * times within the {@code retryWindow}, backing off and waiting between each retry up to
// * {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// @SuppressWarnings("unchecked")
// public static PlanMaker retryOn(Class<? extends Throwable> causeType, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, Duration maxRetryInterval) {
// return new PlanMaker().addDirective(
// Directive.Retry(maxRetries, retryWindow, initialRetryInterval, 2, maxRetryInterval),
// causeType);
// }
//
// /**
// * Perform a retry when a failure of any of the {@code causeTypes} occurs, retrying up to
// * {@code maxRetries} times within the {@code timeRange} with zero wait time between retries.
// *
// * @throws NullPointerException if {@code causeTypes} is null
// */
// public static PlanMaker retryOn(Class<? extends Throwable>[] causeTypes, int maxRetries,
// Duration timeRange) {
// return new PlanMaker().addDirective(Directive.Retry(maxRetries, timeRange), causeTypes);
// }
//
// /**
// * Perform a retry when a failure of any of the {@code causeTypes} occurs, retrying up to
// * {@code maxRetries} times within the {@code retryWindow}, backing off and waiting between each
// * retry up to {@code maxRetryInterval}.
// *
// * @throws NullPointerException if {@code causeType} is null
// */
// public static PlanMaker retryOn(Class<? extends Throwable>[] causeTypes, int maxRetries,
// Duration retryWindow, Duration initialRetryInterval, Duration maxRetryInterval) {
// return new PlanMaker().addDirective(
// Directive.Retry(maxRetries, retryWindow, initialRetryInterval, 2, maxRetryInterval),
// causeTypes);
// }
// }
// Path: src/test/java/net/jodah/sarge/functional/BackoffTest.java
import net.jodah.sarge.AbstractTest;
import net.jodah.sarge.Plans;
import org.testng.annotations.Test;
import java.time.Duration;
import static org.testng.Assert.*;
package net.jodah.sarge.functional;
/**
* @author Jonathan Halterman
*/
@Test(groups = "slow")
public class BackoffTest extends AbstractTest {
private static int counter;
static class Foo {
void doSomething() {
counter++;
throw new IllegalStateException();
}
}
public void shouldBackoff() { | Foo foo = sarge.supervised(Foo.class, Plans.retryOn(IllegalStateException.class, 5, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.