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
|
---|---|---|---|---|---|---|
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/controller/UserFullDataProjectionResourceProcessor.java | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/RestApiConstants.java
// public final class RestApiConstants {
//
// private RestApiConstants() {
// }
//
// public static final String AUTHORITIES_RESOURCE = "authorities";
//
// public static final String UPDATE_USER_RESOURCE = "update-user";
// public static final String LOGIN_USER_RESOURCE = "login-user";
// public static final String USERS_RESOURCE = "users";
// public static final String REGISTRATIONS_RESOURCE = "registrations";
// public static final String SEARCH_RESOURCE = "search";
//
// public static final String AUTHORITY_PARAM = "authority";
// public static final String USERNAME_PARAM = "username";
// public static final String TOKEN_PARAM = "token";
//
// public static final String PROJECTION = "projection";
// public static final String CONFIRM = "confirm";
// public static final String UPDATE = "update";
// public static final String LOGIN = "login";
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/UserFullDataProjection.java
// @Projection(name = UserProjections.Values.USER_FULL_DATA, types = User.class)
// public interface UserFullDataProjection extends Identifiable<Long> {
//
// boolean isAccountNonExpired();
//
// boolean isAccountNonLocked();
//
// boolean isCredentialsNonExpired();
//
// boolean isEnabled();
//
// String getUsername();
//
// String getRememberMeToken();
//
// String getRegistrationConfirmationToken();
//
// LocalDate getRegistrationDate();
//
// LocalDateTime getLastLogin();
//
// String getEmail();
//
// String getPassword();
//
// Collection<Authority> getAuthorities();
// }
| import info.rolandkrueger.userservice.api._internal.RestApiConstants;
import info.rolandkrueger.userservice.model.UserFullDataProjection;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Component; | package info.rolandkrueger.userservice.controller;
/**
* @author Roland Krüger
*/
@Component
public class UserFullDataProjectionResourceProcessor implements ResourceProcessor<Resource<UserFullDataProjection>> {
@Override
public Resource<UserFullDataProjection> process(Resource<UserFullDataProjection> resource) {
UserFullDataProjection userData = resource.getContent();
resource.add(ControllerLinkBuilder
.linkTo(UpdateUserRestController.class)
.slash(userData) | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/RestApiConstants.java
// public final class RestApiConstants {
//
// private RestApiConstants() {
// }
//
// public static final String AUTHORITIES_RESOURCE = "authorities";
//
// public static final String UPDATE_USER_RESOURCE = "update-user";
// public static final String LOGIN_USER_RESOURCE = "login-user";
// public static final String USERS_RESOURCE = "users";
// public static final String REGISTRATIONS_RESOURCE = "registrations";
// public static final String SEARCH_RESOURCE = "search";
//
// public static final String AUTHORITY_PARAM = "authority";
// public static final String USERNAME_PARAM = "username";
// public static final String TOKEN_PARAM = "token";
//
// public static final String PROJECTION = "projection";
// public static final String CONFIRM = "confirm";
// public static final String UPDATE = "update";
// public static final String LOGIN = "login";
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/UserFullDataProjection.java
// @Projection(name = UserProjections.Values.USER_FULL_DATA, types = User.class)
// public interface UserFullDataProjection extends Identifiable<Long> {
//
// boolean isAccountNonExpired();
//
// boolean isAccountNonLocked();
//
// boolean isCredentialsNonExpired();
//
// boolean isEnabled();
//
// String getUsername();
//
// String getRememberMeToken();
//
// String getRegistrationConfirmationToken();
//
// LocalDate getRegistrationDate();
//
// LocalDateTime getLastLogin();
//
// String getEmail();
//
// String getPassword();
//
// Collection<Authority> getAuthorities();
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/controller/UserFullDataProjectionResourceProcessor.java
import info.rolandkrueger.userservice.api._internal.RestApiConstants;
import info.rolandkrueger.userservice.model.UserFullDataProjection;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Component;
package info.rolandkrueger.userservice.controller;
/**
* @author Roland Krüger
*/
@Component
public class UserFullDataProjectionResourceProcessor implements ResourceProcessor<Resource<UserFullDataProjection>> {
@Override
public Resource<UserFullDataProjection> process(Resource<UserFullDataProjection> resource) {
UserFullDataProjection userData = resource.getContent();
resource.add(ControllerLinkBuilder
.linkTo(UpdateUserRestController.class)
.slash(userData) | .withRel(RestApiConstants.UPDATE)); |
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/controller/UserExcerptProjectionResourceProcessor.java | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/RestApiConstants.java
// public final class RestApiConstants {
//
// private RestApiConstants() {
// }
//
// public static final String AUTHORITIES_RESOURCE = "authorities";
//
// public static final String UPDATE_USER_RESOURCE = "update-user";
// public static final String LOGIN_USER_RESOURCE = "login-user";
// public static final String USERS_RESOURCE = "users";
// public static final String REGISTRATIONS_RESOURCE = "registrations";
// public static final String SEARCH_RESOURCE = "search";
//
// public static final String AUTHORITY_PARAM = "authority";
// public static final String USERNAME_PARAM = "username";
// public static final String TOKEN_PARAM = "token";
//
// public static final String PROJECTION = "projection";
// public static final String CONFIRM = "confirm";
// public static final String UPDATE = "update";
// public static final String LOGIN = "login";
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/UserExcerptProjection.java
// @Projection(name = UserProjections.Values.USER_EXCERPT_DATA, types = User.class)
// public interface UserExcerptProjection extends Identifiable<Long> {
// String getUsername();
//
// LocalDate getRegistrationDate();
//
// LocalDateTime getLastLogin();
//
// String getEmail();
// }
| import info.rolandkrueger.userservice.api._internal.RestApiConstants;
import info.rolandkrueger.userservice.model.UserExcerptProjection;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Component; | package info.rolandkrueger.userservice.controller;
/**
* @author Roland Krüger
*/
@Component
public class UserExcerptProjectionResourceProcessor implements ResourceProcessor<Resource<UserExcerptProjection>> {
@Override
public Resource<UserExcerptProjection> process(Resource<UserExcerptProjection> resource) {
resource.add(ControllerLinkBuilder
.linkTo(UpdateUserRestController.class)
.slash(resource.getContent()) | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/RestApiConstants.java
// public final class RestApiConstants {
//
// private RestApiConstants() {
// }
//
// public static final String AUTHORITIES_RESOURCE = "authorities";
//
// public static final String UPDATE_USER_RESOURCE = "update-user";
// public static final String LOGIN_USER_RESOURCE = "login-user";
// public static final String USERS_RESOURCE = "users";
// public static final String REGISTRATIONS_RESOURCE = "registrations";
// public static final String SEARCH_RESOURCE = "search";
//
// public static final String AUTHORITY_PARAM = "authority";
// public static final String USERNAME_PARAM = "username";
// public static final String TOKEN_PARAM = "token";
//
// public static final String PROJECTION = "projection";
// public static final String CONFIRM = "confirm";
// public static final String UPDATE = "update";
// public static final String LOGIN = "login";
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/UserExcerptProjection.java
// @Projection(name = UserProjections.Values.USER_EXCERPT_DATA, types = User.class)
// public interface UserExcerptProjection extends Identifiable<Long> {
// String getUsername();
//
// LocalDate getRegistrationDate();
//
// LocalDateTime getLastLogin();
//
// String getEmail();
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/controller/UserExcerptProjectionResourceProcessor.java
import info.rolandkrueger.userservice.api._internal.RestApiConstants;
import info.rolandkrueger.userservice.model.UserExcerptProjection;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.stereotype.Component;
package info.rolandkrueger.userservice.controller;
/**
* @author Roland Krüger
*/
@Component
public class UserExcerptProjectionResourceProcessor implements ResourceProcessor<Resource<UserExcerptProjection>> {
@Override
public Resource<UserExcerptProjection> process(Resource<UserExcerptProjection> resource) {
resource.add(ControllerLinkBuilder
.linkTo(UpdateUserRestController.class)
.slash(resource.getContent()) | .withRel(RestApiConstants.UPDATE)); |
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/service/AuthorityServiceImpl.java | // Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/repository/AuthorityRepository.java
// public interface AuthorityRepository extends PagingAndSortingRepository<Authority, Long> {
// Authority findByAuthority(@Param(RestApiConstants.AUTHORITY_PARAM) String authority);
//
// @RestResource(exported = false)
// @Override Iterable<Authority> findAll();
// }
| import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@Service
public class AuthorityServiceImpl implements AuthorityService {
| // Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/repository/AuthorityRepository.java
// public interface AuthorityRepository extends PagingAndSortingRepository<Authority, Long> {
// Authority findByAuthority(@Param(RestApiConstants.AUTHORITY_PARAM) String authority);
//
// @RestResource(exported = false)
// @Override Iterable<Authority> findAll();
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/service/AuthorityServiceImpl.java
import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@Service
public class AuthorityServiceImpl implements AuthorityService {
| private AuthorityRepository authorityRepository; |
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/service/AuthorityServiceImpl.java | // Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/repository/AuthorityRepository.java
// public interface AuthorityRepository extends PagingAndSortingRepository<Authority, Long> {
// Authority findByAuthority(@Param(RestApiConstants.AUTHORITY_PARAM) String authority);
//
// @RestResource(exported = false)
// @Override Iterable<Authority> findAll();
// }
| import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@Service
public class AuthorityServiceImpl implements AuthorityService {
private AuthorityRepository authorityRepository;
@Override | // Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/repository/AuthorityRepository.java
// public interface AuthorityRepository extends PagingAndSortingRepository<Authority, Long> {
// Authority findByAuthority(@Param(RestApiConstants.AUTHORITY_PARAM) String authority);
//
// @RestResource(exported = false)
// @Override Iterable<Authority> findAll();
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/service/AuthorityServiceImpl.java
import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@Service
public class AuthorityServiceImpl implements AuthorityService {
private AuthorityRepository authorityRepository;
@Override | public Authority findByAuthority(String authority) { |
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/application/GlobalControllerExceptionHandler.java | // Path: service/src/main/java/info/rolandkrueger/userservice/model/ServiceError.java
// public class ServiceError {
// private String error;
// private String message;
//
// public ServiceError(Exception exception) {
// this.message = exception.getMessage();
// this.error = exception.getClass().getSimpleName();
// }
//
// public String getError() {
// return error;
// }
//
// public String getMessage() {
// return message;
// }
// }
| import info.rolandkrueger.userservice.model.ServiceError;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.ws.rs.NotFoundException; | package info.rolandkrueger.userservice.application;
/**
* @author Roland Krüger
*/
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody | // Path: service/src/main/java/info/rolandkrueger/userservice/model/ServiceError.java
// public class ServiceError {
// private String error;
// private String message;
//
// public ServiceError(Exception exception) {
// this.message = exception.getMessage();
// this.error = exception.getClass().getSimpleName();
// }
//
// public String getError() {
// return error;
// }
//
// public String getMessage() {
// return message;
// }
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/application/GlobalControllerExceptionHandler.java
import info.rolandkrueger.userservice.model.ServiceError;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.ws.rs.NotFoundException;
package info.rolandkrueger.userservice.application;
/**
* @author Roland Krüger
*/
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody | public ServiceError handleNotFoundException(NotFoundException notFoundException) { |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/repository/AuthorityRepositoryTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat; | package info.rolandkrueger.userservice.repository;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional
public class AuthorityRepositoryTest { | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/repository/AuthorityRepositoryTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
package info.rolandkrueger.userservice.repository;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional
public class AuthorityRepositoryTest { | private Authority authority; |
rolandkrueger/user-microservice | service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java | // Path: service/src/main/java/info/rolandkrueger/userservice/application/DevelopmentProfileConfiguration.java
// @Component
// @Profile("DEV")
// public class DevelopmentProfileConfiguration implements ApplicationListener<ContextRefreshedEvent> {
//
// private final static Logger LOG = LoggerFactory.getLogger(DevelopmentProfileConfiguration.class);
//
// public final static Authority adminAuthority, userAuthority, developerAuthority;
// public final static User alice, bob, charly;
//
// static {
// LOG.info("Creating test data: authorities 'admin', 'user', 'developer'");
//
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
//
// LOG.info("Creating test data: users 'alice', 'bob', 'charly'");
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
// }
//
// @Autowired
// private UserRepository userRepository;
//
// @Autowired
// private AuthorityRepository authorityRepository;
//
// @Override
// public void onApplicationEvent(ContextRefreshedEvent event) {
// saveAuthorities();
// saveUsers();
// }
//
// private void saveAuthorities() {
// authorityRepository.save(Arrays.asList(adminAuthority, userAuthority, developerAuthority));
// }
//
// private void saveUsers() {
// final List<User> users = Arrays.asList(alice, bob, charly);
// userRepository.save(users);
// LOG.info("Added users {}", users);
// }
// }
| import info.rolandkrueger.userservice.application.DevelopmentProfileConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource; | package info.rolandkrueger.userservice;
@SpringBootApplication
@PropertySource("userservice.properties")
public class UserMicroserviceApplication {
public static void main(String[] args) {
SpringApplication.run(
new Object[]{
UserMicroserviceApplication.class, | // Path: service/src/main/java/info/rolandkrueger/userservice/application/DevelopmentProfileConfiguration.java
// @Component
// @Profile("DEV")
// public class DevelopmentProfileConfiguration implements ApplicationListener<ContextRefreshedEvent> {
//
// private final static Logger LOG = LoggerFactory.getLogger(DevelopmentProfileConfiguration.class);
//
// public final static Authority adminAuthority, userAuthority, developerAuthority;
// public final static User alice, bob, charly;
//
// static {
// LOG.info("Creating test data: authorities 'admin', 'user', 'developer'");
//
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
//
// LOG.info("Creating test data: users 'alice', 'bob', 'charly'");
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
// }
//
// @Autowired
// private UserRepository userRepository;
//
// @Autowired
// private AuthorityRepository authorityRepository;
//
// @Override
// public void onApplicationEvent(ContextRefreshedEvent event) {
// saveAuthorities();
// saveUsers();
// }
//
// private void saveAuthorities() {
// authorityRepository.save(Arrays.asList(adminAuthority, userAuthority, developerAuthority));
// }
//
// private void saveUsers() {
// final List<User> users = Arrays.asList(alice, bob, charly);
// userRepository.save(users);
// LOG.info("Added users {}", users);
// }
// }
// Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
import info.rolandkrueger.userservice.application.DevelopmentProfileConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
package info.rolandkrueger.userservice;
@SpringBootApplication
@PropertySource("userservice.properties")
public class UserMicroserviceApplication {
public static void main(String[] args) {
SpringApplication.run(
new Object[]{
UserMicroserviceApplication.class, | DevelopmentProfileConfiguration.class} |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/AuthorityServiceTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractServiceTest.java
// @Transactional
// public abstract class AbstractServiceTest {
//
// public Authority adminAuthority, userAuthority, developerAuthority;
// public User alice, bob, charly;
//
// public AbstractServiceTest() {
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
// }
//
// protected void createTestData(AuthorityService authorityService, UserService userService) {
// Arrays.asList(adminAuthority, userAuthority, developerAuthority)
// .stream()
// .forEach(authorityService::create);
//
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
//
// Arrays.asList(alice, bob, charly)
// .stream()
// .forEach(userService::save);
// }
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.testsupport.AbstractServiceTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.number.OrderingComparison.greaterThan; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractServiceTest.java
// @Transactional
// public abstract class AbstractServiceTest {
//
// public Authority adminAuthority, userAuthority, developerAuthority;
// public User alice, bob, charly;
//
// public AbstractServiceTest() {
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
// }
//
// protected void createTestData(AuthorityService authorityService, UserService userService) {
// Arrays.asList(adminAuthority, userAuthority, developerAuthority)
// .stream()
// .forEach(authorityService::create);
//
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
//
// Arrays.asList(alice, bob, charly)
// .stream()
// .forEach(userService::save);
// }
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/service/AuthorityServiceTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.testsupport.AbstractServiceTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.number.OrderingComparison.greaterThan;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional | public class AuthorityServiceTest extends AbstractServiceTest { |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/AuthorityServiceTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractServiceTest.java
// @Transactional
// public abstract class AbstractServiceTest {
//
// public Authority adminAuthority, userAuthority, developerAuthority;
// public User alice, bob, charly;
//
// public AbstractServiceTest() {
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
// }
//
// protected void createTestData(AuthorityService authorityService, UserService userService) {
// Arrays.asList(adminAuthority, userAuthority, developerAuthority)
// .stream()
// .forEach(authorityService::create);
//
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
//
// Arrays.asList(alice, bob, charly)
// .stream()
// .forEach(userService::save);
// }
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.testsupport.AbstractServiceTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.number.OrderingComparison.greaterThan; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional
public class AuthorityServiceTest extends AbstractServiceTest {
@Autowired
private AuthorityService authorityService;
@Autowired
private UserService userService;
@Before
public void setUp() {
createTestData(authorityService, userService);
}
@Test
public void testFindByAuthority() throws Exception { | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: service/src/main/java/info/rolandkrueger/userservice/model/Authority.java
// @Entity
// public class Authority implements GrantedAuthority {
// private Long id;
// @Version
// Long version;
// @LastModifiedDate
// LocalDateTime lastModified;
//
// @NotBlank
// private String authority;
//
// private String description;
//
// private Authority() {
// lastModified = LocalDateTime.now();
// version = 1L;
// }
//
// public Authority(String authority) {
// this();
// setAuthority(authority);
// }
//
// public Authority(String authority, String description) {
// this(authority);
// this.description = description;
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// protected void setAuthority(String authority) {
// Preconditions.checkArgument(!Strings.isNullOrEmpty(MoreObjects.firstNonNull(authority, "").trim()));
// this.authority = authority;
// }
//
// @Override
// @Column(unique = true)
// public String getAuthority() {
// return authority;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public LocalDateTime getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(LocalDateTime lastModified) {
// this.lastModified = lastModified;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(Authority.class)
// .add("authority", authority)
// .toString();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof Authority)) {
// return false;
// }
// if (obj == this) {
// return true;
// }
// Authority other = (Authority) obj;
// return Objects.equals(authority, other.authority);
// }
//
// @Override
// public int hashCode() {
// return authority.hashCode();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractServiceTest.java
// @Transactional
// public abstract class AbstractServiceTest {
//
// public Authority adminAuthority, userAuthority, developerAuthority;
// public User alice, bob, charly;
//
// public AbstractServiceTest() {
// adminAuthority = new Authority("admin", "The admin role");
// userAuthority = new Authority("user", "The user role");
// developerAuthority = new Authority("developer", "The developer role");
// }
//
// protected void createTestData(AuthorityService authorityService, UserService userService) {
// Arrays.asList(adminAuthority, userAuthority, developerAuthority)
// .stream()
// .forEach(authorityService::create);
//
// alice = new User("alice");
// alice.setUnencryptedPassword("alice");
// alice.createRegistrationConfirmationToken();
// alice.setEmail("[email protected]");
// alice.addAuthority(adminAuthority);
//
// bob = new User("bob");
// bob.setUnencryptedPassword("bob");
// bob.addAuthority(developerAuthority);
// bob.addAuthority(userAuthority);
//
// charly = new User("charly");
// charly.setLastLogin(LocalDateTime.now());
// charly.setUnencryptedPassword("charly");
//
// Arrays.asList(alice, bob, charly)
// .stream()
// .forEach(userService::save);
// }
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/service/AuthorityServiceTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.model.Authority;
import info.rolandkrueger.userservice.testsupport.AbstractServiceTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.number.OrderingComparison.greaterThan;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@Transactional
public class AuthorityServiceTest extends AbstractServiceTest {
@Autowired
private AuthorityService authorityService;
@Autowired
private UserService userService;
@Before
public void setUp() {
createTestData(authorityService, userService);
}
@Test
public void testFindByAuthority() throws Exception { | final Authority authority = authorityService.findByAuthority("admin"); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
| import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter; | package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException { |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
| import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter; | package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException { |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
| import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter; | package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/ReportFactory.java
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.rule.Rule;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
package org.graylog.plugins.aggregates.report;
public class ReportFactory {
private static final Logger LOG = LoggerFactory.getLogger(ReportFactory.class);
| public static void createReport(Map<Rule, List<HistoryAggregateItem>> series, Map<Rule, ReportSchedule> ruleScheduleMapping, Calendar cal, OutputStream outputStream, String hostname) throws ParseException { |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleServiceImpl.java | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
| import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import org.bson.types.ObjectId;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import org.graylog2.bindings.providers.MongoJackObjectMapperProvider;
import org.graylog2.database.CollectionName;
import org.graylog2.database.MongoConnection;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.DBUpdate;
import org.mongojack.JacksonDBCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Set; | package org.graylog.plugins.aggregates.report.schedule;
public class ReportScheduleServiceImpl implements ReportScheduleService {
private final JacksonDBCollection<ReportScheduleImpl, String> coll; | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleServiceImpl.java
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import org.bson.types.ObjectId;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import org.graylog2.bindings.providers.MongoJackObjectMapperProvider;
import org.graylog2.database.CollectionName;
import org.graylog2.database.MongoConnection;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.DBUpdate;
import org.mongojack.JacksonDBCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Set;
package org.graylog.plugins.aggregates.report.schedule;
public class ReportScheduleServiceImpl implements ReportScheduleService {
private final JacksonDBCollection<ReportScheduleImpl, String> coll; | private final JacksonDBCollection<RuleImpl, String> ruleColl; |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/responses/ReportSchedulesList.java | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
| import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule; | package org.graylog.plugins.aggregates.report.schedule.rest.models.responses;
@AutoValue
@JsonAutoDetect
public abstract class ReportSchedulesList {
@JsonProperty | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/responses/ReportSchedulesList.java
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
package org.graylog.plugins.aggregates.report.schedule.rest.models.responses;
@AutoValue
@JsonAutoDetect
public abstract class ReportSchedulesList {
@JsonProperty | public abstract List<ReportSchedule> getReportSchedules(); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java
// public class AggregatesUtil {
// public final static String ALERT_CONDITION_TYPE = "Aggregates Alert";
//
// public static int timespanToSeconds(String timespan, Calendar cal){
// Period period = Period.parse(timespan);
// Duration duration = period.toDurationFrom(new DateTime(cal.getTime()));
// return duration.toStandardSeconds().getSeconds();
// }
//
// public static String getAlertConditionDescription(Rule rule){
// String matchDescriptor = rule.getNumberOfMatches() + " or more";
// if (!rule.isMatchMoreOrEqual()){
// matchDescriptor = "less than " + rule.getNumberOfMatches();
// }
// return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval";
// }
//
// public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException {
//
// final StringBuilder sb = new StringBuilder();
//
// sb.append("Matched values for field [ " + rule.getField() + " ]\n");
//
// for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) {
//
// sb.append("\nValue: " + entry.getKey() + "\n");
// sb.append("Occurrences: " + entry.getValue() + "\n");
//
// if (!emailConfiguration.isEnabled()) {
// sb.append("\n");
// } else {
// String streamId = rule.getStreamId();
// String search_uri = "";
//
// if (streamId != null && streamId != "") {
// search_uri += "/streams/" + streamId;
// }
// search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8");
// sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n");
//
// }
// }
// return sb.toString();
//
// }
//
// public static Map<String, Object> parametersFromRule(Rule rule){
// String query = rule.getQuery();
// String streamId = rule.getStreamId();
//
// Map<String, Object> parameters = new HashMap<String, Object>();
// parameters.put("time", rule.getInterval());
// parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule));
//
// if (rule.isMatchMoreOrEqual()){
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString());
// } else {
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString());
// }
//
// parameters.put("threshold", rule.getNumberOfMatches());
// parameters.put("grace", 0);
// parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE);
// parameters.put("field", rule.getField());
// parameters.put("number_of_matches", rule.getNumberOfMatches());
// parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual());
// parameters.put("backlog", rule.getBacklog());
// parameters.put("repeat_notifications", rule.shouldRepeatNotifications());
// parameters.put("interval", rule.getInterval());
// parameters.put("query", query);
// parameters.put("rule_name", rule.getName());
//
// return parameters;
// }
//
// public static String alertConditionTitleFromRule(Rule rule){
// return "Aggregate rule [" + rule.getName() + "] triggered an alert.";
// }
// }
| import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.util.AggregatesUtil;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Day;
import org.jfree.data.time.Hour;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.Year;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYBarDataset;
import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting; | package org.graylog.plugins.aggregates.report;
public class ChartFactory {
private final static int SECONDS_IN_YEAR = 3600*24*366;
private final static int SECONDS_IN_MONTH = 3600*24*31;
private final static int SECONDS_IN_DAY = 3600*24;
private final static int SECONDS_IN_HOUR = 3600;
@SuppressWarnings("deprecation")
@VisibleForTesting | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java
// public class AggregatesUtil {
// public final static String ALERT_CONDITION_TYPE = "Aggregates Alert";
//
// public static int timespanToSeconds(String timespan, Calendar cal){
// Period period = Period.parse(timespan);
// Duration duration = period.toDurationFrom(new DateTime(cal.getTime()));
// return duration.toStandardSeconds().getSeconds();
// }
//
// public static String getAlertConditionDescription(Rule rule){
// String matchDescriptor = rule.getNumberOfMatches() + " or more";
// if (!rule.isMatchMoreOrEqual()){
// matchDescriptor = "less than " + rule.getNumberOfMatches();
// }
// return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval";
// }
//
// public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException {
//
// final StringBuilder sb = new StringBuilder();
//
// sb.append("Matched values for field [ " + rule.getField() + " ]\n");
//
// for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) {
//
// sb.append("\nValue: " + entry.getKey() + "\n");
// sb.append("Occurrences: " + entry.getValue() + "\n");
//
// if (!emailConfiguration.isEnabled()) {
// sb.append("\n");
// } else {
// String streamId = rule.getStreamId();
// String search_uri = "";
//
// if (streamId != null && streamId != "") {
// search_uri += "/streams/" + streamId;
// }
// search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8");
// sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n");
//
// }
// }
// return sb.toString();
//
// }
//
// public static Map<String, Object> parametersFromRule(Rule rule){
// String query = rule.getQuery();
// String streamId = rule.getStreamId();
//
// Map<String, Object> parameters = new HashMap<String, Object>();
// parameters.put("time", rule.getInterval());
// parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule));
//
// if (rule.isMatchMoreOrEqual()){
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString());
// } else {
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString());
// }
//
// parameters.put("threshold", rule.getNumberOfMatches());
// parameters.put("grace", 0);
// parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE);
// parameters.put("field", rule.getField());
// parameters.put("number_of_matches", rule.getNumberOfMatches());
// parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual());
// parameters.put("backlog", rule.getBacklog());
// parameters.put("repeat_notifications", rule.shouldRepeatNotifications());
// parameters.put("interval", rule.getInterval());
// parameters.put("query", query);
// parameters.put("rule_name", rule.getName());
//
// return parameters;
// }
//
// public static String alertConditionTitleFromRule(Rule rule){
// return "Aggregate rule [" + rule.getName() + "] triggered an alert.";
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java
import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.util.AggregatesUtil;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Day;
import org.jfree.data.time.Hour;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.Year;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYBarDataset;
import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting;
package org.graylog.plugins.aggregates.report;
public class ChartFactory {
private final static int SECONDS_IN_YEAR = 3600*24*366;
private final static int SECONDS_IN_MONTH = 3600*24*31;
private final static int SECONDS_IN_DAY = 3600*24;
private final static int SECONDS_IN_HOUR = 3600;
@SuppressWarnings("deprecation")
@VisibleForTesting | private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{ |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java
// public class AggregatesUtil {
// public final static String ALERT_CONDITION_TYPE = "Aggregates Alert";
//
// public static int timespanToSeconds(String timespan, Calendar cal){
// Period period = Period.parse(timespan);
// Duration duration = period.toDurationFrom(new DateTime(cal.getTime()));
// return duration.toStandardSeconds().getSeconds();
// }
//
// public static String getAlertConditionDescription(Rule rule){
// String matchDescriptor = rule.getNumberOfMatches() + " or more";
// if (!rule.isMatchMoreOrEqual()){
// matchDescriptor = "less than " + rule.getNumberOfMatches();
// }
// return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval";
// }
//
// public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException {
//
// final StringBuilder sb = new StringBuilder();
//
// sb.append("Matched values for field [ " + rule.getField() + " ]\n");
//
// for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) {
//
// sb.append("\nValue: " + entry.getKey() + "\n");
// sb.append("Occurrences: " + entry.getValue() + "\n");
//
// if (!emailConfiguration.isEnabled()) {
// sb.append("\n");
// } else {
// String streamId = rule.getStreamId();
// String search_uri = "";
//
// if (streamId != null && streamId != "") {
// search_uri += "/streams/" + streamId;
// }
// search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8");
// sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n");
//
// }
// }
// return sb.toString();
//
// }
//
// public static Map<String, Object> parametersFromRule(Rule rule){
// String query = rule.getQuery();
// String streamId = rule.getStreamId();
//
// Map<String, Object> parameters = new HashMap<String, Object>();
// parameters.put("time", rule.getInterval());
// parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule));
//
// if (rule.isMatchMoreOrEqual()){
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString());
// } else {
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString());
// }
//
// parameters.put("threshold", rule.getNumberOfMatches());
// parameters.put("grace", 0);
// parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE);
// parameters.put("field", rule.getField());
// parameters.put("number_of_matches", rule.getNumberOfMatches());
// parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual());
// parameters.put("backlog", rule.getBacklog());
// parameters.put("repeat_notifications", rule.shouldRepeatNotifications());
// parameters.put("interval", rule.getInterval());
// parameters.put("query", query);
// parameters.put("rule_name", rule.getName());
//
// return parameters;
// }
//
// public static String alertConditionTitleFromRule(Rule rule){
// return "Aggregate rule [" + rule.getName() + "] triggered an alert.";
// }
// }
| import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.util.AggregatesUtil;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Day;
import org.jfree.data.time.Hour;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.Year;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYBarDataset;
import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting; | package org.graylog.plugins.aggregates.report;
public class ChartFactory {
private final static int SECONDS_IN_YEAR = 3600*24*366;
private final static int SECONDS_IN_MONTH = 3600*24*31;
private final static int SECONDS_IN_DAY = 3600*24;
private final static int SECONDS_IN_HOUR = 3600;
@SuppressWarnings("deprecation")
@VisibleForTesting
private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{
Calendar cal = (Calendar) calParam.clone();
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/util/AggregatesUtil.java
// public class AggregatesUtil {
// public final static String ALERT_CONDITION_TYPE = "Aggregates Alert";
//
// public static int timespanToSeconds(String timespan, Calendar cal){
// Period period = Period.parse(timespan);
// Duration duration = period.toDurationFrom(new DateTime(cal.getTime()));
// return duration.toStandardSeconds().getSeconds();
// }
//
// public static String getAlertConditionDescription(Rule rule){
// String matchDescriptor = rule.getNumberOfMatches() + " or more";
// if (!rule.isMatchMoreOrEqual()){
// matchDescriptor = "less than " + rule.getNumberOfMatches();
// }
// return "The same value of field '" + rule.getField() + "' occurs " + matchDescriptor + " times in a " + rule.getInterval() + " minute interval";
// }
//
// public String buildSummary(Rule rule, EmailConfiguration emailConfiguration, Map<String, Long> matchedTerms, TimeRange timeRange) throws UnsupportedEncodingException {
//
// final StringBuilder sb = new StringBuilder();
//
// sb.append("Matched values for field [ " + rule.getField() + " ]\n");
//
// for (Map.Entry<String, Long> entry : matchedTerms.entrySet()) {
//
// sb.append("\nValue: " + entry.getKey() + "\n");
// sb.append("Occurrences: " + entry.getValue() + "\n");
//
// if (!emailConfiguration.isEnabled()) {
// sb.append("\n");
// } else {
// String streamId = rule.getStreamId();
// String search_uri = "";
//
// if (streamId != null && streamId != "") {
// search_uri += "/streams/" + streamId;
// }
// search_uri += "/search?rangetype=absolute&fields=message%2Csource%2C" + rule.getField() + "&from=" + timeRange.getFrom() + "&to=" + timeRange.getTo() + "&q=" + URLEncoder.encode(rule.getQuery() + " AND " + rule.getField() + ":\"" + entry.getKey() + "\"", "UTF-8");
// sb.append("Search: " + emailConfiguration.getWebInterfaceUri() + search_uri + "\n");
//
// }
// }
// return sb.toString();
//
// }
//
// public static Map<String, Object> parametersFromRule(Rule rule){
// String query = rule.getQuery();
// String streamId = rule.getStreamId();
//
// Map<String, Object> parameters = new HashMap<String, Object>();
// parameters.put("time", rule.getInterval());
// parameters.put("description", AggregatesUtil.getAlertConditionDescription(rule));
//
// if (rule.isMatchMoreOrEqual()){
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.MORE_OR_EQUAL.toString());
// } else {
// parameters.put("threshold_type", AggregatesAlertCondition.ThresholdType.LESS.toString());
// }
//
// parameters.put("threshold", rule.getNumberOfMatches());
// parameters.put("grace", 0);
// parameters.put("type", AggregatesUtil.ALERT_CONDITION_TYPE);
// parameters.put("field", rule.getField());
// parameters.put("number_of_matches", rule.getNumberOfMatches());
// parameters.put("match_more_or_equal", rule.isMatchMoreOrEqual());
// parameters.put("backlog", rule.getBacklog());
// parameters.put("repeat_notifications", rule.shouldRepeatNotifications());
// parameters.put("interval", rule.getInterval());
// parameters.put("query", query);
// parameters.put("rule_name", rule.getName());
//
// return parameters;
// }
//
// public static String alertConditionTitleFromRule(Rule rule){
// return "Aggregate rule [" + rule.getName() + "] triggered an alert.";
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/ChartFactory.java
import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.util.AggregatesUtil;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Day;
import org.jfree.data.time.Hour;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.Year;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYBarDataset;
import autovalue.shaded.com.google.common.common.annotations.VisibleForTesting;
package org.graylog.plugins.aggregates.report;
public class ChartFactory {
private final static int SECONDS_IN_YEAR = 3600*24*366;
private final static int SECONDS_IN_MONTH = 3600*24*31;
private final static int SECONDS_IN_DAY = 3600*24;
private final static int SECONDS_IN_HOUR = 3600;
@SuppressWarnings("deprecation")
@VisibleForTesting
private static TimeSeries initializeSeries(String timespan, Calendar calParam, List<HistoryAggregateItem> history) throws ParseException{
Calendar cal = (Calendar) calParam.clone();
| int seconds = AggregatesUtil.timespanToSeconds(timespan, cal); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
| import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import com.mongodb.MongoException; | package org.graylog.plugins.aggregates.report.schedule;
public interface ReportScheduleService {
long count();
ReportSchedule update(String name, ReportSchedule schedule);
ReportSchedule create(ReportSchedule schedule);
List<ReportSchedule> all();
int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
| // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.report.schedule;
public interface ReportScheduleService {
long count();
ReportSchedule update(String name, ReportSchedule schedule);
ReportSchedule create(ReportSchedule schedule);
List<ReportSchedule> all();
int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
| ReportSchedule fromRequest(AddReportScheduleRequest request); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java | // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
| import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import com.mongodb.MongoException; | package org.graylog.plugins.aggregates.report.schedule;
public interface ReportScheduleService {
long count();
ReportSchedule update(String name, ReportSchedule schedule);
ReportSchedule create(ReportSchedule schedule);
List<ReportSchedule> all();
int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
ReportSchedule fromRequest(AddReportScheduleRequest request);
| // Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/AddReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddReportScheduleRequest {
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static AddReportScheduleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
//
// ) {
// return new AutoValue_AddReportScheduleRequest(reportSchedule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/rest/models/requests/UpdateReportScheduleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateReportScheduleRequest {
//
//
// @JsonProperty("reportSchedule")
// @NotNull
// public abstract ReportScheduleImpl getReportSchedule();
//
// @JsonCreator
// public static UpdateReportScheduleRequest create(
// @JsonProperty("reportSchedule") @Valid ReportScheduleImpl reportSchedule
// ) {
// return new AutoValue_UpdateReportScheduleRequest(reportSchedule);
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.AddReportScheduleRequest;
import org.graylog.plugins.aggregates.report.schedule.rest.models.requests.UpdateReportScheduleRequest;
import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.report.schedule;
public interface ReportScheduleService {
long count();
ReportSchedule update(String name, ReportSchedule schedule);
ReportSchedule create(ReportSchedule schedule);
List<ReportSchedule> all();
int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
ReportSchedule fromRequest(AddReportScheduleRequest request);
| ReportSchedule fromRequest(UpdateReportScheduleRequest request); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java | // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddRuleRequest {
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static AddRuleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("rule") @Valid RuleImpl rule
//
// ) {
// return new AutoValue_AddRuleRequest(rule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateRuleRequest {
//
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static UpdateRuleRequest create(
// @JsonProperty("rule") @Valid RuleImpl rule
// ) {
// return new AutoValue_UpdateRuleRequest(rule);
// }
// }
| import java.io.UnsupportedEncodingException;
import java.util.List;
import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest;
import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest;
import com.mongodb.MongoException; | package org.graylog.plugins.aggregates.rule;
public interface RuleService {
long count();
Rule update(String name, Rule rule);
Rule create(Rule rule);
List<Rule> all();
int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
| // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddRuleRequest {
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static AddRuleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("rule") @Valid RuleImpl rule
//
// ) {
// return new AutoValue_AddRuleRequest(rule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateRuleRequest {
//
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static UpdateRuleRequest create(
// @JsonProperty("rule") @Valid RuleImpl rule
// ) {
// return new AutoValue_UpdateRuleRequest(rule);
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest;
import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest;
import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.rule;
public interface RuleService {
long count();
Rule update(String name, Rule rule);
Rule create(Rule rule);
List<Rule> all();
int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
| Rule fromRequest(AddRuleRequest request); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java | // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddRuleRequest {
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static AddRuleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("rule") @Valid RuleImpl rule
//
// ) {
// return new AutoValue_AddRuleRequest(rule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateRuleRequest {
//
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static UpdateRuleRequest create(
// @JsonProperty("rule") @Valid RuleImpl rule
// ) {
// return new AutoValue_UpdateRuleRequest(rule);
// }
// }
| import java.io.UnsupportedEncodingException;
import java.util.List;
import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest;
import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest;
import com.mongodb.MongoException; | package org.graylog.plugins.aggregates.rule;
public interface RuleService {
long count();
Rule update(String name, Rule rule);
Rule create(Rule rule);
List<Rule> all();
int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
Rule fromRequest(AddRuleRequest request);
| // Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class AddRuleRequest {
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static AddRuleRequest create(//@JsonProperty("name") @Valid String name,
// @JsonProperty("rule") @Valid RuleImpl rule
//
// ) {
// return new AutoValue_AddRuleRequest(rule);
// }
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
// @AutoValue
// @JsonAutoDetect
// public abstract class UpdateRuleRequest {
//
//
// @JsonProperty("rule")
// @NotNull
// public abstract RuleImpl getRule();
//
// @JsonCreator
// public static UpdateRuleRequest create(
// @JsonProperty("rule") @Valid RuleImpl rule
// ) {
// return new AutoValue_UpdateRuleRequest(rule);
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.graylog.plugins.aggregates.rule.rest.models.requests.AddRuleRequest;
import org.graylog.plugins.aggregates.rule.rest.models.requests.UpdateRuleRequest;
import com.mongodb.MongoException;
package org.graylog.plugins.aggregates.rule;
public interface RuleService {
long count();
Rule update(String name, Rule rule);
Rule create(Rule rule);
List<Rule> all();
int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
Rule fromRequest(AddRuleRequest request);
| Rule fromRequest(UpdateRuleRequest request); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
| import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; | package org.graylog.plugins.aggregates.rule.rest.models.requests;
@AutoValue
@JsonAutoDetect
public abstract class UpdateRuleRequest {
@JsonProperty("rule")
@NotNull | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/UpdateRuleRequest.java
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
package org.graylog.plugins.aggregates.rule.rest.models.requests;
@AutoValue
@JsonAutoDetect
public abstract class UpdateRuleRequest {
@JsonProperty("rule")
@NotNull | public abstract RuleImpl getRule(); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender; | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender; | private final HistoryItemService historyItemService; |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService; | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService; | private final RuleService ruleService; |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService;
private final RuleService ruleService; | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService;
private final RuleService ruleService; | private final ReportScheduleService reportScheduleService; |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService;
private final RuleService ruleService;
private final ReportScheduleService reportScheduleService;
private String hostname = "localhost";
@Inject
public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService,
ReportScheduleService reportScheduleService) {
this.reportSender = reportSender;
this.historyItemService = historyItemService;
this.ruleService = ruleService;
this.reportScheduleService = reportScheduleService;
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
this.hostname = addr.getCanonicalHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.graylog.plugins.aggregates.report;
public class AggregatesReport extends Periodical {
private static final Logger LOG = LoggerFactory.getLogger(AggregatesReport.class);
private final ReportSender reportSender;
private final HistoryItemService historyItemService;
private final RuleService ruleService;
private final ReportScheduleService reportScheduleService;
private String hostname = "localhost";
@Inject
public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService,
ReportScheduleService reportScheduleService) {
this.reportSender = reportSender;
this.historyItemService = historyItemService;
this.ruleService = ruleService;
this.reportScheduleService = reportScheduleService;
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
this.hostname = addr.getCanonicalHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
| private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) { |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
@Inject
public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService,
ReportScheduleService reportScheduleService) {
this.reportSender = reportSender;
this.historyItemService = historyItemService;
this.ruleService = ruleService;
this.reportScheduleService = reportScheduleService;
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
this.hostname = addr.getCanonicalHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) {
CronExpression c;
try {
c = new CronExpression(reportSchedule.getExpression());
reportScheduleService.updateNextFireTime(reportSchedule.getId(), c.getNextValidTimeAfter(cal.getTime()));
} catch (ParseException e) {
LOG.error("Schedule " + reportSchedule.getName() + " has invalid Cron Expression "
+ reportSchedule.getExpression());
}
}
| // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Inject
public AggregatesReport(ReportSender reportSender, HistoryItemService historyItemService, RuleService ruleService,
ReportScheduleService reportScheduleService) {
this.reportSender = reportSender;
this.historyItemService = historyItemService;
this.ruleService = ruleService;
this.reportScheduleService = reportScheduleService;
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
this.hostname = addr.getCanonicalHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
private void setNewFireTime(ReportSchedule reportSchedule, Calendar cal) {
CronExpression c;
try {
c = new CronExpression(reportSchedule.getExpression());
reportScheduleService.updateNextFireTime(reportSchedule.getId(), c.getNextValidTimeAfter(cal.getTime()));
} catch (ParseException e) {
LOG.error("Schedule " + reportSchedule.getName() + " has invalid Cron Expression "
+ reportSchedule.getExpression());
}
}
| private ReportSchedule getMatchingSchedule(Rule rule, List<ReportSchedule> reportSchedules) { |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
| import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | for (ReportSchedule reportSchedule : reportSchedules) {
if (rule.getReportSchedules().contains(reportSchedule.getId())) {
return reportSchedule;
}
}
return null;
}
@Override
public void doRun() {
Calendar cal = Calendar.getInstance();
List<ReportSchedule> reportSchedules = reportScheduleService.all();
List<ReportSchedule> applicableReportSchedules = new ArrayList<ReportSchedule>();
// get the schedules that apply to the current dateTime
for (ReportSchedule reportSchedule : reportSchedules) {
if (reportSchedule.getNextFireTime() == null) {
setNewFireTime(reportSchedule, cal);
}
if (reportSchedule.getNextFireTime() != null && new Date(reportSchedule.getNextFireTime()).before(cal.getTime())) {
applicableReportSchedules.add(reportSchedule);
setNewFireTime(reportSchedule, cal);
}
}
// select the rules that match the applicable schedules
List<Rule> rulesList = ruleService.all(); | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryItemService.java
// public interface HistoryItemService {
// long count();
//
// HistoryItem create(HistoryItem historyItem);
//
// List<HistoryItem> all();
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, int days);
//
// void removeBefore(Date date);
//
// List<HistoryAggregateItem> getForRuleName(String ruleName, String timespan);
//
// void updateHistoryRuleName(String oldName, String newName);
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportSchedule.java
// public interface ReportSchedule {
//
// public String getId();
//
// public String getName();
//
// public String getExpression();
//
// public String getTimespan();
//
// public boolean isDefaultSchedule();
//
// public Long getNextFireTime();
//
// public List<String> getReportReceivers();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/report/schedule/ReportScheduleService.java
// public interface ReportScheduleService {
// long count();
//
// ReportSchedule update(String name, ReportSchedule schedule);
//
// ReportSchedule create(ReportSchedule schedule);
//
// List<ReportSchedule> all();
//
// int destroy(String scheduleName) throws MongoException, UnsupportedEncodingException;
//
// ReportSchedule fromRequest(AddReportScheduleRequest request);
//
// ReportSchedule fromRequest(UpdateReportScheduleRequest request);
//
// ReportSchedule get(String id);
//
// ReportSchedule updateNextFireTime(String id, Date nextFireTime);
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleService.java
// public interface RuleService {
// long count();
//
// Rule update(String name, Rule rule);
//
// Rule create(Rule rule);
//
// List<Rule> all();
//
// int destroy(String ruleName) throws MongoException, UnsupportedEncodingException;
//
// Rule fromRequest(AddRuleRequest request);
//
// Rule fromRequest(UpdateRuleRequest request);
//
// //Rule setAlertConditionId(Rule rule, String currentAlertId);
//
// String createOrUpdateAlertCondition(Rule rule);
// }
// Path: src/main/java/org/graylog/plugins/aggregates/report/AggregatesReport.java
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.apache.commons.mail.EmailException;
import org.drools.core.time.impl.CronExpression;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryItemService;
import org.graylog.plugins.aggregates.report.schedule.ReportSchedule;
import org.graylog.plugins.aggregates.report.schedule.ReportScheduleService;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleService;
import org.graylog2.plugin.alarms.transports.TransportConfigurationException;
import org.graylog2.plugin.periodical.Periodical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
for (ReportSchedule reportSchedule : reportSchedules) {
if (rule.getReportSchedules().contains(reportSchedule.getId())) {
return reportSchedule;
}
}
return null;
}
@Override
public void doRun() {
Calendar cal = Calendar.getInstance();
List<ReportSchedule> reportSchedules = reportScheduleService.all();
List<ReportSchedule> applicableReportSchedules = new ArrayList<ReportSchedule>();
// get the schedules that apply to the current dateTime
for (ReportSchedule reportSchedule : reportSchedules) {
if (reportSchedule.getNextFireTime() == null) {
setNewFireTime(reportSchedule, cal);
}
if (reportSchedule.getNextFireTime() != null && new Date(reportSchedule.getNextFireTime()).before(cal.getTime())) {
applicableReportSchedules.add(reportSchedule);
setNewFireTime(reportSchedule, cal);
}
}
// select the rules that match the applicable schedules
List<Rule> rulesList = ruleService.all(); | Map<String, Map<Rule, List<HistoryAggregateItem>>> receipientsSeries = new HashMap<String, Map<Rule, List<HistoryAggregateItem>>>(); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/rule/rest/models/responses/RulesList.java | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
| import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.util.List;
import org.graylog.plugins.aggregates.rule.Rule; | package org.graylog.plugins.aggregates.rule.rest.models.responses;
@AutoValue
@JsonAutoDetect
public abstract class RulesList {
@JsonProperty | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/responses/RulesList.java
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.util.List;
import org.graylog.plugins.aggregates.rule.Rule;
package org.graylog.plugins.aggregates.rule.rest.models.responses;
@AutoValue
@JsonAutoDetect
public abstract class RulesList {
@JsonProperty | public abstract List<Rule> getRules(); |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
| import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; | package org.graylog.plugins.aggregates.rule.rest.models.requests;
@AutoValue
@JsonAutoDetect
public abstract class AddRuleRequest {
@JsonProperty("rule")
@NotNull | // Path: src/main/java/org/graylog/plugins/aggregates/rule/Rule.java
// public interface Rule {
//
// public String getQuery();
//
// public String getField();
//
// public long getNumberOfMatches();
//
// public boolean isMatchMoreOrEqual();
//
// public int getInterval();
//
// public String getName();
//
// public boolean isEnabled();
//
// public String getStreamId();
//
// public boolean isInReport();
//
// public List<String> getReportSchedules();
//
// public String getAlertConditionId();
//
// public boolean shouldRepeatNotifications();
//
// public long getBacklog();
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/rule/RuleImpl.java
// @AutoValue
// @JsonAutoDetect
// @JsonIgnoreProperties(ignoreUnknown = true)
// @CollectionName("aggregate_rules")
// public abstract class RuleImpl implements Rule{
//
//
// @JsonProperty("query")
// @Override
// @NotNull
// public abstract String getQuery();
//
// @JsonProperty("field")
// @Override
// @NotNull
// public abstract String getField();
//
// @JsonProperty("numberOfMatches")
// @Override
// @Min(1)
// public abstract long getNumberOfMatches();
//
// @JsonProperty("matchMoreOrEqual")
// @Override
// public abstract boolean isMatchMoreOrEqual();
//
// @JsonProperty("interval")
// @Override
// @Min(1)
// public abstract int getInterval();
//
// @JsonProperty("name")
// @Override
// @NotNull
// public abstract String getName();
//
// @JsonProperty("enabled")
// @Override
// public abstract boolean isEnabled();
//
// @JsonProperty("streamId")
// @Override
// public abstract String getStreamId();
//
// @JsonProperty("inReport")
// @Override
// public abstract boolean isInReport();
//
// @JsonProperty("reportSchedules")
// @Override
// @Nullable
// public abstract List<String> getReportSchedules();
//
// @JsonProperty("alertConditionId")
// @Override
// @Nullable
// public abstract String getAlertConditionId();
//
// @JsonProperty("repeatNotifications")
// @Override
// @Nullable
// public abstract boolean shouldRepeatNotifications();
//
// @JsonProperty("backlog")
// @Override
// @Nullable
// @Min(0)
// public abstract long getBacklog();
//
// @JsonCreator
// public static RuleImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("query") String query,
// @JsonProperty("field") String field,
// @JsonProperty("numberOfMatches") long numberOfMatches,
// @JsonProperty("matchMoreOrEqual") boolean matchMoreOrEqual,
// @JsonProperty("interval") int interval,
// @JsonProperty("name") String name,
// @JsonProperty("enabled") boolean enabled,
// @JsonProperty("streamId") String streamId,
// @JsonProperty("inReport") boolean inReport,
// @JsonProperty("reportSchedules") List<String> reportSchedules,
// @JsonProperty("alertConditionId") String alertConditionId,
// @JsonProperty("repeatNotifications") boolean repeatNotifications,
// @JsonProperty("backlog") long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
// }
//
// public static RuleImpl create(
// String query,
// String field,
// long numberOfMatches,
// boolean matchMoreOrEqual,
// int interval,
// String name,
// boolean enabled,
// String streamId,
// boolean inReport,
// List<String> reportSchedules,
// String alertConditionId,
// boolean repeatNotifications,
// long backlog) {
// return new AutoValue_RuleImpl(query, field, numberOfMatches, matchMoreOrEqual, interval, name, enabled, streamId, inReport, reportSchedules, alertConditionId, repeatNotifications, backlog);
//
// }
// }
// Path: src/main/java/org/graylog/plugins/aggregates/rule/rest/models/requests/AddRuleRequest.java
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.graylog.plugins.aggregates.rule.Rule;
import org.graylog.plugins.aggregates.rule.RuleImpl;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
package org.graylog.plugins.aggregates.rule.rest.models.requests;
@AutoValue
@JsonAutoDetect
public abstract class AddRuleRequest {
@JsonProperty("rule")
@NotNull | public abstract RuleImpl getRule(); |
cvtienhoven/graylog-plugin-aggregates | src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java
// @AutoValue
// @JsonAutoDetect
// public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{
//
// @JsonProperty("moment")
// @Override
// public abstract String getMoment();
//
// @JsonProperty("numberOfHits")
// @Override
// public abstract long getNumberOfHits();
//
//
// @JsonCreator
// public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("moment") String moment,
// @JsonProperty("numberOfHits") long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
// }
//
// public static HistoryAggregateItemImpl create(
// String moment,
// long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
//
// }
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner; | package org.graylog.plugins.aggregates.report;
@RunWith(MockitoJUnitRunner.class)
public class ChartFactoryTest {
@Test
public void testGenerateTimeSeriesChart() throws ParseException{
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH"); | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java
// @AutoValue
// @JsonAutoDetect
// public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{
//
// @JsonProperty("moment")
// @Override
// public abstract String getMoment();
//
// @JsonProperty("numberOfHits")
// @Override
// public abstract long getNumberOfHits();
//
//
// @JsonCreator
// public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("moment") String moment,
// @JsonProperty("numberOfHits") long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
// }
//
// public static HistoryAggregateItemImpl create(
// String moment,
// long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
//
// }
// }
// Path: src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
package org.graylog.plugins.aggregates.report;
@RunWith(MockitoJUnitRunner.class)
public class ChartFactoryTest {
@Test
public void testGenerateTimeSeriesChart() throws ParseException{
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH"); | List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>(); |
cvtienhoven/graylog-plugin-aggregates | src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java
// @AutoValue
// @JsonAutoDetect
// public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{
//
// @JsonProperty("moment")
// @Override
// public abstract String getMoment();
//
// @JsonProperty("numberOfHits")
// @Override
// public abstract long getNumberOfHits();
//
//
// @JsonCreator
// public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("moment") String moment,
// @JsonProperty("numberOfHits") long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
// }
//
// public static HistoryAggregateItemImpl create(
// String moment,
// long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
//
// }
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner; | package org.graylog.plugins.aggregates.report;
@RunWith(MockitoJUnitRunner.class)
public class ChartFactoryTest {
@Test
public void testGenerateTimeSeriesChart() throws ParseException{
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH");
List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>();
for (int i=0; i<70; i++){
cal.add(Calendar.DATE, -1);
String day = format.format(cal.getTime()); | // Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItem.java
// public interface HistoryAggregateItem {
// public String getMoment();
//
// public long getNumberOfHits();
//
// }
//
// Path: src/main/java/org/graylog/plugins/aggregates/history/HistoryAggregateItemImpl.java
// @AutoValue
// @JsonAutoDetect
// public abstract class HistoryAggregateItemImpl implements HistoryAggregateItem{
//
// @JsonProperty("moment")
// @Override
// public abstract String getMoment();
//
// @JsonProperty("numberOfHits")
// @Override
// public abstract long getNumberOfHits();
//
//
// @JsonCreator
// public static HistoryAggregateItemImpl create(@JsonProperty("_id") String objectId,
// @JsonProperty("moment") String moment,
// @JsonProperty("numberOfHits") long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
// }
//
// public static HistoryAggregateItemImpl create(
// String moment,
// long numberOfHits) {
// return new AutoValue_HistoryAggregateItemImpl(moment, numberOfHits);
//
// }
// }
// Path: src/test/java/org/graylog/plugins/aggregates/report/ChartFactoryTest.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.graylog.plugins.aggregates.history.HistoryAggregateItem;
import org.graylog.plugins.aggregates.history.HistoryAggregateItemImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
package org.graylog.plugins.aggregates.report;
@RunWith(MockitoJUnitRunner.class)
public class ChartFactoryTest {
@Test
public void testGenerateTimeSeriesChart() throws ParseException{
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd'T'HH");
List<HistoryAggregateItem> history = new ArrayList<HistoryAggregateItem>();
for (int i=0; i<70; i++){
cal.add(Calendar.DATE, -1);
String day = format.format(cal.getTime()); | history.add(HistoryAggregateItemImpl.create(day, 54+i)); |
TeamCohen/SEAL | src/com/rcwang/seal/util/StringFactory.java | // Path: src/com/rcwang/seal/expand/Wrapper.java
// public static class EntityLiteral implements Comparable<EntityLiteral> {
// public String arg1;
// public String arg2;
// public EntityLiteral(String arg1) { this.arg1=StringFactory.get(arg1); }
// public EntityLiteral(String arg1, String arg2) { this(arg1); this.arg2 = StringFactory.get(arg2); }
// public EntityLiteral(String ... names) {
// if (names.length > 0) this.arg1=StringFactory.get(names[0]);
// if (names.length > 1) this.arg2 = StringFactory.get(names[1]);
// if (names.length > 2) log.warn("Attempt to create entity literal with more than two strings:" + names);
// }
// public String toString() {
// StringBuilder sb = new StringBuilder(arg1);
// if (arg2!= null) sb.append(Entity.RELATION_SEPARATOR).append(arg2);
// return sb.toString();
// }
// final public boolean equals(Object o) {
// if (! (o instanceof EntityLiteral)) return false;
// EntityLiteral e = (EntityLiteral) o;
// return arg1 == e.arg1 && arg2 == e.arg2;
// }
// final public int hashCode() {
// int a1 = arg1.hashCode();
// if (arg2!=null) return a1 ^ arg2.hashCode();
// return a1;
// }
// final public int compareTo(EntityLiteral e) {
// return this.toString().compareTo(e.toString());
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.rcwang.seal.expand.Wrapper.EntityLiteral;
| if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final SID other = (SID) obj;
if (!Arrays.equals(array, other.array))
return false;
return true;
}
@Override
public int hashCode() {
return 31 + Arrays.hashCode(array);
}
public Iterator<String> iterator() {
return Arrays.asList(array).iterator();
}
public int length() {
int length = 0;
for (String s : this)
length += s.length();
return length;
}
@Override
public String toString() {
return StringFactory.toName(this);
}
| // Path: src/com/rcwang/seal/expand/Wrapper.java
// public static class EntityLiteral implements Comparable<EntityLiteral> {
// public String arg1;
// public String arg2;
// public EntityLiteral(String arg1) { this.arg1=StringFactory.get(arg1); }
// public EntityLiteral(String arg1, String arg2) { this(arg1); this.arg2 = StringFactory.get(arg2); }
// public EntityLiteral(String ... names) {
// if (names.length > 0) this.arg1=StringFactory.get(names[0]);
// if (names.length > 1) this.arg2 = StringFactory.get(names[1]);
// if (names.length > 2) log.warn("Attempt to create entity literal with more than two strings:" + names);
// }
// public String toString() {
// StringBuilder sb = new StringBuilder(arg1);
// if (arg2!= null) sb.append(Entity.RELATION_SEPARATOR).append(arg2);
// return sb.toString();
// }
// final public boolean equals(Object o) {
// if (! (o instanceof EntityLiteral)) return false;
// EntityLiteral e = (EntityLiteral) o;
// return arg1 == e.arg1 && arg2 == e.arg2;
// }
// final public int hashCode() {
// int a1 = arg1.hashCode();
// if (arg2!=null) return a1 ^ arg2.hashCode();
// return a1;
// }
// final public int compareTo(EntityLiteral e) {
// return this.toString().compareTo(e.toString());
// }
// }
// Path: src/com/rcwang/seal/util/StringFactory.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.rcwang.seal.expand.Wrapper.EntityLiteral;
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final SID other = (SID) obj;
if (!Arrays.equals(array, other.array))
return false;
return true;
}
@Override
public int hashCode() {
return 31 + Arrays.hashCode(array);
}
public Iterator<String> iterator() {
return Arrays.asList(array).iterator();
}
public int length() {
int length = 0;
for (String s : this)
length += s.length();
return length;
}
@Override
public String toString() {
return StringFactory.toName(this);
}
| public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
|
TeamCohen/SEAL | src/com/rcwang/seal/expand/PairedComboMaker2.java | // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.rank.Ranker.Feature;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class PairedComboMaker2 {
// public static long DEFAULT_RANDOM_SEED = 0;
public static Logger log = Logger.getLogger(PairedComboMaker2.class);
private RankedComboMaker rankedComboMaker;
private List<EntityList> list1;
private List<EntityList> list2;
private Set<EntityList> historicalEntities;
// private long randomSeed;
private boolean hasList1 = false;
private boolean hasList2 = false;
public static void main(String args[]) {
PairedComboMaker2 ss = new PairedComboMaker2();
// ss.setRandomSeed(System.currentTimeMillis());
| // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
// Path: src/com/rcwang/seal/expand/PairedComboMaker2.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.rank.Ranker.Feature;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class PairedComboMaker2 {
// public static long DEFAULT_RANDOM_SEED = 0;
public static Logger log = Logger.getLogger(PairedComboMaker2.class);
private RankedComboMaker rankedComboMaker;
private List<EntityList> list1;
private List<EntityList> list2;
private Set<EntityList> historicalEntities;
// private long randomSeed;
private boolean hasList1 = false;
private boolean hasList2 = false;
public static void main(String args[]) {
PairedComboMaker2 ss = new PairedComboMaker2();
// ss.setRandomSeed(System.currentTimeMillis());
| Feature feature = Feature.GWW;
|
TeamCohen/SEAL | src/com/rcwang/seal/expand/Pinniped.java | // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
| import com.rcwang.seal.rank.Ranker.Feature; | package com.rcwang.seal.expand;
/**
* Pinniped defines the shared methods of Seal-like classes, including Seal and OfflineSeal.
* Putting these methods in a common interface allows us to use better logic in code
* which can operate with either class.
*
* @author krivard
*
*/
public abstract class Pinniped extends SetExpander {
public abstract void setEngine(int useEngine); | // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
// Path: src/com/rcwang/seal/expand/Pinniped.java
import com.rcwang.seal.rank.Ranker.Feature;
package com.rcwang.seal.expand;
/**
* Pinniped defines the shared methods of Seal-like classes, including Seal and OfflineSeal.
* Putting these methods in a common interface allows us to use better logic in code
* which can operate with either class.
*
* @author krivard
*
*/
public abstract class Pinniped extends SetExpander {
public abstract void setEngine(int useEngine); | public abstract void setFeature(Feature feature); |
TeamCohen/SEAL | src/com/rcwang/seal/util/Originator.java | // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
| import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
| package com.rcwang.seal.util;
public class Originator {
/**
* Stores distribution and sources of instances
* @author rcwang
*
*/
public static class DistKeys {
public static final double DEFAULT_WEIGHT = 1;
public static final double DASHED_STR_WEIGHT = 0.5; // 0.5
public static final double IDENTICAL_STR_WEIGHT = 0.1; // 0.1
public static final int MAX_DIST_SIZE = 10;
private Set<Integer> keys;
private Distribution dist;
| // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
// Path: src/com/rcwang/seal/util/Originator.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
package com.rcwang.seal.util;
public class Originator {
/**
* Stores distribution and sources of instances
* @author rcwang
*
*/
public static class DistKeys {
public static final double DEFAULT_WEIGHT = 1;
public static final double DASHED_STR_WEIGHT = 0.5; // 0.5
public static final double IDENTICAL_STR_WEIGHT = 0.1; // 0.1
public static final int MAX_DIST_SIZE = 10;
private Set<Integer> keys;
private Distribution dist;
| private SID canonical;
|
TeamCohen/SEAL | src/com/rcwang/seal/util/MatrixUtil.java | // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
| import java.util.HashSet;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class MatrixUtil {
public static Logger log = Logger.getLogger(MatrixUtil.class);
public static SparseMatrix dotProduct(SparseMatrix sm1, SparseMatrix sm2) {
SparseMatrix sm = new SparseMatrix();
for (SparseVector col2 : sm2.getColumns())
sm.addColumn(dotProduct(sm1, col2));
return sm;
}
public static SparseVector dotProduct(SparseMatrix sm, SparseVector sv1) {
SparseVector sv = new SparseVector(sv1.id);
for (SparseVector row : sm.getRows())
sv.put(row.id, dotProduct(row, sv1));
return sv;
}
public static double dotProduct(SparseVector sv1, SparseVector sv2) {
if (sv2.size() < sv1.size()) {
SparseVector sv = sv2;
sv2 = sv1; sv1 = sv;
}
double sum = 0;
| // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
// Path: src/com/rcwang/seal/util/MatrixUtil.java
import java.util.HashSet;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class MatrixUtil {
public static Logger log = Logger.getLogger(MatrixUtil.class);
public static SparseMatrix dotProduct(SparseMatrix sm1, SparseMatrix sm2) {
SparseMatrix sm = new SparseMatrix();
for (SparseVector col2 : sm2.getColumns())
sm.addColumn(dotProduct(sm1, col2));
return sm;
}
public static SparseVector dotProduct(SparseMatrix sm, SparseVector sv1) {
SparseVector sv = new SparseVector(sv1.id);
for (SparseVector row : sm.getRows())
sv.put(row.id, dotProduct(row, sv1));
return sv;
}
public static double dotProduct(SparseVector sv1, SparseVector sv2) {
if (sv2.size() < sv1.size()) {
SparseVector sv = sv2;
sv2 = sv1; sv1 = sv;
}
double sum = 0;
| for (Entry<SID, Cell> entry : sv1) {
|
TeamCohen/SEAL | src/com/rcwang/seal/expand/PairedComboMaker.java | // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.rank.Ranker.Feature;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class PairedComboMaker {
public static long DEFAULT_RANDOM_SEED = 0;
public static Logger log = Logger.getLogger(PairedComboMaker.class);
private RankedComboMaker rankedComboMaker;
private List<EntityList> possComboList;
private List<EntityList> trueComboList;
private Set<EntityList> historicalSeeds;
private boolean hasTrueSeeds = false;
private boolean hasPossSeeds = false;
private long randomSeed;
public static void main(String args[]) {
PairedComboMaker ss = new PairedComboMaker();
ss.setRandomSeed(System.currentTimeMillis());
EntityList trueSeeds = new EntityList();
trueSeeds.add("a");
trueSeeds.add("b");
trueSeeds.add("c");
| // Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
// Path: src/com/rcwang/seal/expand/PairedComboMaker.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.log4j.Logger;
import com.rcwang.seal.rank.Ranker.Feature;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class PairedComboMaker {
public static long DEFAULT_RANDOM_SEED = 0;
public static Logger log = Logger.getLogger(PairedComboMaker.class);
private RankedComboMaker rankedComboMaker;
private List<EntityList> possComboList;
private List<EntityList> trueComboList;
private Set<EntityList> historicalSeeds;
private boolean hasTrueSeeds = false;
private boolean hasPossSeeds = false;
private long randomSeed;
public static void main(String args[]) {
PairedComboMaker ss = new PairedComboMaker();
ss.setRandomSeed(System.currentTimeMillis());
EntityList trueSeeds = new EntityList();
trueSeeds.add("a");
trueSeeds.add("b");
trueSeeds.add("c");
| Feature feature = Feature.WLW;
|
TeamCohen/SEAL | src/com/rcwang/seal/util/SparseMatrix.java | // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class SparseMatrix {
public static Logger log = Logger.getLogger(SparseMatrix.class);
| // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
// Path: src/com/rcwang/seal/util/SparseMatrix.java
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class SparseMatrix {
public static Logger log = Logger.getLogger(SparseMatrix.class);
| private Map<SID, SparseVector> rowMap;
|
TeamCohen/SEAL | src/com/rcwang/seal/util/VotedPerceptron.java | // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class VotedPerceptron {
public static class WeightedPerceptron {
public double weight = 0;
public double[] perceptron;
public WeightedPerceptron(int size) { perceptron = new double[size]; }
public WeightedPerceptron(double[] perceptron) { this.perceptron = perceptron; }
}
public static int MIN_PERCEPTRON_WEIGHT = 1;
public static boolean FAIL_EARLY = false;
public static Logger log = Logger.getLogger(VotedPerceptron.class);
private List<WeightedPerceptron> weightedPerceptrons;
| // Path: src/com/rcwang/seal/util/StringFactory.java
// public static class SID implements Iterable<String> {
//
// String[] array;
//
// public SID(List<String> strs) {
// array = strs.toArray(new String[strs.size()]);
// }
//
// public SID(SID id) {
// this(id.array);
// }
//
// public SID(String[] array) {
// this.array = array.clone();
// }
//
// public void append(SID sid) {
// append(sid.array);
// }
//
// public void append(String s) {
// append(StringFactory.toID(s));
// }
//
// public void append(String[] array) {
// String[] array2 = new String[this.array.length+array.length];
// System.arraycopy(this.array, 0, array2, 0, this.array.length);
// System.arraycopy(array, 0, array2, this.array.length, array.length);
// this.array = array2;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// final SID other = (SID) obj;
// if (!Arrays.equals(array, other.array))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// return 31 + Arrays.hashCode(array);
// }
//
// public Iterator<String> iterator() {
// return Arrays.asList(array).iterator();
// }
//
// public int length() {
// int length = 0;
// for (String s : this)
// length += s.length();
// return length;
// }
//
// @Override
// public String toString() {
// return StringFactory.toName(this);
// }
//
// public EntityLiteral toLiteral() { return new EntityLiteral(StringFactory.toName(this)); }
//
// public SID toLower() {
// return StringFactory.toID(new EntityLiteral(StringFactory.toName(this).toLowerCase()));
// }
// }
// Path: src/com/rcwang/seal/util/VotedPerceptron.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.StringFactory.SID;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class VotedPerceptron {
public static class WeightedPerceptron {
public double weight = 0;
public double[] perceptron;
public WeightedPerceptron(int size) { perceptron = new double[size]; }
public WeightedPerceptron(double[] perceptron) { this.perceptron = perceptron; }
}
public static int MIN_PERCEPTRON_WEIGHT = 1;
public static boolean FAIL_EARLY = false;
public static Logger log = Logger.getLogger(VotedPerceptron.class);
private List<WeightedPerceptron> weightedPerceptrons;
| private Map<SID, Double> trueLabels;
|
TeamCohen/SEAL | src/com/rcwang/seal/expand/RankedComboMaker.java | // Path: src/com/rcwang/seal/util/ComboMaker.java
// public class ComboMaker<T> {
//
// public static void main(String args[]) {
// Set<String> set = new HashSet<String>();
// set.add("a");
// set.add("b");
// set.add("c");
// set.add("d");
//
// ComboMaker<String> comboMaker = new ComboMaker<String>();
// List<List<String>> comboLists = comboMaker.make(set, 2);
// for (int i = 0; i < comboLists.size(); i++) {
// List<String> comboList = comboLists.get(i);
// System.out.print((i+1) + ". ");
// for (String s : comboList)
// System.out.print(s + ", ");
// System.out.println();
// }
// }
//
// /**
// * Generates all possible combinations of size n from the input entities.
// * The generated list of combinations are in random order.
// * @param entities the input entities
// * @param n the size n
// * @return a list of entity combinations
// */
// public List<List<T>> make(Collection<T> entities, int n) {
// return make(new ArrayList<T>(entities), n);
// }
//
// public List<List<T>> make(List<T> entities, int n) {
// if (n > entities.size()) return null;
// List<List<T>> resultList = new ArrayList<List<T>>();
// int[] arr = null;
//
// while (true) {
// if (arr != null && arr[0] == entities.size()-arr.length)
// break;
// if (arr == null) {
// arr = new int[n];
// for (int i = 0; i < n; i++)
// arr[i] = i;
// } else if (arr[arr.length-1] == entities.size()-1) {
// for (int i = 0; i < arr.length;i++) {
// if (arr[i] == entities.size()-arr.length+i) {
// arr[i-1]++;
// for (int j = i; j < arr.length; j++)
// arr[j] = arr[j-1] + 1;
// break;
// }
// }
// } else arr[arr.length-1]++;
//
// List<T> list = new ArrayList<T>();
// for (int i = 0; i < arr.length ; i++)
// list.add(entities.get(arr[i]));
// resultList.add(list);
// }
// return resultList;
// }
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.ComboMaker;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class RankedComboMaker {
public static Logger log = Logger.getLogger(RankedComboMaker.class);
public static final int DEFAULT_MAX_COMBINATIONS = 128;
| // Path: src/com/rcwang/seal/util/ComboMaker.java
// public class ComboMaker<T> {
//
// public static void main(String args[]) {
// Set<String> set = new HashSet<String>();
// set.add("a");
// set.add("b");
// set.add("c");
// set.add("d");
//
// ComboMaker<String> comboMaker = new ComboMaker<String>();
// List<List<String>> comboLists = comboMaker.make(set, 2);
// for (int i = 0; i < comboLists.size(); i++) {
// List<String> comboList = comboLists.get(i);
// System.out.print((i+1) + ". ");
// for (String s : comboList)
// System.out.print(s + ", ");
// System.out.println();
// }
// }
//
// /**
// * Generates all possible combinations of size n from the input entities.
// * The generated list of combinations are in random order.
// * @param entities the input entities
// * @param n the size n
// * @return a list of entity combinations
// */
// public List<List<T>> make(Collection<T> entities, int n) {
// return make(new ArrayList<T>(entities), n);
// }
//
// public List<List<T>> make(List<T> entities, int n) {
// if (n > entities.size()) return null;
// List<List<T>> resultList = new ArrayList<List<T>>();
// int[] arr = null;
//
// while (true) {
// if (arr != null && arr[0] == entities.size()-arr.length)
// break;
// if (arr == null) {
// arr = new int[n];
// for (int i = 0; i < n; i++)
// arr[i] = i;
// } else if (arr[arr.length-1] == entities.size()-1) {
// for (int i = 0; i < arr.length;i++) {
// if (arr[i] == entities.size()-arr.length+i) {
// arr[i-1]++;
// for (int j = i; j < arr.length; j++)
// arr[j] = arr[j-1] + 1;
// break;
// }
// }
// } else arr[arr.length-1]++;
//
// List<T> list = new ArrayList<T>();
// for (int i = 0; i < arr.length ; i++)
// list.add(entities.get(arr[i]));
// resultList.add(list);
// }
// return resultList;
// }
// }
// Path: src/com/rcwang/seal/expand/RankedComboMaker.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import com.rcwang.seal.util.ComboMaker;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class RankedComboMaker {
public static Logger log = Logger.getLogger(RankedComboMaker.class);
public static final int DEFAULT_MAX_COMBINATIONS = 128;
| private ComboMaker<Entity> comboMaker;
|
TeamCohen/SEAL | src/com/rcwang/seal/util/GlobalVar.java | // Path: src/com/rcwang/seal/expand/SeedSelector.java
// public static enum SeedingPolicy {
// FSS_SUPERVISED,
// FSS_SEMI_SUPERVISED,
// FSS_UNSUPERVISED,
// FSS_UNSUPERVISED_V2,
// ISS_SUPERVISED,
// ISS_UNSUPERVISED,
// CIS_SUPERVISED,
// };
//
// Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
| import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.SeedSelector.SeedingPolicy;
import com.rcwang.seal.rank.Ranker.Feature;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class GlobalVar {
public static final String PROP_ENV_NAME = "SEAL_PROP";
public static final String PROP_FILE_PATH = "seal.properties";
public static final String COMMA_REGEXP = "\\s*,\\s*";
public static final String CLUEWEB_TMP_DIR="clueweb.tmpdir";
public static final String CLUEWEB_HEADER_TIMEOUT_MS = "clueweb.headerTimeout";
public static final String CLUEWEB_TIMEOUT_NUMTRIALS = "clueweb.numtrials";
public static final String CLUEWEB_TIMEOUT_REPORTING_MS = "clueweb.timeoutReporting";
public static Logger log = Logger.getLogger(GlobalVar.class);
private static GlobalVar gv = null;
private static Properties prop = null;
// Basic parameters
private static String langID;
| // Path: src/com/rcwang/seal/expand/SeedSelector.java
// public static enum SeedingPolicy {
// FSS_SUPERVISED,
// FSS_SEMI_SUPERVISED,
// FSS_UNSUPERVISED,
// FSS_UNSUPERVISED_V2,
// ISS_SUPERVISED,
// ISS_UNSUPERVISED,
// CIS_SUPERVISED,
// };
//
// Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
// Path: src/com/rcwang/seal/util/GlobalVar.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.SeedSelector.SeedingPolicy;
import com.rcwang.seal.rank.Ranker.Feature;
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.util;
public class GlobalVar {
public static final String PROP_ENV_NAME = "SEAL_PROP";
public static final String PROP_FILE_PATH = "seal.properties";
public static final String COMMA_REGEXP = "\\s*,\\s*";
public static final String CLUEWEB_TMP_DIR="clueweb.tmpdir";
public static final String CLUEWEB_HEADER_TIMEOUT_MS = "clueweb.headerTimeout";
public static final String CLUEWEB_TIMEOUT_NUMTRIALS = "clueweb.numtrials";
public static final String CLUEWEB_TIMEOUT_REPORTING_MS = "clueweb.timeoutReporting";
public static Logger log = Logger.getLogger(GlobalVar.class);
private static GlobalVar gv = null;
private static Properties prop = null;
// Basic parameters
private static String langID;
| private static Feature feature;
|
TeamCohen/SEAL | src/com/rcwang/seal/util/GlobalVar.java | // Path: src/com/rcwang/seal/expand/SeedSelector.java
// public static enum SeedingPolicy {
// FSS_SUPERVISED,
// FSS_SEMI_SUPERVISED,
// FSS_UNSUPERVISED,
// FSS_UNSUPERVISED_V2,
// ISS_SUPERVISED,
// ISS_UNSUPERVISED,
// CIS_SUPERVISED,
// };
//
// Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
| import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.SeedSelector.SeedingPolicy;
import com.rcwang.seal.rank.Ranker.Feature;
| private static String yahooBossKey;
private static long googleHitGapInMS;
private static File resultDir;
private static int minSeedsBracketed;
private static String bingAPIKey;
private static String googleCustomAPIKey;
private static String setExpander;
// Fetching parameters
private static int numResults;
private static int numSubSeeds;
// OfflineSeal and WrapperSavingAsia parameters
private static boolean isFetchFromWeb; //wwc - keeps WebManager from getting stuff from web
private static File localDir; //wwc - files that will be searched by the OfflineSearcher
private static File indexDir; //wwc - index of files in localDir
private static File localRoot; //wwc - set if files are indexed relative to some root directory
private static File savedWrapperDir; //wwc - stores wrappers generated by OfflineSeal or WrapperSavingAsia
private static int wrapperSaving; //wwc - policy on wrapper saving, 2 means save to savedWrapperDir
// Optimization parameters
private static int wrapperLevel;
private static int minContextLength;
private static int maxDocSizeInKB;
private static int timeOutInMS;
private static File cacheDir;
private static File urlBlackList;
private static File stopwordsList;
// Iterative expansion parameters
| // Path: src/com/rcwang/seal/expand/SeedSelector.java
// public static enum SeedingPolicy {
// FSS_SUPERVISED,
// FSS_SEMI_SUPERVISED,
// FSS_UNSUPERVISED,
// FSS_UNSUPERVISED_V2,
// ISS_SUPERVISED,
// ISS_UNSUPERVISED,
// CIS_SUPERVISED,
// };
//
// Path: src/com/rcwang/seal/rank/Ranker.java
// public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}
// Path: src/com/rcwang/seal/util/GlobalVar.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.SeedSelector.SeedingPolicy;
import com.rcwang.seal.rank.Ranker.Feature;
private static String yahooBossKey;
private static long googleHitGapInMS;
private static File resultDir;
private static int minSeedsBracketed;
private static String bingAPIKey;
private static String googleCustomAPIKey;
private static String setExpander;
// Fetching parameters
private static int numResults;
private static int numSubSeeds;
// OfflineSeal and WrapperSavingAsia parameters
private static boolean isFetchFromWeb; //wwc - keeps WebManager from getting stuff from web
private static File localDir; //wwc - files that will be searched by the OfflineSearcher
private static File indexDir; //wwc - index of files in localDir
private static File localRoot; //wwc - set if files are indexed relative to some root directory
private static File savedWrapperDir; //wwc - stores wrappers generated by OfflineSeal or WrapperSavingAsia
private static int wrapperSaving; //wwc - policy on wrapper saving, 2 means save to savedWrapperDir
// Optimization parameters
private static int wrapperLevel;
private static int minContextLength;
private static int maxDocSizeInKB;
private static int timeOutInMS;
private static File cacheDir;
private static File urlBlackList;
private static File stopwordsList;
// Iterative expansion parameters
| private static SeedingPolicy policy;
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/view/activity/ActivityUpdateView.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/UpdateView.java
// public interface UpdateView {
//
// void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gPayload);
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/Version.java
// public class Version implements Comparable<Version>, Parcelable {
//
// private int [] version;
//
// public Version(String gVersionString) {
//
// if(TextUtils.isEmpty(gVersionString) || !Character.isDigit(gVersionString.charAt(0))) {
// throw new RuntimeException("Invalid version format \"" + gVersionString + "\". Accepted are only numbers with dots followed by anything. Examples of valid version strings are '0.1.2', '0.1.2-beta' or '0.1.2.3'.");
// }
//
// List<Integer> versionParts = new LinkedList<Integer>();
//
// String[] versionStringParts = gVersionString.split("\\.");
//
// for(String part : versionStringParts) {
// if(TextUtils.isEmpty(part)) {
// break;
// }
//
// if(isDigit(part)) {
// versionParts.add(Integer.valueOf(part));
// } else {
// int lastNumberIndex = -1;
// for(int i = 0; i < part.length(); i++) {
// if(Character.isDigit(part.charAt(i))) {
// lastNumberIndex = i;
// } else {
// break;
// }
// }
// if(lastNumberIndex >= 0) {
// versionParts.add(Integer.valueOf(part.substring(0, lastNumberIndex + 1)));
// }
// break;
// }
// }
//
// // convert list of Integers to array of priminive ints
// int [] versionPartsArray = new int [versionParts.size()];
// for(int i = 0; i < versionParts.size(); i++) {
// versionPartsArray[i] = versionParts.get(i);
// }
//
// init(versionPartsArray);
// }
//
// public Version(int [] gVersionParts) {
// init(gVersionParts.clone());
// }
//
// private void init(int[] gVersionParts) {
// for(int part : gVersionParts) {
// if(part < 0) {
// throw new RuntimeException("Only positive numbers are allowed, you provided " + part + " as one part of version.");
// }
// }
//
// version = gVersionParts;
// }
//
// private static boolean isDigit(CharSequence str) {
// final int len = str.length();
//
// if(len > 0) {
// char firstChar = str.charAt(0);
// if(!Character.isDigit(firstChar) && firstChar != '-') {
// return false;
// }
// }
//
// for (int i = 1; i < len; i++) {
// if (!Character.isDigit(str.charAt(i))) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public boolean equals(Object o) {
// if(!(o instanceof Version)) {
// return false;
// }
//
// Version comparedVersion = (Version)o;
//
// if(version.length != comparedVersion.version.length) {
// return false;
// }
//
// for (int i = 0; i < version.length; i++) {
// if(version[i] != comparedVersion.version[i]) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(version);
// }
//
// @Override
// public int compareTo(Version another) {
// int minLength = Math.min(version.length, another.version.length);
//
// for(int i = 0; i < minLength; i++) {
// int version1 = version[i];
// int version2 = another.version[i];
// if(version1 != version2) {
// return version1 - version2;
// }
// }
//
// return 0;
// }
//
// @Override
// public String toString() {
// String versionName = "";
// for (int i = 0; i < version.length; i++) {
// versionName += Integer.toString(version[i]);
// if (i + 1 < version.length) {
// versionName += ".";
// }
// }
// return versionName;
// }
//
// public int [] getVersionParts() {
// return version.clone();
// }
//
// protected Version(Parcel in) {
// in.readIntArray(version);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeIntArray(version);
// }
//
// public static final Parcelable.Creator<Version> CREATOR = new Parcelable.Creator<Version>() {
// @Override
// public Version createFromParcel(Parcel in) {
// return new Version(in);
// }
//
// @Override
// public Version[] newArray(int size) {
// return new Version[size];
// }
// };
// }
| import android.app.Activity;
import android.content.Intent;
import net.skoumal.forceupdate.UpdateView;
import net.skoumal.forceupdate.Version;
| package net.skoumal.forceupdate.view.activity;
public class ActivityUpdateView implements UpdateView {
public static final String CURRENT_VERSION_EXTRA = "current_version";
public static final String REQUIRED_VERSION_EXTRA = "required_version";
public static final String PAYLOAD_EXTRA = "payload";
private Class<?> activityClass;
public ActivityUpdateView(Class<?> gActivityClass) {
activityClass = gActivityClass;
}
@Override
| // Path: force-update/src/main/java/net/skoumal/forceupdate/UpdateView.java
// public interface UpdateView {
//
// void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gPayload);
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/Version.java
// public class Version implements Comparable<Version>, Parcelable {
//
// private int [] version;
//
// public Version(String gVersionString) {
//
// if(TextUtils.isEmpty(gVersionString) || !Character.isDigit(gVersionString.charAt(0))) {
// throw new RuntimeException("Invalid version format \"" + gVersionString + "\". Accepted are only numbers with dots followed by anything. Examples of valid version strings are '0.1.2', '0.1.2-beta' or '0.1.2.3'.");
// }
//
// List<Integer> versionParts = new LinkedList<Integer>();
//
// String[] versionStringParts = gVersionString.split("\\.");
//
// for(String part : versionStringParts) {
// if(TextUtils.isEmpty(part)) {
// break;
// }
//
// if(isDigit(part)) {
// versionParts.add(Integer.valueOf(part));
// } else {
// int lastNumberIndex = -1;
// for(int i = 0; i < part.length(); i++) {
// if(Character.isDigit(part.charAt(i))) {
// lastNumberIndex = i;
// } else {
// break;
// }
// }
// if(lastNumberIndex >= 0) {
// versionParts.add(Integer.valueOf(part.substring(0, lastNumberIndex + 1)));
// }
// break;
// }
// }
//
// // convert list of Integers to array of priminive ints
// int [] versionPartsArray = new int [versionParts.size()];
// for(int i = 0; i < versionParts.size(); i++) {
// versionPartsArray[i] = versionParts.get(i);
// }
//
// init(versionPartsArray);
// }
//
// public Version(int [] gVersionParts) {
// init(gVersionParts.clone());
// }
//
// private void init(int[] gVersionParts) {
// for(int part : gVersionParts) {
// if(part < 0) {
// throw new RuntimeException("Only positive numbers are allowed, you provided " + part + " as one part of version.");
// }
// }
//
// version = gVersionParts;
// }
//
// private static boolean isDigit(CharSequence str) {
// final int len = str.length();
//
// if(len > 0) {
// char firstChar = str.charAt(0);
// if(!Character.isDigit(firstChar) && firstChar != '-') {
// return false;
// }
// }
//
// for (int i = 1; i < len; i++) {
// if (!Character.isDigit(str.charAt(i))) {
// return false;
// }
// }
// return true;
// }
//
// @Override
// public boolean equals(Object o) {
// if(!(o instanceof Version)) {
// return false;
// }
//
// Version comparedVersion = (Version)o;
//
// if(version.length != comparedVersion.version.length) {
// return false;
// }
//
// for (int i = 0; i < version.length; i++) {
// if(version[i] != comparedVersion.version[i]) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(version);
// }
//
// @Override
// public int compareTo(Version another) {
// int minLength = Math.min(version.length, another.version.length);
//
// for(int i = 0; i < minLength; i++) {
// int version1 = version[i];
// int version2 = another.version[i];
// if(version1 != version2) {
// return version1 - version2;
// }
// }
//
// return 0;
// }
//
// @Override
// public String toString() {
// String versionName = "";
// for (int i = 0; i < version.length; i++) {
// versionName += Integer.toString(version[i]);
// if (i + 1 < version.length) {
// versionName += ".";
// }
// }
// return versionName;
// }
//
// public int [] getVersionParts() {
// return version.clone();
// }
//
// protected Version(Parcel in) {
// in.readIntArray(version);
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeIntArray(version);
// }
//
// public static final Parcelable.Creator<Version> CREATOR = new Parcelable.Creator<Version>() {
// @Override
// public Version createFromParcel(Parcel in) {
// return new Version(in);
// }
//
// @Override
// public Version[] newArray(int size) {
// return new Version[size];
// }
// };
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/activity/ActivityUpdateView.java
import android.app.Activity;
import android.content.Intent;
import net.skoumal.forceupdate.UpdateView;
import net.skoumal.forceupdate.Version;
package net.skoumal.forceupdate.view.activity;
public class ActivityUpdateView implements UpdateView {
public static final String CURRENT_VERSION_EXTRA = "current_version";
public static final String REQUIRED_VERSION_EXTRA = "required_version";
public static final String PAYLOAD_EXTRA = "payload";
private Class<?> activityClass;
public ActivityUpdateView(Class<?> gActivityClass) {
activityClass = gActivityClass;
}
@Override
| public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gPayload) {
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpMasterVersionProvider.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
| import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
| package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class AbstractHttpMasterVersionProvider extends MasterVersionProvider {
private URL url;
public AbstractHttpMasterVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getUrl() {
return url.toString();
}
protected abstract void processHttpResponseAndPutVersions(String gResponseString);
@Override
protected void fetchAndPutVersions() {
try {
| // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpMasterVersionProvider.java
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class AbstractHttpMasterVersionProvider extends MasterVersionProvider {
private URL url;
public AbstractHttpMasterVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getUrl() {
return url.toString();
}
protected abstract void processHttpResponseAndPutVersions(String gResponseString);
@Override
protected void fetchAndPutVersions() {
try {
| String stringResponse = Http.loadString(url);
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpMasterVersionProvider.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
| import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
| package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class AbstractHttpMasterVersionProvider extends MasterVersionProvider {
private URL url;
public AbstractHttpMasterVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getUrl() {
return url.toString();
}
protected abstract void processHttpResponseAndPutVersions(String gResponseString);
@Override
protected void fetchAndPutVersions() {
try {
String stringResponse = Http.loadString(url);
processHttpResponseAndPutVersions(stringResponse.toString());
} catch (IOException e) {
| // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpMasterVersionProvider.java
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class AbstractHttpMasterVersionProvider extends MasterVersionProvider {
private URL url;
public AbstractHttpMasterVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getUrl() {
return url.toString();
}
protected abstract void processHttpResponseAndPutVersions(String gResponseString);
@Override
protected void fetchAndPutVersions() {
try {
String stringResponse = Http.loadString(url);
processHttpResponseAndPutVersions(stringResponse.toString());
} catch (IOException e) {
| VersionResult versionResult = new VersionResult(e.toString(), e);
|
skoumalcz/force-update | example/src/main/java/net/skoumal/forceupdate/example/activites/ResetVersionsForceUpdateActivity.java | // Path: example/src/main/java/net/skoumal/forceupdate/example/ExampleApp.java
// public class ExampleApp extends Application {
//
// private final static boolean SHOW_CUSTOM_FORCED_VIEW = false;
//
// private static ExampleApp instance;
//
// private VersionProvider currentVersionProvider;
// private SharedPreferencesVersionProvider minAllowedVersionProvider;
// private SharedPreferencesVersionProvider recommendedVersionProvider;
// private SharedPreferencesVersionProvider excludedVersionProvider;
//
// private ForceUpdate forceUpdate;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES_VERSIONS,
// MODE_PRIVATE);
//
// /*
// -- Current version --
//
// The simples way to provide current version is via ApkVersionProvider, but you can
// implement your own provider of course.
// */
// currentVersionProvider = new ApkVersionProvider(this);
//
// /*
// -- Min allowed and recommended version --
//
// For this example purposes we use SharedPreferencesVersionProvider to fake min-allowed
// and recommended version. It is also great example of custom VersionProvider, but for
// real world purposes see use one of ready-to-use VersionProviders, or implement your own:
//
// https://github.com/skoumalcz/force-update/blob/master/doc/VersionProviders.md
// */
// Version defaultVersion = currentVersionProvider.getVersionResult().getVersion(); // default version when SharedPreferences are empty
// minAllowedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_MIN_ALLOWED_VERSION, defaultVersion);
// recommendedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_RECOMMENDED_VERSION, defaultVersion);
//
// /*
// -- Excluded version --
//
// To ban particular version we also use SharedPreferencesVersionProvider to fake it.
// */
// int [] apkVersionParts = currentVersionProvider.getVersionResult().getVersion().getVersionParts();
// Versions.decrementVersion(apkVersionParts);
// excludedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_EXCLUDED_VERSION, new Version(apkVersionParts));
//
// ForceUpdate.Builder builder = new ForceUpdate.Builder()
// .application(this)
// .debug(true)
// .currentVersionProvider(currentVersionProvider)
// .minAllowedVersionProvider(minAllowedVersionProvider)
// .recommendedVersionProvider(recommendedVersionProvider)
// .excludedVersionListProvider(excludedVersionProvider)
// .minAllowedVersionCheckMinInterval(1)
// .recommendedVersionCheckMinInterval(1)
// .excludedVersionListCheckMinInterval(1)
// .forcedUpdateView(new ActivityUpdateView(ResetVersionsForceUpdateActivity.class))
// .recommendedUpdateView(new ActivityUpdateView(RecommendedUpdateActivity.class));
//
// if (SHOW_CUSTOM_FORCED_VIEW) {
// //here you can show your custom activity or just exclude forcedUpdateView function to use default activity
// builder.addForceUpdateActivity(CustomForceUpdateActivity.class);
// builder.forcedUpdateView(new UpdateView() {
// @Override
// public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gUpdateMessage) {
// CustomForceUpdateActivity.start(gActivity, gCurrentVersion.toString(), gRequiredVersion.toString(), gUpdateMessage);
// }
// });
// }
//
// forceUpdate = builder.buildAndInit();
// }
//
// public static ExampleApp getInstance() {
// return instance;
// }
//
// public VersionProvider getCurrentVersionProvider() {
// return currentVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getMinAllowedVersionProvider() {
// return minAllowedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getRecommendedVersionProvider() {
// return recommendedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getExcludedVersionProvider() {
// return excludedVersionProvider;
// }
//
// public ForceUpdate getForceUpdate() {
// return forceUpdate;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/activity/ForceUpdateActivity.java
// public class ForceUpdateActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// onCreate(savedInstanceState, R.style.NoActionBarTheme);
//
// }
//
// public void onCreate(Bundle savedInstanceState, int gTheme) {
// super.onCreate(savedInstanceState);
//
// setTheme(gTheme);
//
// setContentView(R.layout.force_update_activity);
//
// findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// openGooglePlay();
// }
// });
// }
//
//
// public void openGooglePlay() {
// GooglePlay.openAppDetail(this);
// }
//
// public static void start(Activity gActivity) {
// Intent starter = new Intent(gActivity, ForceUpdateActivity.class);
// gActivity.startActivity(starter);
// }
// }
| import android.os.Bundle;
import android.view.View;
import com.jakewharton.processphoenix.ProcessPhoenix;
import net.skoumal.forceupdate.example.ExampleApp;
import net.skoumal.forceupdate.view.activity.ForceUpdateActivity;
| package net.skoumal.forceupdate.example.activites;
/**
* Created by gingo on 3.1.2017.
*/
public class ResetVersionsForceUpdateActivity extends ForceUpdateActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(net.skoumal.forceupdate.R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
| // Path: example/src/main/java/net/skoumal/forceupdate/example/ExampleApp.java
// public class ExampleApp extends Application {
//
// private final static boolean SHOW_CUSTOM_FORCED_VIEW = false;
//
// private static ExampleApp instance;
//
// private VersionProvider currentVersionProvider;
// private SharedPreferencesVersionProvider minAllowedVersionProvider;
// private SharedPreferencesVersionProvider recommendedVersionProvider;
// private SharedPreferencesVersionProvider excludedVersionProvider;
//
// private ForceUpdate forceUpdate;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES_VERSIONS,
// MODE_PRIVATE);
//
// /*
// -- Current version --
//
// The simples way to provide current version is via ApkVersionProvider, but you can
// implement your own provider of course.
// */
// currentVersionProvider = new ApkVersionProvider(this);
//
// /*
// -- Min allowed and recommended version --
//
// For this example purposes we use SharedPreferencesVersionProvider to fake min-allowed
// and recommended version. It is also great example of custom VersionProvider, but for
// real world purposes see use one of ready-to-use VersionProviders, or implement your own:
//
// https://github.com/skoumalcz/force-update/blob/master/doc/VersionProviders.md
// */
// Version defaultVersion = currentVersionProvider.getVersionResult().getVersion(); // default version when SharedPreferences are empty
// minAllowedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_MIN_ALLOWED_VERSION, defaultVersion);
// recommendedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_RECOMMENDED_VERSION, defaultVersion);
//
// /*
// -- Excluded version --
//
// To ban particular version we also use SharedPreferencesVersionProvider to fake it.
// */
// int [] apkVersionParts = currentVersionProvider.getVersionResult().getVersion().getVersionParts();
// Versions.decrementVersion(apkVersionParts);
// excludedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_EXCLUDED_VERSION, new Version(apkVersionParts));
//
// ForceUpdate.Builder builder = new ForceUpdate.Builder()
// .application(this)
// .debug(true)
// .currentVersionProvider(currentVersionProvider)
// .minAllowedVersionProvider(minAllowedVersionProvider)
// .recommendedVersionProvider(recommendedVersionProvider)
// .excludedVersionListProvider(excludedVersionProvider)
// .minAllowedVersionCheckMinInterval(1)
// .recommendedVersionCheckMinInterval(1)
// .excludedVersionListCheckMinInterval(1)
// .forcedUpdateView(new ActivityUpdateView(ResetVersionsForceUpdateActivity.class))
// .recommendedUpdateView(new ActivityUpdateView(RecommendedUpdateActivity.class));
//
// if (SHOW_CUSTOM_FORCED_VIEW) {
// //here you can show your custom activity or just exclude forcedUpdateView function to use default activity
// builder.addForceUpdateActivity(CustomForceUpdateActivity.class);
// builder.forcedUpdateView(new UpdateView() {
// @Override
// public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gUpdateMessage) {
// CustomForceUpdateActivity.start(gActivity, gCurrentVersion.toString(), gRequiredVersion.toString(), gUpdateMessage);
// }
// });
// }
//
// forceUpdate = builder.buildAndInit();
// }
//
// public static ExampleApp getInstance() {
// return instance;
// }
//
// public VersionProvider getCurrentVersionProvider() {
// return currentVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getMinAllowedVersionProvider() {
// return minAllowedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getRecommendedVersionProvider() {
// return recommendedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getExcludedVersionProvider() {
// return excludedVersionProvider;
// }
//
// public ForceUpdate getForceUpdate() {
// return forceUpdate;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/activity/ForceUpdateActivity.java
// public class ForceUpdateActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// onCreate(savedInstanceState, R.style.NoActionBarTheme);
//
// }
//
// public void onCreate(Bundle savedInstanceState, int gTheme) {
// super.onCreate(savedInstanceState);
//
// setTheme(gTheme);
//
// setContentView(R.layout.force_update_activity);
//
// findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// openGooglePlay();
// }
// });
// }
//
//
// public void openGooglePlay() {
// GooglePlay.openAppDetail(this);
// }
//
// public static void start(Activity gActivity) {
// Intent starter = new Intent(gActivity, ForceUpdateActivity.class);
// gActivity.startActivity(starter);
// }
// }
// Path: example/src/main/java/net/skoumal/forceupdate/example/activites/ResetVersionsForceUpdateActivity.java
import android.os.Bundle;
import android.view.View;
import com.jakewharton.processphoenix.ProcessPhoenix;
import net.skoumal.forceupdate.example.ExampleApp;
import net.skoumal.forceupdate.view.activity.ForceUpdateActivity;
package net.skoumal.forceupdate.example.activites;
/**
* Created by gingo on 3.1.2017.
*/
public class ResetVersionsForceUpdateActivity extends ForceUpdateActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(net.skoumal.forceupdate.R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
| ExampleApp.getInstance().getForceUpdate().clearCache();
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/view/dialog/ForceUpdateActivity.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/util/GooglePlay.java
// public class GooglePlay {
//
// public static void openAppDetail(Activity gContext) {
// String appPackage = gContext.getPackageName();
// Uri googlePlayUri = Uri.parse("market://details?id=" + appPackage);
// Intent googlePlayIntent = new Intent(Intent.ACTION_VIEW, googlePlayUri);
// boolean googlePlayAvailable = false;
//
// // try to find official Google Play app
// final List<ResolveInfo> availableApps = gContext.getPackageManager().queryIntentActivities(googlePlayIntent, 0);
// for (ResolveInfo app: availableApps) {
// if (app.activityInfo.applicationInfo.packageName.equals("com.android.vending")) {
//
// ActivityInfo appActivity = app.activityInfo;
// ComponentName component = new ComponentName(
// appActivity.applicationInfo.packageName,
// appActivity.name
// );
// googlePlayIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// googlePlayIntent.setComponent(component);
// gContext.startActivity(googlePlayIntent);
// googlePlayAvailable = true;
// break;
//
// }
// }
//
// if (!googlePlayAvailable) {
// if (availableApps.size() > 0) {
// // fallback to universal Google Play Intent
// gContext.startActivity(googlePlayIntent);
// } else {
// // if there is no app bind to market:// open Google Play in browser
// Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// gContext.startActivity(webIntent);
// }
// }
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import net.skoumal.forceupdate.R;
import net.skoumal.forceupdate.util.GooglePlay;
| package net.skoumal.forceupdate.view.dialog;
/**
* Created by gingo on 1.10.2016.
*/
public class ForceUpdateActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.NoActionBarTheme);
setContentView(R.layout.force_update_activity);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGooglePlay();
}
});
}
public void openGooglePlay() {
| // Path: force-update/src/main/java/net/skoumal/forceupdate/util/GooglePlay.java
// public class GooglePlay {
//
// public static void openAppDetail(Activity gContext) {
// String appPackage = gContext.getPackageName();
// Uri googlePlayUri = Uri.parse("market://details?id=" + appPackage);
// Intent googlePlayIntent = new Intent(Intent.ACTION_VIEW, googlePlayUri);
// boolean googlePlayAvailable = false;
//
// // try to find official Google Play app
// final List<ResolveInfo> availableApps = gContext.getPackageManager().queryIntentActivities(googlePlayIntent, 0);
// for (ResolveInfo app: availableApps) {
// if (app.activityInfo.applicationInfo.packageName.equals("com.android.vending")) {
//
// ActivityInfo appActivity = app.activityInfo;
// ComponentName component = new ComponentName(
// appActivity.applicationInfo.packageName,
// appActivity.name
// );
// googlePlayIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// googlePlayIntent.setComponent(component);
// gContext.startActivity(googlePlayIntent);
// googlePlayAvailable = true;
// break;
//
// }
// }
//
// if (!googlePlayAvailable) {
// if (availableApps.size() > 0) {
// // fallback to universal Google Play Intent
// gContext.startActivity(googlePlayIntent);
// } else {
// // if there is no app bind to market:// open Google Play in browser
// Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// gContext.startActivity(webIntent);
// }
// }
// }
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/dialog/ForceUpdateActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import net.skoumal.forceupdate.R;
import net.skoumal.forceupdate.util.GooglePlay;
package net.skoumal.forceupdate.view.dialog;
/**
* Created by gingo on 1.10.2016.
*/
public class ForceUpdateActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.NoActionBarTheme);
setContentView(R.layout.force_update_activity);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGooglePlay();
}
});
}
public void openGooglePlay() {
| GooglePlay.openAppDetail(this);
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/provider/MasterVersionProvider.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
| import net.skoumal.forceupdate.VersionResult;
| package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class MasterVersionProvider {
private SlaveVersionProvider recommendedProvider;
private SlaveVersionProvider minAllowedProvider;
private SlaveVersionProvider excludedProvider;
private boolean fetchInProgress = false;
public void fetchVersions() {
synchronized (this) {
fetchAndPutVersions();
}
}
| // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/provider/MasterVersionProvider.java
import net.skoumal.forceupdate.VersionResult;
package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 6.10.2016.
*/
public abstract class MasterVersionProvider {
private SlaveVersionProvider recommendedProvider;
private SlaveVersionProvider minAllowedProvider;
private SlaveVersionProvider excludedProvider;
private boolean fetchInProgress = false;
public void fetchVersions() {
synchronized (this) {
fetchAndPutVersions();
}
}
| public void putRecommendedVersionResult(VersionResult gResult) {
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpVersionProvider.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionProvider.java
// public interface VersionProvider {
//
// VersionResult getVersionResult();
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
| import net.skoumal.forceupdate.VersionProvider;
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
| package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 26.9.2016.
*/
public abstract class AbstractHttpVersionProvider implements VersionProvider {
private URL url;
public AbstractHttpVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
| // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionProvider.java
// public interface VersionProvider {
//
// VersionResult getVersionResult();
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpVersionProvider.java
import net.skoumal.forceupdate.VersionProvider;
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 26.9.2016.
*/
public abstract class AbstractHttpVersionProvider implements VersionProvider {
private URL url;
public AbstractHttpVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
| public VersionResult getVersionResult() {
|
skoumalcz/force-update | force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpVersionProvider.java | // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionProvider.java
// public interface VersionProvider {
//
// VersionResult getVersionResult();
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
| import net.skoumal.forceupdate.VersionProvider;
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
| package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 26.9.2016.
*/
public abstract class AbstractHttpVersionProvider implements VersionProvider {
private URL url;
public AbstractHttpVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public VersionResult getVersionResult() {
try {
| // Path: force-update/src/main/java/net/skoumal/forceupdate/VersionProvider.java
// public interface VersionProvider {
//
// VersionResult getVersionResult();
//
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/VersionResult.java
// public class VersionResult {
//
// private List<Version> versionList = new ArrayList<>(1);
//
// private List<String> payloadList = new ArrayList<>(1);
//
// private boolean isError = false;
//
// private String errorMessage = null;
//
// private Exception errorException = null;
//
// public VersionResult(Version gVersion, String gPayload) {
// versionList.add(gVersion);
// payloadList.add(gPayload);
// }
//
// public VersionResult(String gErrorMessage, Exception gErrorException) {
// errorMessage = gErrorMessage;
// errorException = gErrorException;
// isError = true;
// }
//
// public VersionResult(List<Version> gVersionList, List<String> gPayloadList) {
// versionList = gVersionList;
// payloadList = gPayloadList;
// }
//
// public Version getVersion() {
// if(isError || versionList.size() < 1) {
// return null;
// } else {
// return versionList.get(0);
// }
// }
//
// public String getPayload() {
// if(isError || payloadList.size() < 1) {
// return null;
// } else {
// return payloadList.get(0);
// }
// }
//
// public List<Version> getVersionList() {
// return versionList;
// }
//
// public List<String> getPayloadList() {
// return payloadList;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public Exception getErrorException() {
// return errorException;
// }
//
// public boolean isError() {
// return isError;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/util/Http.java
// public class Http {
//
// private static final int HTTP_TIMEOUT = 10 * 1000;
//
// public static String loadString(URL gUrl) throws IOException {
// HttpURLConnection urlConnection = null;
// try {
//
// urlConnection = (HttpURLConnection) gUrl.openConnection();
// urlConnection.setRequestMethod("GET");
// urlConnection.setUseCaches(false);
// urlConnection.setConnectTimeout(HTTP_TIMEOUT);
// urlConnection.setReadTimeout(HTTP_TIMEOUT);
// urlConnection.connect();
//
// int status = urlConnection.getResponseCode();
// if(status >= 200 && status < 300) {
//
// //TODO [1] fix this to not add new line sign to last line
// InputStream inputStream = urlConnection.getInputStream();
// BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder response = new StringBuilder();
// String line;
// boolean firstLine = true;
// while ((line = responseReader.readLine()) != null) {
// if(firstLine) {
// firstLine = false;
// } else {
// response.append('\n');
// }
// response.append(line);
// }
//
// return response.toString();
// } else {
// throw new IOException("HTTP status code " + status + " returned.");
// }
//
// } finally {
// if(urlConnection != null) {
// urlConnection.disconnect();
// }
// }
// }
//
// }
// Path: force-update/src/main/java/net/skoumal/forceupdate/provider/AbstractHttpVersionProvider.java
import net.skoumal.forceupdate.VersionProvider;
import net.skoumal.forceupdate.VersionResult;
import net.skoumal.forceupdate.util.Http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
package net.skoumal.forceupdate.provider;
/**
* Created by gingo on 26.9.2016.
*/
public abstract class AbstractHttpVersionProvider implements VersionProvider {
private URL url;
public AbstractHttpVersionProvider(String gUrl) {
try {
url = new URL(gUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public VersionResult getVersionResult() {
try {
| String stringResponse = Http.loadString(url);
|
skoumalcz/force-update | example/src/main/java/net/skoumal/forceupdate/example/activites/ResetVersionsRecommendedUpdateActivity.java | // Path: example/src/main/java/net/skoumal/forceupdate/example/ExampleApp.java
// public class ExampleApp extends Application {
//
// private final static boolean SHOW_CUSTOM_FORCED_VIEW = false;
//
// private static ExampleApp instance;
//
// private VersionProvider currentVersionProvider;
// private SharedPreferencesVersionProvider minAllowedVersionProvider;
// private SharedPreferencesVersionProvider recommendedVersionProvider;
// private SharedPreferencesVersionProvider excludedVersionProvider;
//
// private ForceUpdate forceUpdate;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES_VERSIONS,
// MODE_PRIVATE);
//
// /*
// -- Current version --
//
// The simples way to provide current version is via ApkVersionProvider, but you can
// implement your own provider of course.
// */
// currentVersionProvider = new ApkVersionProvider(this);
//
// /*
// -- Min allowed and recommended version --
//
// For this example purposes we use SharedPreferencesVersionProvider to fake min-allowed
// and recommended version. It is also great example of custom VersionProvider, but for
// real world purposes see use one of ready-to-use VersionProviders, or implement your own:
//
// https://github.com/skoumalcz/force-update/blob/master/doc/VersionProviders.md
// */
// Version defaultVersion = currentVersionProvider.getVersionResult().getVersion(); // default version when SharedPreferences are empty
// minAllowedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_MIN_ALLOWED_VERSION, defaultVersion);
// recommendedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_RECOMMENDED_VERSION, defaultVersion);
//
// /*
// -- Excluded version --
//
// To ban particular version we also use SharedPreferencesVersionProvider to fake it.
// */
// int [] apkVersionParts = currentVersionProvider.getVersionResult().getVersion().getVersionParts();
// Versions.decrementVersion(apkVersionParts);
// excludedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_EXCLUDED_VERSION, new Version(apkVersionParts));
//
// ForceUpdate.Builder builder = new ForceUpdate.Builder()
// .application(this)
// .debug(true)
// .currentVersionProvider(currentVersionProvider)
// .minAllowedVersionProvider(minAllowedVersionProvider)
// .recommendedVersionProvider(recommendedVersionProvider)
// .excludedVersionListProvider(excludedVersionProvider)
// .minAllowedVersionCheckMinInterval(1)
// .recommendedVersionCheckMinInterval(1)
// .excludedVersionListCheckMinInterval(1)
// .forcedUpdateView(new ActivityUpdateView(ResetVersionsForceUpdateActivity.class))
// .recommendedUpdateView(new ActivityUpdateView(RecommendedUpdateActivity.class));
//
// if (SHOW_CUSTOM_FORCED_VIEW) {
// //here you can show your custom activity or just exclude forcedUpdateView function to use default activity
// builder.addForceUpdateActivity(CustomForceUpdateActivity.class);
// builder.forcedUpdateView(new UpdateView() {
// @Override
// public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gUpdateMessage) {
// CustomForceUpdateActivity.start(gActivity, gCurrentVersion.toString(), gRequiredVersion.toString(), gUpdateMessage);
// }
// });
// }
//
// forceUpdate = builder.buildAndInit();
// }
//
// public static ExampleApp getInstance() {
// return instance;
// }
//
// public VersionProvider getCurrentVersionProvider() {
// return currentVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getMinAllowedVersionProvider() {
// return minAllowedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getRecommendedVersionProvider() {
// return recommendedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getExcludedVersionProvider() {
// return excludedVersionProvider;
// }
//
// public ForceUpdate getForceUpdate() {
// return forceUpdate;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/activity/ForceUpdateActivity.java
// public class ForceUpdateActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// onCreate(savedInstanceState, R.style.NoActionBarTheme);
//
// }
//
// public void onCreate(Bundle savedInstanceState, int gTheme) {
// super.onCreate(savedInstanceState);
//
// setTheme(gTheme);
//
// setContentView(R.layout.force_update_activity);
//
// findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// openGooglePlay();
// }
// });
// }
//
//
// public void openGooglePlay() {
// GooglePlay.openAppDetail(this);
// }
//
// public static void start(Activity gActivity) {
// Intent starter = new Intent(gActivity, ForceUpdateActivity.class);
// gActivity.startActivity(starter);
// }
// }
| import android.os.Bundle;
import android.view.View;
import com.jakewharton.processphoenix.ProcessPhoenix;
import net.skoumal.forceupdate.example.ExampleApp;
import net.skoumal.forceupdate.view.activity.ForceUpdateActivity;
| package net.skoumal.forceupdate.example.activites;
/**
* Created by gingo on 3.1.2017.
*/
public class ResetVersionsRecommendedUpdateActivity extends ForceUpdateActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(net.skoumal.forceupdate.R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
| // Path: example/src/main/java/net/skoumal/forceupdate/example/ExampleApp.java
// public class ExampleApp extends Application {
//
// private final static boolean SHOW_CUSTOM_FORCED_VIEW = false;
//
// private static ExampleApp instance;
//
// private VersionProvider currentVersionProvider;
// private SharedPreferencesVersionProvider minAllowedVersionProvider;
// private SharedPreferencesVersionProvider recommendedVersionProvider;
// private SharedPreferencesVersionProvider excludedVersionProvider;
//
// private ForceUpdate forceUpdate;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// instance = this;
//
// SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES_VERSIONS,
// MODE_PRIVATE);
//
// /*
// -- Current version --
//
// The simples way to provide current version is via ApkVersionProvider, but you can
// implement your own provider of course.
// */
// currentVersionProvider = new ApkVersionProvider(this);
//
// /*
// -- Min allowed and recommended version --
//
// For this example purposes we use SharedPreferencesVersionProvider to fake min-allowed
// and recommended version. It is also great example of custom VersionProvider, but for
// real world purposes see use one of ready-to-use VersionProviders, or implement your own:
//
// https://github.com/skoumalcz/force-update/blob/master/doc/VersionProviders.md
// */
// Version defaultVersion = currentVersionProvider.getVersionResult().getVersion(); // default version when SharedPreferences are empty
// minAllowedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_MIN_ALLOWED_VERSION, defaultVersion);
// recommendedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_RECOMMENDED_VERSION, defaultVersion);
//
// /*
// -- Excluded version --
//
// To ban particular version we also use SharedPreferencesVersionProvider to fake it.
// */
// int [] apkVersionParts = currentVersionProvider.getVersionResult().getVersion().getVersionParts();
// Versions.decrementVersion(apkVersionParts);
// excludedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_EXCLUDED_VERSION, new Version(apkVersionParts));
//
// ForceUpdate.Builder builder = new ForceUpdate.Builder()
// .application(this)
// .debug(true)
// .currentVersionProvider(currentVersionProvider)
// .minAllowedVersionProvider(minAllowedVersionProvider)
// .recommendedVersionProvider(recommendedVersionProvider)
// .excludedVersionListProvider(excludedVersionProvider)
// .minAllowedVersionCheckMinInterval(1)
// .recommendedVersionCheckMinInterval(1)
// .excludedVersionListCheckMinInterval(1)
// .forcedUpdateView(new ActivityUpdateView(ResetVersionsForceUpdateActivity.class))
// .recommendedUpdateView(new ActivityUpdateView(RecommendedUpdateActivity.class));
//
// if (SHOW_CUSTOM_FORCED_VIEW) {
// //here you can show your custom activity or just exclude forcedUpdateView function to use default activity
// builder.addForceUpdateActivity(CustomForceUpdateActivity.class);
// builder.forcedUpdateView(new UpdateView() {
// @Override
// public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gUpdateMessage) {
// CustomForceUpdateActivity.start(gActivity, gCurrentVersion.toString(), gRequiredVersion.toString(), gUpdateMessage);
// }
// });
// }
//
// forceUpdate = builder.buildAndInit();
// }
//
// public static ExampleApp getInstance() {
// return instance;
// }
//
// public VersionProvider getCurrentVersionProvider() {
// return currentVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getMinAllowedVersionProvider() {
// return minAllowedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getRecommendedVersionProvider() {
// return recommendedVersionProvider;
// }
//
// public SharedPreferencesVersionProvider getExcludedVersionProvider() {
// return excludedVersionProvider;
// }
//
// public ForceUpdate getForceUpdate() {
// return forceUpdate;
// }
// }
//
// Path: force-update/src/main/java/net/skoumal/forceupdate/view/activity/ForceUpdateActivity.java
// public class ForceUpdateActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// onCreate(savedInstanceState, R.style.NoActionBarTheme);
//
// }
//
// public void onCreate(Bundle savedInstanceState, int gTheme) {
// super.onCreate(savedInstanceState);
//
// setTheme(gTheme);
//
// setContentView(R.layout.force_update_activity);
//
// findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// openGooglePlay();
// }
// });
// }
//
//
// public void openGooglePlay() {
// GooglePlay.openAppDetail(this);
// }
//
// public static void start(Activity gActivity) {
// Intent starter = new Intent(gActivity, ForceUpdateActivity.class);
// gActivity.startActivity(starter);
// }
// }
// Path: example/src/main/java/net/skoumal/forceupdate/example/activites/ResetVersionsRecommendedUpdateActivity.java
import android.os.Bundle;
import android.view.View;
import com.jakewharton.processphoenix.ProcessPhoenix;
import net.skoumal.forceupdate.example.ExampleApp;
import net.skoumal.forceupdate.view.activity.ForceUpdateActivity;
package net.skoumal.forceupdate.example.activites;
/**
* Created by gingo on 3.1.2017.
*/
public class ResetVersionsRecommendedUpdateActivity extends ForceUpdateActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(net.skoumal.forceupdate.R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
| ExampleApp.getInstance().getMinAllowedVersionProvider().resetVersion();
|
EuregJUG-Maas-Rhine/site | src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
| import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; | /*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2016-07-13
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(PostApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
// Path: src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java
import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
/*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2016-07-13
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(PostApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters | @Import(SecurityTestConfig.class) // Needed to get rid of default CSRF protection |
EuregJUG-Maas-Rhine/site | src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
| import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; | /*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2016-07-13
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(PostApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters
@Import(SecurityTestConfig.class) // Needed to get rid of default CSRF protection
@AutoConfigureRestDocs(
outputDir = "target/generated-snippets",
uriHost = "euregjug.eu",
uriPort = 80
)
public class PostApiControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private PostRepository postRepository;
@MockBean
private PostIndexService postIndexService;
@Autowired
private ObjectMapper objectMapper;
private JacksonTester<PostEntity> json;
@Before
public void setup() {
JacksonTester.initFields(this, objectMapper);
}
@Test
public void createShouldWork() throws Exception {
final PostEntity postEntity1 = new PostEntity(new Date(), "new-site-is-live1", "New site is live", "Welcome to the new EuregJUG website. We have switched off the old static pages and replaced it with a little application based on Hibernate, Spring Data JPA, Spring Boot and Thymeleaf.");
postEntity1.setLocale(new Locale("de", "DE")); | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
// Path: src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java
import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
/*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2016-07-13
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(PostApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters
@Import(SecurityTestConfig.class) // Needed to get rid of default CSRF protection
@AutoConfigureRestDocs(
outputDir = "target/generated-snippets",
uriHost = "euregjug.eu",
uriPort = 80
)
public class PostApiControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private PostRepository postRepository;
@MockBean
private PostIndexService postIndexService;
@Autowired
private ObjectMapper objectMapper;
private JacksonTester<PostEntity> json;
@Before
public void setup() {
JacksonTester.initFields(this, objectMapper);
}
@Test
public void createShouldWork() throws Exception {
final PostEntity postEntity1 = new PostEntity(new Date(), "new-site-is-live1", "New site is live", "Welcome to the new EuregJUG website. We have switched off the old static pages and replaced it with a little application based on Hibernate, Spring Data JPA, Spring Boot and Thymeleaf.");
postEntity1.setLocale(new Locale("de", "DE")); | postEntity1.setStatus(Status.published); |
EuregJUG-Maas-Rhine/site | src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
| import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; |
@Test
public void searchShouldWork() throws Exception {
final PostEntity p1 = Reflect.on(
new PostEntity(new Date(), "new-site-is-live", "New site is live", "Welcome to the new EuregJUG website. We have switched off the old static pages and replaced it with a little application based on Hibernate, Spring Data JPA, Spring Boot and Thymeleaf.")
).call("updateUpdatedAt").set("id", 23).get();
when(this.postRepository.searchByKeyword("website")).thenReturn(Arrays.asList(p1));
this.mvc
.perform(
get("/api/posts/search")
.param("q", "website")
.principal(() -> "euregjug")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].slug", equalTo("new-site-is-live")))
.andDo(document("api/posts/search",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint())
));
verify(this.postRepository).searchByKeyword("website");
verifyNoMoreInteractions(this.postRepository);
}
@Test
public void updateShouldShouldWork() throws Exception {
final PostEntity updateEntity = new PostEntity(new Date(), "newslug", "newtitle", "newcontent"); | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
//
// Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
// Path: src/test/java/eu/euregjug/site/posts/PostApiControllerTest.java
import eu.euregjug.site.config.SecurityTestConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.euregjug.site.posts.PostEntity.Format;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Optional;
import org.joor.Reflect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
@Test
public void searchShouldWork() throws Exception {
final PostEntity p1 = Reflect.on(
new PostEntity(new Date(), "new-site-is-live", "New site is live", "Welcome to the new EuregJUG website. We have switched off the old static pages and replaced it with a little application based on Hibernate, Spring Data JPA, Spring Boot and Thymeleaf.")
).call("updateUpdatedAt").set("id", 23).get();
when(this.postRepository.searchByKeyword("website")).thenReturn(Arrays.asList(p1));
this.mvc
.perform(
get("/api/posts/search")
.param("q", "website")
.principal(() -> "euregjug")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].slug", equalTo("new-site-is-live")))
.andDo(document("api/posts/search",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint())
));
verify(this.postRepository).searchByKeyword("website");
verifyNoMoreInteractions(this.postRepository);
}
@Test
public void updateShouldShouldWork() throws Exception {
final PostEntity updateEntity = new PostEntity(new Date(), "newslug", "newtitle", "newcontent"); | updateEntity.setFormat(Format.markdown); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/posts/PostRepository.java | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
| import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.Repository;
import org.springframework.transaction.annotation.Transactional; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
public interface PostRepository extends Repository<PostEntity, Integer>, PostRepositoryExt {
/**
* Saves the given post.
*
* @param entity
* @return Persisted post
*/
PostEntity save(PostEntity entity);
/**
* @param id
* @return Post with the given Id or an empty optional
*/
@Transactional(readOnly = true)
Optional<PostEntity> findOne(Integer id);
/**
* Selects a post by date and slug.
*
* @param publishedOn
* @param slug
* @return
*/
@Transactional(readOnly = true)
Optional<PostEntity> findByPublishedOnAndSlug(Date publishedOn, String slug);
/**
* Selects a "page" of posts with a given status.
*
* @param status status as selection criteria
* @param pageable
* @return
*/
@Transactional(readOnly = true) | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
// Path: src/main/java/eu/euregjug/site/posts/PostRepository.java
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.Repository;
import org.springframework.transaction.annotation.Transactional;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
public interface PostRepository extends Repository<PostEntity, Integer>, PostRepositoryExt {
/**
* Saves the given post.
*
* @param entity
* @return Persisted post
*/
PostEntity save(PostEntity entity);
/**
* @param id
* @return Post with the given Id or an empty optional
*/
@Transactional(readOnly = true)
Optional<PostEntity> findOne(Integer id);
/**
* Selects a post by date and slug.
*
* @param publishedOn
* @param slug
* @return
*/
@Transactional(readOnly = true)
Optional<PostEntity> findByPublishedOnAndSlug(Date publishedOn, String slug);
/**
* Selects a "page" of posts with a given status.
*
* @param status status as selection criteria
* @param pageable
* @return
*/
@Transactional(readOnly = true) | Page<PostEntity> findAllByStatus(Status status, Pageable pageable); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/posts/PostRenderingService.java | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
| import eu.euregjug.site.posts.PostEntity.Format;
import lombok.extern.slf4j.Slf4j;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Options;
import org.asciidoctor.OptionsBuilder;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* A post rendering service that supports only AsciiDoc at the moment.
*
* @author Michael J. Simons, 2015-12-28
*/
@Service
@Slf4j
public class PostRenderingService {
@FunctionalInterface
interface Renderer {
String render(String content);
}
static class AsciiDocRenderer implements Renderer {
private final Asciidoctor asciidoctor = Asciidoctor.Factory.create();
private final Options options = OptionsBuilder.options().inPlace(false).get();
@Override
public String render(final String content) {
String rv;
try {
rv = asciidoctor.render(content, options);
} catch (Exception e) {
log.error("Could not render AsciiDoc content!", e);
rv = "<strong>Could not render content.</strong>";
}
return rv;
}
}
private final Renderer renderer = new AsciiDocRenderer();
@Cacheable(cacheNames = "renderedPosts", key = "#post.id")
public Post render(final PostEntity post) {
String renderedContent; | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Format {
//
// asciidoc, markdown
// }
// Path: src/main/java/eu/euregjug/site/posts/PostRenderingService.java
import eu.euregjug.site.posts.PostEntity.Format;
import lombok.extern.slf4j.Slf4j;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Options;
import org.asciidoctor.OptionsBuilder;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* A post rendering service that supports only AsciiDoc at the moment.
*
* @author Michael J. Simons, 2015-12-28
*/
@Service
@Slf4j
public class PostRenderingService {
@FunctionalInterface
interface Renderer {
String render(String content);
}
static class AsciiDocRenderer implements Renderer {
private final Asciidoctor asciidoctor = Asciidoctor.Factory.create();
private final Options options = OptionsBuilder.options().inPlace(false).get();
@Override
public String render(final String content) {
String rv;
try {
rv = asciidoctor.render(content, options);
} catch (Exception e) {
log.error("Could not render AsciiDoc content!", e);
rv = "<strong>Could not render content.</strong>";
}
return rv;
}
}
private final Renderer renderer = new AsciiDocRenderer();
@Cacheable(cacheNames = "renderedPosts", key = "#post.id")
public Post render(final PostEntity post) {
String renderedContent; | if (post.getFormat() != Format.asciidoc) { |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/support/thymeleaf/EuregJUGDialect.java | // Path: src/main/java/eu/euregjug/site/support/thymeleaf/expressions/Temporals.java
// public final class Temporals {
//
// /**
// * Locale of this instance
// */
// private final Locale locale;
//
// /**
// * Creates a new instance of a {@code Temporals} object bound to the given
// * {@link #locale}.
// *
// * @param locale The locale of this instance
// */
// public Temporals(final Locale locale) {
// this.locale = locale;
// }
//
// /**
// * Formats both date and time of the given {@code temporal} with one of the
// * predefined {@link FormatStyle}s.
// *
// * @param temporal The temporal object to be formatted
// * @param dateStyle The chosen date style
// * @param timeStyle The chosen time style
// * @return Formatted object
// */
// public String formatDateTime(final TemporalAccessor temporal, final FormatStyle dateStyle, final FormatStyle timeStyle) {
// return DateTimeFormatter.ofLocalizedDateTime(dateStyle, timeStyle).withLocale(this.locale).format(temporal);
// }
//
// /**
// * Formats the date part of the given {@code temporal} with one of the
// * predefined {@link FormatStyle}s.
// *
// * @param temporal The temporal object to be formatted
// * @param dateStyle The chosen date style
// * @return Formatted object
// */
// public String formatDate(final TemporalAccessor temporal, final FormatStyle dateStyle) {
// return DateTimeFormatter.ofLocalizedDate(dateStyle).withLocale(this.locale).format(temporal);
// }
//
// /**
// * Formats a temporal accessor according to the given {@code pattern}.
// *
// * @param temporal An arbitrary temporal thing
// * @param pattern The pattern to format the year-mont
// * @return Formatted object
// */
// public String format(final TemporalAccessor temporal, final String pattern) {
// return DateTimeFormatter.ofPattern(pattern, locale).format(temporal);
// }
// }
| import eu.euregjug.site.support.thymeleaf.expressions.Temporals;
import java.util.HashMap;
import java.util.Map;
import org.thymeleaf.context.IProcessingContext;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.dialect.IExpressionEnhancingDialect; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.support.thymeleaf;
/**
* This is a custom dialect for the thymeleaf templates. It contains among
* others serveral methods for formatting modern {@code java.time} instances.
*
* @author Michael J. Simons, 2015-01-04
*/
public final class EuregJUGDialect extends AbstractDialect implements IExpressionEnhancingDialect {
@Override
public String getPrefix() {
return "eur";
}
@Override
public Map<String, Object> getAdditionalExpressionObjects(final IProcessingContext processingContext) {
final Map<String, Object> expressionObjects = new HashMap<>(); | // Path: src/main/java/eu/euregjug/site/support/thymeleaf/expressions/Temporals.java
// public final class Temporals {
//
// /**
// * Locale of this instance
// */
// private final Locale locale;
//
// /**
// * Creates a new instance of a {@code Temporals} object bound to the given
// * {@link #locale}.
// *
// * @param locale The locale of this instance
// */
// public Temporals(final Locale locale) {
// this.locale = locale;
// }
//
// /**
// * Formats both date and time of the given {@code temporal} with one of the
// * predefined {@link FormatStyle}s.
// *
// * @param temporal The temporal object to be formatted
// * @param dateStyle The chosen date style
// * @param timeStyle The chosen time style
// * @return Formatted object
// */
// public String formatDateTime(final TemporalAccessor temporal, final FormatStyle dateStyle, final FormatStyle timeStyle) {
// return DateTimeFormatter.ofLocalizedDateTime(dateStyle, timeStyle).withLocale(this.locale).format(temporal);
// }
//
// /**
// * Formats the date part of the given {@code temporal} with one of the
// * predefined {@link FormatStyle}s.
// *
// * @param temporal The temporal object to be formatted
// * @param dateStyle The chosen date style
// * @return Formatted object
// */
// public String formatDate(final TemporalAccessor temporal, final FormatStyle dateStyle) {
// return DateTimeFormatter.ofLocalizedDate(dateStyle).withLocale(this.locale).format(temporal);
// }
//
// /**
// * Formats a temporal accessor according to the given {@code pattern}.
// *
// * @param temporal An arbitrary temporal thing
// * @param pattern The pattern to format the year-mont
// * @return Formatted object
// */
// public String format(final TemporalAccessor temporal, final String pattern) {
// return DateTimeFormatter.ofPattern(pattern, locale).format(temporal);
// }
// }
// Path: src/main/java/eu/euregjug/site/support/thymeleaf/EuregJUGDialect.java
import eu.euregjug.site.support.thymeleaf.expressions.Temporals;
import java.util.HashMap;
import java.util.Map;
import org.thymeleaf.context.IProcessingContext;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.dialect.IExpressionEnhancingDialect;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.support.thymeleaf;
/**
* This is a custom dialect for the thymeleaf templates. It contains among
* others serveral methods for formatting modern {@code java.time} instances.
*
* @author Michael J. Simons, 2015-01-04
*/
public final class EuregJUGDialect extends AbstractDialect implements IExpressionEnhancingDialect {
@Override
public String getPrefix() {
return "eur";
}
@Override
public Map<String, Object> getAdditionalExpressionObjects(final IProcessingContext processingContext) {
final Map<String, Object> expressionObjects = new HashMap<>(); | expressionObjects.put("temporals", new Temporals(processingContext.getContext().getLocale())); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/config/WebConfig.java | // Path: src/main/java/eu/euregjug/site/support/thymeleaf/EuregJUGDialect.java
// public final class EuregJUGDialect extends AbstractDialect implements IExpressionEnhancingDialect {
//
// @Override
// public String getPrefix() {
// return "eur";
// }
//
// @Override
// public Map<String, Object> getAdditionalExpressionObjects(final IProcessingContext processingContext) {
// final Map<String, Object> expressionObjects = new HashMap<>();
// expressionObjects.put("temporals", new Temporals(processingContext.getContext().getLocale()));
// return expressionObjects;
// }
// }
| import eu.euregjug.site.support.thymeleaf.EuregJUGDialect;
import java.time.Duration;
import java.util.Locale;
import java.util.TimeZone;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; | /*
* Copyright 2015-2018 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.config;
/**
* @author Michael J. Simons, 2015-12-27
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/about").setViewName("about");
registry.addViewController("/imprint").setViewName("imprint");
}
@Bean | // Path: src/main/java/eu/euregjug/site/support/thymeleaf/EuregJUGDialect.java
// public final class EuregJUGDialect extends AbstractDialect implements IExpressionEnhancingDialect {
//
// @Override
// public String getPrefix() {
// return "eur";
// }
//
// @Override
// public Map<String, Object> getAdditionalExpressionObjects(final IProcessingContext processingContext) {
// final Map<String, Object> expressionObjects = new HashMap<>();
// expressionObjects.put("temporals", new Temporals(processingContext.getContext().getLocale()));
// return expressionObjects;
// }
// }
// Path: src/main/java/eu/euregjug/site/config/WebConfig.java
import eu.euregjug.site.support.thymeleaf.EuregJUGDialect;
import java.time.Duration;
import java.util.Locale;
import java.util.TimeZone;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
/*
* Copyright 2015-2018 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.config;
/**
* @author Michael J. Simons, 2015-12-27
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/about").setViewName("about");
registry.addViewController("/imprint").setViewName("imprint");
}
@Bean | public EuregJUGDialect enSupplyDialect() { |
EuregJUG-Maas-Rhine/site | src/test/java/eu/euregjug/site/assets/AssetApiControllerTest.java | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
| import com.mongodb.gridfs.GridFSDBFile;
import eu.euregjug.site.config.SecurityTestConfig;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.time.format.TextStyle;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import java.util.Locale;
import org.apache.tika.Tika;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.joor.Reflect;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.mock.web.MockMultipartFile;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; | /*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.assets;
/**
* @author Michael J. Simons, 2016-07-15
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(AssetApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters | // Path: src/test/java/eu/euregjug/site/config/SecurityTestConfig.java
// @Configuration
// @Profile("test")
// public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
// }
// }
// Path: src/test/java/eu/euregjug/site/assets/AssetApiControllerTest.java
import com.mongodb.gridfs.GridFSDBFile;
import eu.euregjug.site.config.SecurityTestConfig;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.time.format.TextStyle;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import java.util.Locale;
import org.apache.tika.Tika;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.joor.Reflect;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.mock.web.MockMultipartFile;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
/*
* Copyright 2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.assets;
/**
* @author Michael J. Simons, 2016-07-15
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@WebMvcTest(AssetApiController.class)
@EnableSpringDataWebSupport // Needed to enable resolving of Pageable and other parameters | @Import(SecurityTestConfig.class) // Needed to get rid of default CSRF protection |
EuregJUG-Maas-Rhine/site | src/test/java/eu/euregjug/site/events/EventEntityTest.java | // Path: src/main/java/eu/euregjug/site/events/EventEntity.java
// public enum Status {
//
// open, closed
// }
| import eu.euregjug.site.events.EventEntity.Status;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test; | /*
* Copyright 2016-2017 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.events;
/**
* @author Michael J. Simons, 2016-08-16
*/
public class EventEntityTest {
@Test
public void getDisplayNameShouldWork() {
final EventEntity event = new EventEntity(Calendar.getInstance(), "test", "test");
assertThat(event.getDisplayName(), is("test"));
event.setSpeaker(" \t ");
assertThat(event.getDisplayName(), is("test"));
event.setSpeaker("test");
assertThat(event.getDisplayName(), is("test - test"));
}
@Test
public void isOpenForRegistrationShouldWork() {
EventEntity event;
event = new EventEntity(GregorianCalendar.from(LocalDateTime.now().plusDays(1).atZone(ZoneId.systemDefault())), "test", "test");
assertThat(event.isOpenForRegistration(), is(true)); | // Path: src/main/java/eu/euregjug/site/events/EventEntity.java
// public enum Status {
//
// open, closed
// }
// Path: src/test/java/eu/euregjug/site/events/EventEntityTest.java
import eu.euregjug.site.events.EventEntity.Status;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/*
* Copyright 2016-2017 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.events;
/**
* @author Michael J. Simons, 2016-08-16
*/
public class EventEntityTest {
@Test
public void getDisplayNameShouldWork() {
final EventEntity event = new EventEntity(Calendar.getInstance(), "test", "test");
assertThat(event.getDisplayName(), is("test"));
event.setSpeaker(" \t ");
assertThat(event.getDisplayName(), is("test"));
event.setSpeaker("test");
assertThat(event.getDisplayName(), is("test - test"));
}
@Test
public void isOpenForRegistrationShouldWork() {
EventEntity event;
event = new EventEntity(GregorianCalendar.from(LocalDateTime.now().plusDays(1).atZone(ZoneId.systemDefault())), "test", "test");
assertThat(event.isOpenForRegistration(), is(true)); | event.setStatus(Status.closed); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/web/IndexRssView.java | // Path: src/main/java/eu/euregjug/site/posts/Post.java
// @Getter
// public final class Post implements Serializable {
//
// private static final long serialVersionUID = 5598037121835514804L;
//
// private final LocalDate publishedOn;
//
// private final String slug;
//
// private final String title;
//
// private final String content;
//
// public Post(final Date publishedOn, final String slug, final String title, final String content) {
// this.publishedOn = publishedOn instanceof java.sql.Date ? ((java.sql.Date) publishedOn).toLocalDate() : publishedOn.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// this.slug = slug;
// this.title = title;
// this.content = content;
// }
//
// /**
// * Maps an entity to a post without rendering the content.
// *
// * @param postEntity
// */
// public Post(final PostEntity postEntity) {
// this(postEntity.getPublishedOn(), postEntity.getSlug(), postEntity.getTitle(), null);
// }
// }
| import ac.simons.syndication.utils.SyndicationGuid;
import ac.simons.syndication.utils.SyndicationLink;
import com.rometools.modules.atom.modules.AtomLinkModuleImpl;
import com.rometools.rome.feed.atom.Link;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;
import eu.euregjug.site.posts.Post;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.web;
/**
* @author Michael J. Simons, 2015-12-30
*/
@Component("index.rss")
@SuppressWarnings({"squid:MaximumInheritanceDepth"}) // Cannot change this...
class IndexRssView extends AbstractRssFeedView {
private static final ZoneId UTC = ZoneId.of("UTC");
private final MessageSource messageSource;
private final DateTimeFormatter permalinkDateFormatter;
IndexRssView(final MessageSource messageSource) {
this.messageSource = messageSource;
this.permalinkDateFormatter = DateTimeFormatter.ofPattern("/y/M/d", Locale.ENGLISH);
}
String getAbsoluteUrl(final HttpServletRequest request, final String relativeUrl) {
final int port = request.getServerPort();
final String hostWithPort = String.format("%s://%s%s",
request.isSecure() ? "https" : "http",
request.getServerName(),
Arrays.asList(80, 443).contains(port) ? "" : String.format(":%d", port)
);
return String.format("%s%s%s", hostWithPort, request.getContextPath(), relativeUrl);
}
@Override
protected void buildFeedMetadata(final Map<String, Object> model, final Channel feed, final HttpServletRequest request) { | // Path: src/main/java/eu/euregjug/site/posts/Post.java
// @Getter
// public final class Post implements Serializable {
//
// private static final long serialVersionUID = 5598037121835514804L;
//
// private final LocalDate publishedOn;
//
// private final String slug;
//
// private final String title;
//
// private final String content;
//
// public Post(final Date publishedOn, final String slug, final String title, final String content) {
// this.publishedOn = publishedOn instanceof java.sql.Date ? ((java.sql.Date) publishedOn).toLocalDate() : publishedOn.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// this.slug = slug;
// this.title = title;
// this.content = content;
// }
//
// /**
// * Maps an entity to a post without rendering the content.
// *
// * @param postEntity
// */
// public Post(final PostEntity postEntity) {
// this(postEntity.getPublishedOn(), postEntity.getSlug(), postEntity.getTitle(), null);
// }
// }
// Path: src/main/java/eu/euregjug/site/web/IndexRssView.java
import ac.simons.syndication.utils.SyndicationGuid;
import ac.simons.syndication.utils.SyndicationLink;
import com.rometools.modules.atom.modules.AtomLinkModuleImpl;
import com.rometools.rome.feed.atom.Link;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;
import eu.euregjug.site.posts.Post;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.web;
/**
* @author Michael J. Simons, 2015-12-30
*/
@Component("index.rss")
@SuppressWarnings({"squid:MaximumInheritanceDepth"}) // Cannot change this...
class IndexRssView extends AbstractRssFeedView {
private static final ZoneId UTC = ZoneId.of("UTC");
private final MessageSource messageSource;
private final DateTimeFormatter permalinkDateFormatter;
IndexRssView(final MessageSource messageSource) {
this.messageSource = messageSource;
this.permalinkDateFormatter = DateTimeFormatter.ofPattern("/y/M/d", Locale.ENGLISH);
}
String getAbsoluteUrl(final HttpServletRequest request, final String relativeUrl) {
final int port = request.getServerPort();
final String hostWithPort = String.format("%s://%s%s",
request.isSecure() ? "https" : "http",
request.getServerName(),
Arrays.asList(80, 443).contains(port) ? "" : String.format(":%d", port)
);
return String.format("%s%s%s", hostWithPort, request.getContextPath(), relativeUrl);
}
@Override
protected void buildFeedMetadata(final Map<String, Object> model, final Channel feed, final HttpServletRequest request) { | final Page<Post> posts = (Page<Post>) model.get("posts"); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/posts/PostApiController.java | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
//
// Path: src/main/java/eu/euregjug/site/support/ResourceNotFoundException.java
// @ResponseStatus(HttpStatus.NOT_FOUND)
// public class ResourceNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = -4819169062859178748L;
// }
| import eu.euregjug.site.posts.PostEntity.Status;
import eu.euregjug.site.support.ResourceNotFoundException;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/posts")
class PostApiController {
private final PostRepository postRepository;
private final PostIndexService postIndexService;
@RequestMapping(method = POST)
@PreAuthorize("isAuthenticated()")
@ResponseStatus(CREATED)
public PostEntity create(@Valid @RequestBody final PostEntity newPost) {
newPost.setLocale(Optional.ofNullable(newPost.getLocale()).orElseGet(() -> new Locale("en", "US"))); | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
//
// Path: src/main/java/eu/euregjug/site/support/ResourceNotFoundException.java
// @ResponseStatus(HttpStatus.NOT_FOUND)
// public class ResourceNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = -4819169062859178748L;
// }
// Path: src/main/java/eu/euregjug/site/posts/PostApiController.java
import eu.euregjug.site.posts.PostEntity.Status;
import eu.euregjug.site.support.ResourceNotFoundException;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/posts")
class PostApiController {
private final PostRepository postRepository;
private final PostIndexService postIndexService;
@RequestMapping(method = POST)
@PreAuthorize("isAuthenticated()")
@ResponseStatus(CREATED)
public PostEntity create(@Valid @RequestBody final PostEntity newPost) {
newPost.setLocale(Optional.ofNullable(newPost.getLocale()).orElseGet(() -> new Locale("en", "US"))); | newPost.setStatus(Optional.ofNullable(newPost.getStatus()).orElse(Status.draft)); |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/posts/PostApiController.java | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
//
// Path: src/main/java/eu/euregjug/site/support/ResourceNotFoundException.java
// @ResponseStatus(HttpStatus.NOT_FOUND)
// public class ResourceNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = -4819169062859178748L;
// }
| import eu.euregjug.site.posts.PostEntity.Status;
import eu.euregjug.site.support.ResourceNotFoundException;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam; | /*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/posts")
class PostApiController {
private final PostRepository postRepository;
private final PostIndexService postIndexService;
@RequestMapping(method = POST)
@PreAuthorize("isAuthenticated()")
@ResponseStatus(CREATED)
public PostEntity create(@Valid @RequestBody final PostEntity newPost) {
newPost.setLocale(Optional.ofNullable(newPost.getLocale()).orElseGet(() -> new Locale("en", "US")));
newPost.setStatus(Optional.ofNullable(newPost.getStatus()).orElse(Status.draft));
return this.postRepository.save(newPost);
}
@RequestMapping(method = GET)
public Page<PostEntity> get(final Pageable pageable) {
return this.postRepository.findAll(pageable);
}
@RequestMapping(path = "/search", method = GET)
public List<PostEntity> get(@RequestParam final String q) {
return this.postRepository.searchByKeyword(q);
}
@RequestMapping(path = "/{id:\\d+}", method = PUT)
@PreAuthorize("isAuthenticated()")
@Transactional
@CacheEvict(cacheNames = "renderedPosts", key = "#id")
public PostEntity update(@PathVariable final Integer id, @Valid @RequestBody final PostEntity updatedPost) { | // Path: src/main/java/eu/euregjug/site/posts/PostEntity.java
// public enum Status {
//
// draft, published, hidden
// }
//
// Path: src/main/java/eu/euregjug/site/support/ResourceNotFoundException.java
// @ResponseStatus(HttpStatus.NOT_FOUND)
// public class ResourceNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = -4819169062859178748L;
// }
// Path: src/main/java/eu/euregjug/site/posts/PostApiController.java
import eu.euregjug.site.posts.PostEntity.Status;
import eu.euregjug.site.support.ResourceNotFoundException;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam;
/*
* Copyright 2015-2016 EuregJUG.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.euregjug.site.posts;
/**
* @author Michael J. Simons, 2015-12-28
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/posts")
class PostApiController {
private final PostRepository postRepository;
private final PostIndexService postIndexService;
@RequestMapping(method = POST)
@PreAuthorize("isAuthenticated()")
@ResponseStatus(CREATED)
public PostEntity create(@Valid @RequestBody final PostEntity newPost) {
newPost.setLocale(Optional.ofNullable(newPost.getLocale()).orElseGet(() -> new Locale("en", "US")));
newPost.setStatus(Optional.ofNullable(newPost.getStatus()).orElse(Status.draft));
return this.postRepository.save(newPost);
}
@RequestMapping(method = GET)
public Page<PostEntity> get(final Pageable pageable) {
return this.postRepository.findAll(pageable);
}
@RequestMapping(path = "/search", method = GET)
public List<PostEntity> get(@RequestParam final String q) {
return this.postRepository.searchByKeyword(q);
}
@RequestMapping(path = "/{id:\\d+}", method = PUT)
@PreAuthorize("isAuthenticated()")
@Transactional
@CacheEvict(cacheNames = "renderedPosts", key = "#id")
public PostEntity update(@PathVariable final Integer id, @Valid @RequestBody final PostEntity updatedPost) { | final PostEntity postEntity = this.postRepository.findOne(id).orElseThrow(ResourceNotFoundException::new); |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/LessThanOrEqualTo.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code lessThanOrEqualTo()} methods.
*/
@Transformer(name = Names.LESS_THAN_OR_EQUAL_TO, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class LessThanOrEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/LessThanOrEqualTo.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code lessThanOrEqualTo()} methods.
*/
@Transformer(name = Names.LESS_THAN_OR_EQUAL_TO, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class LessThanOrEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.lessThanOrEqualTo(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is less than or equal to" : "is not less than or equal to", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/NotEqualTo.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code notEqualTo()} methods.
*/
@Transformer(name = Names.NOT_EQUAL_TO, validArgTypes = {Boolean.class, Date.class, Double.class, Float.class,
Integer.class, Long.class, Short.class, String.class})
public class NotEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.BOOLEAN == fieldType) return realmQuery.notEqualTo(field, (Boolean) args[0]);
else if (FieldType.DATE == fieldType) return realmQuery.notEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.notEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.notEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.notEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.notEqualTo(field, (Long) args[0]);
else if (FieldType.SHORT == fieldType) return realmQuery.notEqualTo(field, (Short) args[0]);
else if (FieldType.STRING == fieldType) return realmQuery.notEqualTo(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format(current.getFieldType() == FieldType.STRING ? "%s %s “%s”" : "%s %s %s",
ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/NotEqualTo.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code notEqualTo()} methods.
*/
@Transformer(name = Names.NOT_EQUAL_TO, validArgTypes = {Boolean.class, Date.class, Double.class, Float.class,
Integer.class, Long.class, Short.class, String.class})
public class NotEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.BOOLEAN == fieldType) return realmQuery.notEqualTo(field, (Boolean) args[0]);
else if (FieldType.DATE == fieldType) return realmQuery.notEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.notEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.notEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.notEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.notEqualTo(field, (Long) args[0]);
else if (FieldType.SHORT == fieldType) return realmQuery.notEqualTo(field, (Short) args[0]);
else if (FieldType.STRING == fieldType) return realmQuery.notEqualTo(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format(current.getFieldType() == FieldType.STRING ? "%s %s “%s”" : "%s %s %s",
ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is unequal to" : "is not unequal to", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/StringContains.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#contains(String, String)}.
*/
@Transformer(name = Names.STRING_CONTAINS, validArgTypes = {String.class})
public class StringContains extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.STRING == fieldType) return realmQuery.contains(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/StringContains.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#contains(String, String)}.
*/
@Transformer(name = Names.STRING_CONTAINS, validArgTypes = {String.class})
public class StringContains extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.STRING == fieldType) return realmQuery.contains(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "contains" : "does not contain", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/EndsWith.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#endsWith(String, String)}.
*/
@Transformer(name = Names.ENDS_WITH, validArgTypes = {String.class})
public class EndsWith extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
if (FieldType.STRING == fieldType) return realmQuery.endsWith(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/EndsWith.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#endsWith(String, String)}.
*/
@Transformer(name = Names.ENDS_WITH, validArgTypes = {String.class})
public class EndsWith extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
if (FieldType.STRING == fieldType) return realmQuery.endsWith(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "ends with" : "does not end with", current.getArgs()[0]); |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/Between.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code between()} methods.
*/
@Transformer(name = Names.BETWEEN, numArgs = 2, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class Between extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.between(field, (Date) args[0], (Date) args[1]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.between(field, (Double) args[0], (Double) args[1]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.between(field, (Float) args[0], (Float) args[1]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.between(field, (Integer) args[0], (Integer) args[1]);
else if (FieldType.LONG == fieldType)
return realmQuery.between(field, (Long) args[0], (Long) args[1]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s and %s", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/Between.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code between()} methods.
*/
@Transformer(name = Names.BETWEEN, numArgs = 2, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class Between extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.between(field, (Date) args[0], (Date) args[1]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.between(field, (Double) args[0], (Double) args[1]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.between(field, (Float) args[0], (Float) args[1]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.between(field, (Integer) args[0], (Integer) args[1]);
else if (FieldType.LONG == fieldType)
return realmQuery.between(field, (Long) args[0], (Long) args[1]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s and %s", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is between" : "is not between", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/RealmUserQuery.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/Condition.java
// public enum Type {
// NORMAL("NORMAL"), NO_ARGS("NO_ARGS"), BEGIN_GROUP("BEGIN_GROUP"), END_GROUP("END_GROUP"), OR("OR"), NOT("NOT");
//
// private final String name;
//
// Type(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Type getForName(String name) {
// switch (name) {
// case "NORMAL":
// return NORMAL;
// case "NO_ARGS":
// return NO_ARGS;
// case "BEGIN_GROUP":
// return BEGIN_GROUP;
// case "END_GROUP":
// return END_GROUP;
// case "OR":
// return OR;
// case "NOT":
// return NOT;
// default:
// throw new IllegalArgumentException("Invalid Condition type name.");
// }
// }
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isAnyOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return true;
// return false;
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isNoneOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return false;
// return true;
// }
| import android.os.Parcel;
import android.os.Parcelable;
import com.squareup.phrase.ListPhrase;
import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmResults;
import io.realm.Sort;
import java.util.ArrayList;
import java.util.regex.Pattern;
import static com.bkromhout.ruqus.Condition.Type.*;
import static com.bkromhout.ruqus.ReadableStringUtils.isAnyOf;
import static com.bkromhout.ruqus.ReadableStringUtils.isNoneOf; | * @return Human-readable query string.
*/
@Override
public String toString() {
if (!isQueryValid()) return null;
// Build up visible string. Start by stating the visible name of the type our results will be.
StringBuilder builder = new StringBuilder()
.append("Find all ")
.append(Ruqus.getClassData().visibleNameOf(queryClass));
// Next, loop through any conditions, appending their human-readable strings and applicable separators.
if (!conditions.isEmpty()) {
builder.append(" where ");
for (int i = 0; i < conditions.size(); i++) {
Condition previous = i - 1 >= 0 ? conditions.get(i - 1) : null;
Condition current = conditions.get(i);
Condition next = i + 1 < conditions.size() ? conditions.get(i + 1) : null;
// Append human-readable condition string.
String conditionPart = current.makeReadableString(previous, next);
builder.append(conditionPart);
// If we don't have any more conditions after this one, just append a period and continue.
if (next == null) {
builder.append(".");
continue;
}
// Append a space if applicable. | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/Condition.java
// public enum Type {
// NORMAL("NORMAL"), NO_ARGS("NO_ARGS"), BEGIN_GROUP("BEGIN_GROUP"), END_GROUP("END_GROUP"), OR("OR"), NOT("NOT");
//
// private final String name;
//
// Type(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Type getForName(String name) {
// switch (name) {
// case "NORMAL":
// return NORMAL;
// case "NO_ARGS":
// return NO_ARGS;
// case "BEGIN_GROUP":
// return BEGIN_GROUP;
// case "END_GROUP":
// return END_GROUP;
// case "OR":
// return OR;
// case "NOT":
// return NOT;
// default:
// throw new IllegalArgumentException("Invalid Condition type name.");
// }
// }
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isAnyOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return true;
// return false;
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isNoneOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return false;
// return true;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/RealmUserQuery.java
import android.os.Parcel;
import android.os.Parcelable;
import com.squareup.phrase.ListPhrase;
import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmResults;
import io.realm.Sort;
import java.util.ArrayList;
import java.util.regex.Pattern;
import static com.bkromhout.ruqus.Condition.Type.*;
import static com.bkromhout.ruqus.ReadableStringUtils.isAnyOf;
import static com.bkromhout.ruqus.ReadableStringUtils.isNoneOf;
* @return Human-readable query string.
*/
@Override
public String toString() {
if (!isQueryValid()) return null;
// Build up visible string. Start by stating the visible name of the type our results will be.
StringBuilder builder = new StringBuilder()
.append("Find all ")
.append(Ruqus.getClassData().visibleNameOf(queryClass));
// Next, loop through any conditions, appending their human-readable strings and applicable separators.
if (!conditions.isEmpty()) {
builder.append(" where ");
for (int i = 0; i < conditions.size(); i++) {
Condition previous = i - 1 >= 0 ? conditions.get(i - 1) : null;
Condition current = conditions.get(i);
Condition next = i + 1 < conditions.size() ? conditions.get(i + 1) : null;
// Append human-readable condition string.
String conditionPart = current.makeReadableString(previous, next);
builder.append(conditionPart);
// If we don't have any more conditions after this one, just append a period and continue.
if (next == null) {
builder.append(".");
continue;
}
// Append a space if applicable. | if (isNoneOf(current, BEGIN_GROUP, NOT) && isNoneOf(next, END_GROUP)) |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/RealmUserQuery.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/Condition.java
// public enum Type {
// NORMAL("NORMAL"), NO_ARGS("NO_ARGS"), BEGIN_GROUP("BEGIN_GROUP"), END_GROUP("END_GROUP"), OR("OR"), NOT("NOT");
//
// private final String name;
//
// Type(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Type getForName(String name) {
// switch (name) {
// case "NORMAL":
// return NORMAL;
// case "NO_ARGS":
// return NO_ARGS;
// case "BEGIN_GROUP":
// return BEGIN_GROUP;
// case "END_GROUP":
// return END_GROUP;
// case "OR":
// return OR;
// case "NOT":
// return NOT;
// default:
// throw new IllegalArgumentException("Invalid Condition type name.");
// }
// }
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isAnyOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return true;
// return false;
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isNoneOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return false;
// return true;
// }
| import android.os.Parcel;
import android.os.Parcelable;
import com.squareup.phrase.ListPhrase;
import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmResults;
import io.realm.Sort;
import java.util.ArrayList;
import java.util.regex.Pattern;
import static com.bkromhout.ruqus.Condition.Type.*;
import static com.bkromhout.ruqus.ReadableStringUtils.isAnyOf;
import static com.bkromhout.ruqus.ReadableStringUtils.isNoneOf; | if (!isQueryValid()) return null;
// Build up visible string. Start by stating the visible name of the type our results will be.
StringBuilder builder = new StringBuilder()
.append("Find all ")
.append(Ruqus.getClassData().visibleNameOf(queryClass));
// Next, loop through any conditions, appending their human-readable strings and applicable separators.
if (!conditions.isEmpty()) {
builder.append(" where ");
for (int i = 0; i < conditions.size(); i++) {
Condition previous = i - 1 >= 0 ? conditions.get(i - 1) : null;
Condition current = conditions.get(i);
Condition next = i + 1 < conditions.size() ? conditions.get(i + 1) : null;
// Append human-readable condition string.
String conditionPart = current.makeReadableString(previous, next);
builder.append(conditionPart);
// If we don't have any more conditions after this one, just append a period and continue.
if (next == null) {
builder.append(".");
continue;
}
// Append a space if applicable.
if (isNoneOf(current, BEGIN_GROUP, NOT) && isNoneOf(next, END_GROUP))
builder.append(" ");
// Append "and " if applicable. | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/Condition.java
// public enum Type {
// NORMAL("NORMAL"), NO_ARGS("NO_ARGS"), BEGIN_GROUP("BEGIN_GROUP"), END_GROUP("END_GROUP"), OR("OR"), NOT("NOT");
//
// private final String name;
//
// Type(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Type getForName(String name) {
// switch (name) {
// case "NORMAL":
// return NORMAL;
// case "NO_ARGS":
// return NO_ARGS;
// case "BEGIN_GROUP":
// return BEGIN_GROUP;
// case "END_GROUP":
// return END_GROUP;
// case "OR":
// return OR;
// case "NOT":
// return NOT;
// default:
// throw new IllegalArgumentException("Invalid Condition type name.");
// }
// }
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isAnyOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return true;
// return false;
// }
//
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean isNoneOf(Condition condition, Condition.Type... types) {
// if (condition == null) return false;
// for (Condition.Type type : types) if (condition.getType() == type) return false;
// return true;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/RealmUserQuery.java
import android.os.Parcel;
import android.os.Parcelable;
import com.squareup.phrase.ListPhrase;
import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmResults;
import io.realm.Sort;
import java.util.ArrayList;
import java.util.regex.Pattern;
import static com.bkromhout.ruqus.Condition.Type.*;
import static com.bkromhout.ruqus.ReadableStringUtils.isAnyOf;
import static com.bkromhout.ruqus.ReadableStringUtils.isNoneOf;
if (!isQueryValid()) return null;
// Build up visible string. Start by stating the visible name of the type our results will be.
StringBuilder builder = new StringBuilder()
.append("Find all ")
.append(Ruqus.getClassData().visibleNameOf(queryClass));
// Next, loop through any conditions, appending their human-readable strings and applicable separators.
if (!conditions.isEmpty()) {
builder.append(" where ");
for (int i = 0; i < conditions.size(); i++) {
Condition previous = i - 1 >= 0 ? conditions.get(i - 1) : null;
Condition current = conditions.get(i);
Condition next = i + 1 < conditions.size() ? conditions.get(i + 1) : null;
// Append human-readable condition string.
String conditionPart = current.makeReadableString(previous, next);
builder.append(conditionPart);
// If we don't have any more conditions after this one, just append a period and continue.
if (next == null) {
builder.append(".");
continue;
}
// Append a space if applicable.
if (isNoneOf(current, BEGIN_GROUP, NOT) && isNoneOf(next, END_GROUP))
builder.append(" ");
// Append "and " if applicable. | if (isNoneOf(current, BEGIN_GROUP, NOT, OR) && isAnyOf(next, NORMAL, NO_ARGS, BEGIN_GROUP, NOT)) |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/GreaterThan.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code greaterThan()} methods.
*/
@Transformer(name = Names.GREATER_THAN, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class GreaterThan extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.greaterThan(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.greaterThan(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.greaterThan(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.greaterThan(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.greaterThan(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/GreaterThan.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code greaterThan()} methods.
*/
@Transformer(name = Names.GREATER_THAN, validArgTypes = {Date.class, Double.class, Float.class, Integer.class,
Long.class})
public class GreaterThan extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.greaterThan(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.greaterThan(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.greaterThan(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.greaterThan(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.greaterThan(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is greater than" : "is not greater than", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/LessThan.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code lessThan()} methods.
*/
@Transformer(name = Names.LESS_THAN, validArgTypes = {Date.class, Double.class, Float.class, Integer.class, Long.class})
public class LessThan extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType) return realmQuery.lessThan(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.lessThan(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.lessThan(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.lessThan(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.lessThan(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/LessThan.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code lessThan()} methods.
*/
@Transformer(name = Names.LESS_THAN, validArgTypes = {Date.class, Double.class, Float.class, Integer.class, Long.class})
public class LessThan extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType) return realmQuery.lessThan(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.lessThan(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.lessThan(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.lessThan(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.lessThan(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is less than" : "is not less than", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/GreaterThanOrEqualTo.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code greaterThanOrEqualTo()} methods.
*/
@Transformer(name = Names.GREATER_THAN_OR_EQUAL_TO, validArgTypes = {Date.class, Double.class, Float.class,
Integer.class, Long.class})
public class GreaterThanOrEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/GreaterThanOrEqualTo.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code greaterThanOrEqualTo()} methods.
*/
@Transformer(name = Names.GREATER_THAN_OR_EQUAL_TO, validArgTypes = {Date.class, Double.class, Float.class,
Integer.class, Long.class})
public class GreaterThanOrEqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.DATE == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType)
return realmQuery.greaterThanOrEqualTo(field, (Long) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s %s", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is greater than or equal to" : "is not greater than or equal to", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/EqualTo.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code equalTo()} methods.
*/
@Transformer(name = Names.EQUAL_TO, validArgTypes = {Boolean.class, Date.class, Double.class, Float.class,
Integer.class, Long.class, Short.class, String.class})
public class EqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.BOOLEAN == fieldType) return realmQuery.equalTo(field, (Boolean) args[0]);
else if (FieldType.DATE == fieldType) return realmQuery.equalTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.equalTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.equalTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.equalTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.equalTo(field, (Long) args[0]);
else if (FieldType.SHORT == fieldType) return realmQuery.equalTo(field, (Short) args[0]);
else if (FieldType.STRING == fieldType) return realmQuery.equalTo(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format(current.getFieldType() == FieldType.STRING ? "%s %s “%s”" : "%s %s %s",
ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/EqualTo.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import java.util.Date;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps the various {@link RealmQuery} {@code equalTo()} methods.
*/
@Transformer(name = Names.EQUAL_TO, validArgTypes = {Boolean.class, Date.class, Double.class, Float.class,
Integer.class, Long.class, Short.class, String.class})
public class EqualTo extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
// Use different methods based on field type.
if (FieldType.BOOLEAN == fieldType) return realmQuery.equalTo(field, (Boolean) args[0]);
else if (FieldType.DATE == fieldType) return realmQuery.equalTo(field, (Date) args[0]);
else if (FieldType.DOUBLE == fieldType) return realmQuery.equalTo(field, (Double) args[0]);
else if (FieldType.FLOAT == fieldType) return realmQuery.equalTo(field, (Float) args[0]);
else if (FieldType.INTEGER == fieldType) return realmQuery.equalTo(field, (Integer) args[0]);
else if (FieldType.LONG == fieldType) return realmQuery.equalTo(field, (Long) args[0]);
else if (FieldType.SHORT == fieldType) return realmQuery.equalTo(field, (Short) args[0]);
else if (FieldType.STRING == fieldType) return realmQuery.equalTo(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format(current.getFieldType() == FieldType.STRING ? "%s %s “%s”" : "%s %s %s",
ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "is" : "is not", |
bkromhout/Ruqus | ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/BeginsWith.java | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
| import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT; | package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#beginsWith(String, String)}.
*/
@Transformer(name = Names.BEGINS_WITH, validArgTypes = {String.class})
public class BeginsWith extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
if (FieldType.STRING == fieldType) return realmQuery.beginsWith(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | // Path: ruqus-core/src/main/java/com/bkromhout/ruqus/ReadableStringUtils.java
// public static boolean notNOT(Condition condition) {
// return condition == null || condition.getType() != Condition.Type.NOT;
// }
// Path: ruqus-core/src/main/java/com/bkromhout/ruqus/transformers/BeginsWith.java
import android.support.annotation.NonNull;
import com.bkromhout.ruqus.*;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import static com.bkromhout.ruqus.ReadableStringUtils.notNOT;
package com.bkromhout.ruqus.transformers;
/**
* Transformer which wraps {@link RealmQuery#beginsWith(String, String)}.
*/
@Transformer(name = Names.BEGINS_WITH, validArgTypes = {String.class})
public class BeginsWith extends RUQTransformer {
@Override
public <T extends RealmModel> RealmQuery<T> transform(RealmQuery<T> realmQuery, Condition condition) {
// Checks.
if (!condition.isValid()) throw new IllegalArgumentException("Condition isn't valid.");
if (condition.getType() != Condition.Type.NORMAL)
throw new IllegalArgumentException("Condition type is not NORMAL.");
// Get data from Conditions.
String field = condition.getField();
FieldType fieldType = condition.getFieldType();
Object[] args = condition.getArgs();
if (FieldType.STRING == fieldType) return realmQuery.beginsWith(field, (String) args[0]);
else
throw new IllegalArgumentException(String.format("Illegal argument type \"%s\".", fieldType.getTypeName()));
}
@Override
public String makeReadableString(@NonNull Condition current, Condition previous, Condition next) {
return String.format("%s %s “%s”", ReadableStringUtils.visibleFieldNameFrom(current), | notNOT(previous) ? "begins with" : "does not begin with", current.getArgs()[0]); |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
| import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement; | package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
| // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java
import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
| private final DatabaseContext databaseContext = new H2DatabaseContext(); |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
| import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement; | package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
private final DatabaseContext databaseContext = new H2DatabaseContext();
| // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java
import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
private final DatabaseContext databaseContext = new H2DatabaseContext();
| private final DropwizardAppRule<AuthriteServiceConfiguration> appRule = new DropwizardAppRule<>( |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
| import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement; | package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
private final DatabaseContext databaseContext = new H2DatabaseContext();
private final DropwizardAppRule<AuthriteServiceConfiguration> appRule = new DropwizardAppRule<>( | // Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceApplication.java
// public class AuthriteServiceApplication extends Application<AuthriteServiceConfiguration> {
//
// // Set to `false` for development, true elsewhere.
// // `false` will load assets from src/main/resources, allowing a fast edit-reload cycle.
// private final boolean useClasspathAssets = Boolean.parseBoolean(System.getProperty("authrite.assets.useClasspath", "true"));
//
// public static void main(final String[] args) throws Exception {
// new AuthriteServiceApplication().run(args);
// }
//
// @Override
// public String getName() {
// return "authrite-service";
// }
//
// @Override
// public void initialize(final Bootstrap<AuthriteServiceConfiguration> bootstrap) {
// bootstrap.addBundle(new Java8Bundle());
//
// if (useClasspathAssets) {
// bootstrap.addBundle(new AssetsBundle("/assets/", "/"));
// } else {
// bootstrap.addBundle(new FileAssetsBundle("src/main/resources/assets", "/"));
// }
//
// bootstrap.addBundle(new MigrationsBundle<AuthriteServiceConfiguration>() {
// @Override
// public DataSourceFactory getDataSourceFactory(final AuthriteServiceConfiguration configuration) {
// return configuration.getDatabase();
// }
// });
// }
//
// @Override
// public void run(final AuthriteServiceConfiguration configuration,
// final Environment environment) {
//
// final DBIFactory factory = new DBIFactory();
// final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2");
// final JWTConfiguration jwtConfiguration = configuration.getJwt();
// final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager();
// final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement();
// final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement);
// final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration);
// environment.jersey().register(usersResource);
//
// final PlayersResource playersResource = new PlayersResource(dbi);
// environment.jersey().register(playersResource);
//
// environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter()));
// environment.jersey().register(RolesAllowedDynamicFeature.class);
//
// //Required to use @Auth to inject a custom Principal type into your resource
// environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
// public class AuthriteServiceConfiguration extends Configuration {
//
// @Valid
// @NotNull
// private JWTConfiguration jwt = new JWTConfiguration();
//
// @Valid
// @NotNull
// private DataSourceFactory database = new DataSourceFactory();
//
// @Valid
// @NotNull
// private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration();
//
// @JsonProperty
// public JWTConfiguration getJwt() {
// return jwt;
// }
//
// @JsonProperty
// public void setJwt(final JWTConfiguration jwt) {
// this.jwt = jwt;
// }
//
// @JsonProperty
// public DataSourceFactory getDatabase() {
// return database;
// }
//
// @JsonProperty
// public void setDatabase(final DataSourceFactory database) {
// this.database = database;
// }
//
// @JsonProperty
// public PasswordManagementConfiguration getPasswordManagement() {
// return passwordManagement;
// }
//
// @JsonProperty
// public void setPasswordManagement(final PasswordManagementConfiguration passwordManagement) {
// this.passwordManagement = passwordManagement;
// }
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/database/H2DatabaseContext.java
// public class H2DatabaseContext extends DatabaseContext {
//
// @Override
// public String databaseUrl() {
// return "jdbc:h2:./target/" + databaseName();
// }
//
// @Override
// public TestRule rules() {
// // Don't chain because we don't need the TemporaryDatabaseRule for H2.
// return makeMigrationRule();
// }
//
// private MigrateDatabaseRule makeMigrationRule() {
// return new MigrateDatabaseRule(databaseUrl(), username(), password());
// }
//
// @Override
// protected String defaultPassword() {
// return "sa";
// }
//
// @Override
// protected String defaultUsername() {
// return "sa";
// }
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/SystemDriver.java
import com.lewisd.authrite.AuthriteServiceApplication;
import com.lewisd.authrite.AuthriteServiceConfiguration;
import com.lewisd.authrite.acctests.framework.database.H2DatabaseContext;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.junit.DropwizardAppRule;
import io.github.unacceptable.database.DatabaseContext;
import io.github.unacceptable.lazy.Lazily;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
package com.lewisd.authrite.acctests.framework.driver;
public class SystemDriver {
private static final ConfigOverride LOG_THRESHOLD = ConfigOverride.config("logging.level", System.getProperty("app.logging.threshold", "INFO"));
private static final String ACCTEST_BASEURI_PROPERTY = "acctest.baseuri";
private final DatabaseContext databaseContext = new H2DatabaseContext();
private final DropwizardAppRule<AuthriteServiceConfiguration> appRule = new DropwizardAppRule<>( | AuthriteServiceApplication.class, |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/TestContext.java | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java
// public class User {
//
// private UUID id;
// private String email;
// private String displayName;
// private Set<Roles> roles;
// private Date createdDate;
// private Date modifiedDate;
// private Date deletedDate;
// private Date lastLoginDate;
// private Date lastPasswordChangeDate;
// private Date emailValidatedDate;
//
// public User() {
// // for deserialization
// }
//
// public User(final UUID id, final String email, final String displayName, final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles;
// }
//
// public UUID getId() {
// return id;
// }
//
// public void setId(final UUID id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(final String displayName) {
// this.displayName = displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public void setRoles(final Set<Roles> roles) {
// this.roles = roles;
// }
//
// public Date getCreatedDate() {
// return createdDate;
// }
//
// public void setCreatedDate(final Date createdDate) {
// this.createdDate = createdDate;
// }
//
// public Date getModifiedDate() {
// return modifiedDate;
// }
//
// public void setModifiedDate(final Date modifiedDate) {
// this.modifiedDate = modifiedDate;
// }
//
// public Date getDeletedDate() {
// return deletedDate;
// }
//
// public void setDeletedDate(final Date deletedDate) {
// this.deletedDate = deletedDate;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public void setLastLoginDate(final Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// }
//
// public Date getLastPasswordChangeDate() {
// return lastPasswordChangeDate;
// }
//
// public void setLastPasswordChangeDate(final Date lastPasswordChangeDate) {
// this.lastPasswordChangeDate = lastPasswordChangeDate;
// }
//
// public Date getEmailValidatedDate() {
// return emailValidatedDate;
// }
//
// public void setEmailValidatedDate(final Date emailValidatedDate) {
// this.emailValidatedDate = emailValidatedDate;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
| import com.google.common.collect.Sets;
import com.lewisd.authrite.acctests.model.User;
import com.lewisd.authrite.auth.Roles;
import io.github.unacceptable.alias.AliasStore;
import io.github.unacceptable.alias.EmailAddressGenerator;
import io.github.unacceptable.alias.PasswordGenerator;
import io.github.unacceptable.alias.UsernameGenerator;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; | package com.lewisd.authrite.acctests.framework.context;
/**
* Shared state for the current test run. DSL classes can use their test context to convert aliases (used in test cases)
* into run-unique actual values, while reusing those values within a test run.
*
* @see Dsl
*/
//CHECKSTYLE.OFF: VisibilityModifier
public class TestContext {
public static final String ADMIN_EMAIL = "[email protected]";
public static final String ADMIN_DISPLAY_NAME = "Admin";
public final AliasStore<String> displayNames = new AliasStore<>(new UsernameGenerator(20)::generate);
public final AliasStore<String> emailAddresses = new AliasStore<>(EmailAddressGenerator::defaultGenerate);
public final AliasStore<String> passwords = new AliasStore<>(PasswordGenerator::defaultGenerate);
public final DateStore dates = new DateStore();
private final Map<String, UUID> userIdsByEmail = new HashMap<>();
private final Map<UUID, String> emailsByUserId = new HashMap<>();
public TestContext() {
emailAddresses.store(ADMIN_EMAIL, ADMIN_EMAIL);
displayNames.store(ADMIN_DISPLAY_NAME, ADMIN_DISPLAY_NAME); | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java
// public class User {
//
// private UUID id;
// private String email;
// private String displayName;
// private Set<Roles> roles;
// private Date createdDate;
// private Date modifiedDate;
// private Date deletedDate;
// private Date lastLoginDate;
// private Date lastPasswordChangeDate;
// private Date emailValidatedDate;
//
// public User() {
// // for deserialization
// }
//
// public User(final UUID id, final String email, final String displayName, final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles;
// }
//
// public UUID getId() {
// return id;
// }
//
// public void setId(final UUID id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(final String displayName) {
// this.displayName = displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public void setRoles(final Set<Roles> roles) {
// this.roles = roles;
// }
//
// public Date getCreatedDate() {
// return createdDate;
// }
//
// public void setCreatedDate(final Date createdDate) {
// this.createdDate = createdDate;
// }
//
// public Date getModifiedDate() {
// return modifiedDate;
// }
//
// public void setModifiedDate(final Date modifiedDate) {
// this.modifiedDate = modifiedDate;
// }
//
// public Date getDeletedDate() {
// return deletedDate;
// }
//
// public void setDeletedDate(final Date deletedDate) {
// this.deletedDate = deletedDate;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public void setLastLoginDate(final Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// }
//
// public Date getLastPasswordChangeDate() {
// return lastPasswordChangeDate;
// }
//
// public void setLastPasswordChangeDate(final Date lastPasswordChangeDate) {
// this.lastPasswordChangeDate = lastPasswordChangeDate;
// }
//
// public Date getEmailValidatedDate() {
// return emailValidatedDate;
// }
//
// public void setEmailValidatedDate(final Date emailValidatedDate) {
// this.emailValidatedDate = emailValidatedDate;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/TestContext.java
import com.google.common.collect.Sets;
import com.lewisd.authrite.acctests.model.User;
import com.lewisd.authrite.auth.Roles;
import io.github.unacceptable.alias.AliasStore;
import io.github.unacceptable.alias.EmailAddressGenerator;
import io.github.unacceptable.alias.PasswordGenerator;
import io.github.unacceptable.alias.UsernameGenerator;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
package com.lewisd.authrite.acctests.framework.context;
/**
* Shared state for the current test run. DSL classes can use their test context to convert aliases (used in test cases)
* into run-unique actual values, while reusing those values within a test run.
*
* @see Dsl
*/
//CHECKSTYLE.OFF: VisibilityModifier
public class TestContext {
public static final String ADMIN_EMAIL = "[email protected]";
public static final String ADMIN_DISPLAY_NAME = "Admin";
public final AliasStore<String> displayNames = new AliasStore<>(new UsernameGenerator(20)::generate);
public final AliasStore<String> emailAddresses = new AliasStore<>(EmailAddressGenerator::defaultGenerate);
public final AliasStore<String> passwords = new AliasStore<>(PasswordGenerator::defaultGenerate);
public final DateStore dates = new DateStore();
private final Map<String, UUID> userIdsByEmail = new HashMap<>();
private final Map<UUID, String> emailsByUserId = new HashMap<>();
public TestContext() {
emailAddresses.store(ADMIN_EMAIL, ADMIN_EMAIL);
displayNames.store(ADMIN_DISPLAY_NAME, ADMIN_DISPLAY_NAME); | addUser(new User(UUID.fromString("46c668be-e2d2-4452-96a9-a8a0452ac922"), |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/auth/DefaultUnauthorizedHandler.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/errors/APIError.java
// public class APIError {
// private final String[] errors;
//
// @JsonCreator
// public APIError(@JsonProperty("errors") final String... errors) {
// this.errors = clone(errors);
// }
//
// @JsonProperty
// public String[] getErrors() {
// return clone(errors);
// }
//
// private static String[] clone(final String[] array) {
// return Arrays.copyOf(array, array.length);
// }
//
// }
| import com.lewisd.authrite.errors.APIError;
import io.dropwizard.auth.UnauthorizedHandler;
import javax.ws.rs.core.Response; | package com.lewisd.authrite.auth;
public class DefaultUnauthorizedHandler implements UnauthorizedHandler {
@Override
public Response buildResponse(final String prefix, final String realm) {
return Response.status(Response.Status.UNAUTHORIZED) | // Path: authrite-service/src/main/java/com/lewisd/authrite/errors/APIError.java
// public class APIError {
// private final String[] errors;
//
// @JsonCreator
// public APIError(@JsonProperty("errors") final String... errors) {
// this.errors = clone(errors);
// }
//
// @JsonProperty
// public String[] getErrors() {
// return clone(errors);
// }
//
// private static String[] clone(final String[] array) {
// return Arrays.copyOf(array, array.length);
// }
//
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/DefaultUnauthorizedHandler.java
import com.lewisd.authrite.errors.APIError;
import io.dropwizard.auth.UnauthorizedHandler;
import javax.ws.rs.core.Response;
package com.lewisd.authrite.auth;
public class DefaultUnauthorizedHandler implements UnauthorizedHandler {
@Override
public Response buildResponse(final String prefix, final String realm) {
return Response.status(Response.Status.UNAUTHORIZED) | .entity(new APIError("Credentials are required to access this resource.")) |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.lewisd.authrite.resources.model.Player;
import com.lewisd.authrite.resources.model.User;
import java.util.UUID; | package com.lewisd.authrite.auth;
public enum Roles {
PLAYER {
@Override | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
import com.lewisd.authrite.resources.model.Player;
import com.lewisd.authrite.resources.model.User;
import java.util.UUID;
package com.lewisd.authrite.auth;
public enum Roles {
PLAYER {
@Override | protected boolean canReadUser(final User principal, final UUID userId) { |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.lewisd.authrite.resources.model.Player;
import com.lewisd.authrite.resources.model.User;
import java.util.UUID; | }
},
ADMIN {
@Override
protected boolean canReadUser(final User principal, final UUID userId) {
return true;
}
@Override
protected boolean canWriteUser(final User principal, final UUID userId) {
return true;
}
};
public String getName() {
return name();
}
public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
if (resourceClass == User.class) {
return canReadUser(principal, resourceId);
}
return false;
}
protected abstract boolean canReadUser(User principal, UUID userId);
public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
if (resourceClass == User.class) {
return canWriteUser(principal, resourceId); | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
import com.lewisd.authrite.resources.model.Player;
import com.lewisd.authrite.resources.model.User;
import java.util.UUID;
}
},
ADMIN {
@Override
protected boolean canReadUser(final User principal, final UUID userId) {
return true;
}
@Override
protected boolean canWriteUser(final User principal, final UUID userId) {
return true;
}
};
public String getName() {
return name();
}
public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
if (resourceClass == User.class) {
return canReadUser(principal, resourceId);
}
return false;
}
protected abstract boolean canReadUser(User principal, UUID userId);
public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
if (resourceClass == User.class) {
return canWriteUser(principal, resourceId); | } else if (resourceClass == Player.class) { |
lewisd32/authrite | authrite-acctests/src/test/java/com/lewisd/authrite/acctests/framework/time/TimeAssertionFactoryTest.java | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/DateStore.java
// public class DateStore extends AliasStore<Date> {
//
// public DateStore() {
// super(new DateGenerator()::generate);
// }
//
// @Override
// public Date resolve(final String alias) {
// if ("now".equals(alias)) {
// return new Date();
// }
// return super.resolve(alias);
// }
// }
| import com.lewisd.authrite.acctests.framework.context.DateStore;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat; | package com.lewisd.authrite.acctests.framework.time;
public class TimeAssertionFactoryTest {
private static final Date FIRST_DATE = new Date(499051260000L);
private static final Date SECOND_DATE = new Date(499137660000L); | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/DateStore.java
// public class DateStore extends AliasStore<Date> {
//
// public DateStore() {
// super(new DateGenerator()::generate);
// }
//
// @Override
// public Date resolve(final String alias) {
// if ("now".equals(alias)) {
// return new Date();
// }
// return super.resolve(alias);
// }
// }
// Path: authrite-acctests/src/test/java/com/lewisd/authrite/acctests/framework/time/TimeAssertionFactoryTest.java
import com.lewisd.authrite.acctests.framework.context.DateStore;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
package com.lewisd.authrite.acctests.framework.time;
public class TimeAssertionFactoryTest {
private static final Date FIRST_DATE = new Date(499051260000L);
private static final Date SECOND_DATE = new Date(499137660000L); | private final DateStore dates = new DateStore(); |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/time/TimeAssertionFactory.java | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/DateStore.java
// public class DateStore extends AliasStore<Date> {
//
// public DateStore() {
// super(new DateGenerator()::generate);
// }
//
// @Override
// public Date resolve(final String alias) {
// if ("now".equals(alias)) {
// return new Date();
// }
// return super.resolve(alias);
// }
// }
| import com.lewisd.authrite.acctests.framework.context.DateStore;
import java.util.Date;
import java.util.Deque; | package com.lewisd.authrite.acctests.framework.time;
public class TimeAssertionFactory {
private final String fieldName;
private final TimeParser timeParser;
| // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/DateStore.java
// public class DateStore extends AliasStore<Date> {
//
// public DateStore() {
// super(new DateGenerator()::generate);
// }
//
// @Override
// public Date resolve(final String alias) {
// if ("now".equals(alias)) {
// return new Date();
// }
// return super.resolve(alias);
// }
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/time/TimeAssertionFactory.java
import com.lewisd.authrite.acctests.framework.context.DateStore;
import java.util.Date;
import java.util.Deque;
package com.lewisd.authrite.acctests.framework.time;
public class TimeAssertionFactory {
private final String fieldName;
private final TimeParser timeParser;
| public TimeAssertionFactory(final DateStore dates, final String fieldName) { |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBPlayer.java
// public class DBPlayer {
// private UUID gameId;
// private UUID userId;
// private UUID raceId;
// private int slot;
// private boolean ready;
//
// public DBPlayer(final UUID gameId, final UUID userId, final UUID raceId, final int slot, final boolean ready) {
// this.gameId = gameId;
// this.userId = userId;
// this.raceId = raceId;
// this.slot = slot;
// this.ready = ready;
// }
//
// @JsonProperty
// public UUID getGameId() {
// return gameId;
// }
//
// @JsonProperty
// public void setGameId(final UUID gameId) {
// this.gameId = gameId;
// }
//
// @JsonProperty
// public UUID getUserId() {
// return userId;
// }
//
// @JsonProperty
// public void setUserId(final UUID userId) {
// this.userId = userId;
// }
//
// @JsonProperty
// public UUID getRaceId() {
// return raceId;
// }
//
// @JsonProperty
// public void setRaceId(final UUID raceId) {
// this.raceId = raceId;
// }
//
// @JsonProperty
// public int getSlot() {
// return slot;
// }
//
// @JsonProperty
// public void setSlot(final int slot) {
// this.slot = slot;
// }
//
// @JsonProperty
// public boolean isReady() {
// return ready;
// }
//
// @JsonProperty
// public void setReady(final boolean ready) {
// this.ready = ready;
// }
// }
| import com.lewisd.authrite.jdbc.model.DBPlayer;
import java.util.UUID; | package com.lewisd.authrite.resources.model;
public class Player {
private final UUID gameId;
public Player(final UUID gameId) {
this.gameId = gameId;
}
public UUID getGameId() {
return gameId;
}
| // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBPlayer.java
// public class DBPlayer {
// private UUID gameId;
// private UUID userId;
// private UUID raceId;
// private int slot;
// private boolean ready;
//
// public DBPlayer(final UUID gameId, final UUID userId, final UUID raceId, final int slot, final boolean ready) {
// this.gameId = gameId;
// this.userId = userId;
// this.raceId = raceId;
// this.slot = slot;
// this.ready = ready;
// }
//
// @JsonProperty
// public UUID getGameId() {
// return gameId;
// }
//
// @JsonProperty
// public void setGameId(final UUID gameId) {
// this.gameId = gameId;
// }
//
// @JsonProperty
// public UUID getUserId() {
// return userId;
// }
//
// @JsonProperty
// public void setUserId(final UUID userId) {
// this.userId = userId;
// }
//
// @JsonProperty
// public UUID getRaceId() {
// return raceId;
// }
//
// @JsonProperty
// public void setRaceId(final UUID raceId) {
// this.raceId = raceId;
// }
//
// @JsonProperty
// public int getSlot() {
// return slot;
// }
//
// @JsonProperty
// public void setSlot(final int slot) {
// this.slot = slot;
// }
//
// @JsonProperty
// public boolean isReady() {
// return ready;
// }
//
// @JsonProperty
// public void setReady(final boolean ready) {
// this.ready = ready;
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
import com.lewisd.authrite.jdbc.model.DBPlayer;
import java.util.UUID;
package com.lewisd.authrite.resources.model;
public class Player {
private final UUID gameId;
public Player(final UUID gameId) {
this.gameId = gameId;
}
public UUID getGameId() {
return gameId;
}
| public static Player fromDB(final DBPlayer player) { |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/PublicApiDriver.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java
// public class JwtTokenManager {
//
// private final JWTSigner jwtSigner;
// private final JWTSigner.Options jwtOptions;
// private final JWTVerifier jwtVerifier;
// private final ObjectMapper jsonMapper;
//
// public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
// jwtSigner = new JWTSigner(jwtSecret);
// jwtVerifier = new JWTVerifier(jwtSecret);
// jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
//
// jsonMapper = new ObjectMapper();
// jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// public JWTSigner getJwtSigner() {
// return jwtSigner;
// }
//
// public JWTSigner.Options getJwtOptions() {
// return jwtOptions;
// }
//
// public JWTVerifier getJwtVerifier() {
// return jwtVerifier;
// }
//
// @SuppressWarnings("unchecked")
// public Map<String, Object> toJWTClaim(final User user) {
// try {
// return jsonMapper.convertValue(user, Map.class);
// } catch (final IllegalArgumentException e) {
// throw new RuntimeException("Can't JSONify User, something's badly wrong", e);
// }
// }
//
// public User fromJWTClaim(final Map<String, Object> claim)
// throws IllegalArgumentException {
// final User user = jsonMapper.convertValue(claim, User.class);
// if (user.getId() == null) {
// throw new IllegalStateException("User from claim is missing id: " + claim);
// }
// if (user.getRoles() == null) {
// throw new IllegalStateException("User from claim is missing roles: " + claim);
// }
// if (user.getEmail() == null) {
// throw new IllegalStateException("User from claim is missing email: " + claim);
// }
// if (user.getDisplayName() == null) {
// throw new IllegalStateException("User from claim is missing displayName: " + claim);
// }
// return user;
// }
//
// }
| import com.auth0.jwt.JWTVerifyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Cookie;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.JwtTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static io.github.unacceptable.alias.AbsentWrappingGenerator.ABSENT;
import static org.junit.Assert.assertNotNull; | }
return response;
}
private RequestSpecification buildResponse() {
RequestSpecification requestSpecification = RestAssured.given()
.contentType(ContentType.JSON);
if (jwtToken != null) {
requestSpecification = requestSpecification.cookie("jwtToken", jwtToken);
}
return requestSpecification;
}
private String createJsonRequestBody(final Map<String, Object> requestBody) {
final String requestBodyJson;
try {
requestBodyJson = new ObjectMapper().writeValueAsString(requestBody);
} catch (final JsonProcessingException e) {
throw new RuntimeException("Unable to generate JSON request body", e);
}
return requestBodyJson;
}
public Cookie getJtwCookie() {
return jtwCookie;
}
public void regenerateToken(final String secret, final String userId, final String email, final String displayName, final String expiry) {
| // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java
// public class JwtTokenManager {
//
// private final JWTSigner jwtSigner;
// private final JWTSigner.Options jwtOptions;
// private final JWTVerifier jwtVerifier;
// private final ObjectMapper jsonMapper;
//
// public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
// jwtSigner = new JWTSigner(jwtSecret);
// jwtVerifier = new JWTVerifier(jwtSecret);
// jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
//
// jsonMapper = new ObjectMapper();
// jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// public JWTSigner getJwtSigner() {
// return jwtSigner;
// }
//
// public JWTSigner.Options getJwtOptions() {
// return jwtOptions;
// }
//
// public JWTVerifier getJwtVerifier() {
// return jwtVerifier;
// }
//
// @SuppressWarnings("unchecked")
// public Map<String, Object> toJWTClaim(final User user) {
// try {
// return jsonMapper.convertValue(user, Map.class);
// } catch (final IllegalArgumentException e) {
// throw new RuntimeException("Can't JSONify User, something's badly wrong", e);
// }
// }
//
// public User fromJWTClaim(final Map<String, Object> claim)
// throws IllegalArgumentException {
// final User user = jsonMapper.convertValue(claim, User.class);
// if (user.getId() == null) {
// throw new IllegalStateException("User from claim is missing id: " + claim);
// }
// if (user.getRoles() == null) {
// throw new IllegalStateException("User from claim is missing roles: " + claim);
// }
// if (user.getEmail() == null) {
// throw new IllegalStateException("User from claim is missing email: " + claim);
// }
// if (user.getDisplayName() == null) {
// throw new IllegalStateException("User from claim is missing displayName: " + claim);
// }
// return user;
// }
//
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/PublicApiDriver.java
import com.auth0.jwt.JWTVerifyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Cookie;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.JwtTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static io.github.unacceptable.alias.AbsentWrappingGenerator.ABSENT;
import static org.junit.Assert.assertNotNull;
}
return response;
}
private RequestSpecification buildResponse() {
RequestSpecification requestSpecification = RestAssured.given()
.contentType(ContentType.JSON);
if (jwtToken != null) {
requestSpecification = requestSpecification.cookie("jwtToken", jwtToken);
}
return requestSpecification;
}
private String createJsonRequestBody(final Map<String, Object> requestBody) {
final String requestBodyJson;
try {
requestBodyJson = new ObjectMapper().writeValueAsString(requestBody);
} catch (final JsonProcessingException e) {
throw new RuntimeException("Unable to generate JSON request body", e);
}
return requestBodyJson;
}
public Cookie getJtwCookie() {
return jtwCookie;
}
public void regenerateToken(final String secret, final String userId, final String email, final String displayName, final String expiry) {
| final JWTConfiguration verifyingConfiguration = new JWTConfiguration(); |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/PublicApiDriver.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java
// public class JwtTokenManager {
//
// private final JWTSigner jwtSigner;
// private final JWTSigner.Options jwtOptions;
// private final JWTVerifier jwtVerifier;
// private final ObjectMapper jsonMapper;
//
// public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
// jwtSigner = new JWTSigner(jwtSecret);
// jwtVerifier = new JWTVerifier(jwtSecret);
// jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
//
// jsonMapper = new ObjectMapper();
// jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// public JWTSigner getJwtSigner() {
// return jwtSigner;
// }
//
// public JWTSigner.Options getJwtOptions() {
// return jwtOptions;
// }
//
// public JWTVerifier getJwtVerifier() {
// return jwtVerifier;
// }
//
// @SuppressWarnings("unchecked")
// public Map<String, Object> toJWTClaim(final User user) {
// try {
// return jsonMapper.convertValue(user, Map.class);
// } catch (final IllegalArgumentException e) {
// throw new RuntimeException("Can't JSONify User, something's badly wrong", e);
// }
// }
//
// public User fromJWTClaim(final Map<String, Object> claim)
// throws IllegalArgumentException {
// final User user = jsonMapper.convertValue(claim, User.class);
// if (user.getId() == null) {
// throw new IllegalStateException("User from claim is missing id: " + claim);
// }
// if (user.getRoles() == null) {
// throw new IllegalStateException("User from claim is missing roles: " + claim);
// }
// if (user.getEmail() == null) {
// throw new IllegalStateException("User from claim is missing email: " + claim);
// }
// if (user.getDisplayName() == null) {
// throw new IllegalStateException("User from claim is missing displayName: " + claim);
// }
// return user;
// }
//
// }
| import com.auth0.jwt.JWTVerifyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Cookie;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.JwtTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static io.github.unacceptable.alias.AbsentWrappingGenerator.ABSENT;
import static org.junit.Assert.assertNotNull; |
return response;
}
private RequestSpecification buildResponse() {
RequestSpecification requestSpecification = RestAssured.given()
.contentType(ContentType.JSON);
if (jwtToken != null) {
requestSpecification = requestSpecification.cookie("jwtToken", jwtToken);
}
return requestSpecification;
}
private String createJsonRequestBody(final Map<String, Object> requestBody) {
final String requestBodyJson;
try {
requestBodyJson = new ObjectMapper().writeValueAsString(requestBody);
} catch (final JsonProcessingException e) {
throw new RuntimeException("Unable to generate JSON request body", e);
}
return requestBodyJson;
}
public Cookie getJtwCookie() {
return jtwCookie;
}
public void regenerateToken(final String secret, final String userId, final String email, final String displayName, final String expiry) {
final JWTConfiguration verifyingConfiguration = new JWTConfiguration(); | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java
// public class JwtTokenManager {
//
// private final JWTSigner jwtSigner;
// private final JWTSigner.Options jwtOptions;
// private final JWTVerifier jwtVerifier;
// private final ObjectMapper jsonMapper;
//
// public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
// jwtSigner = new JWTSigner(jwtSecret);
// jwtVerifier = new JWTVerifier(jwtSecret);
// jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
//
// jsonMapper = new ObjectMapper();
// jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// public JWTSigner getJwtSigner() {
// return jwtSigner;
// }
//
// public JWTSigner.Options getJwtOptions() {
// return jwtOptions;
// }
//
// public JWTVerifier getJwtVerifier() {
// return jwtVerifier;
// }
//
// @SuppressWarnings("unchecked")
// public Map<String, Object> toJWTClaim(final User user) {
// try {
// return jsonMapper.convertValue(user, Map.class);
// } catch (final IllegalArgumentException e) {
// throw new RuntimeException("Can't JSONify User, something's badly wrong", e);
// }
// }
//
// public User fromJWTClaim(final Map<String, Object> claim)
// throws IllegalArgumentException {
// final User user = jsonMapper.convertValue(claim, User.class);
// if (user.getId() == null) {
// throw new IllegalStateException("User from claim is missing id: " + claim);
// }
// if (user.getRoles() == null) {
// throw new IllegalStateException("User from claim is missing roles: " + claim);
// }
// if (user.getEmail() == null) {
// throw new IllegalStateException("User from claim is missing email: " + claim);
// }
// if (user.getDisplayName() == null) {
// throw new IllegalStateException("User from claim is missing displayName: " + claim);
// }
// return user;
// }
//
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/PublicApiDriver.java
import com.auth0.jwt.JWTVerifyException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Cookie;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.JwtTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static io.github.unacceptable.alias.AbsentWrappingGenerator.ABSENT;
import static org.junit.Assert.assertNotNull;
return response;
}
private RequestSpecification buildResponse() {
RequestSpecification requestSpecification = RestAssured.given()
.contentType(ContentType.JSON);
if (jwtToken != null) {
requestSpecification = requestSpecification.cookie("jwtToken", jwtToken);
}
return requestSpecification;
}
private String createJsonRequestBody(final Map<String, Object> requestBody) {
final String requestBodyJson;
try {
requestBodyJson = new ObjectMapper().writeValueAsString(requestBody);
} catch (final JsonProcessingException e) {
throw new RuntimeException("Unable to generate JSON request body", e);
}
return requestBodyJson;
}
public Cookie getJtwCookie() {
return jtwCookie;
}
public void regenerateToken(final String secret, final String userId, final String email, final String displayName, final String expiry) {
final JWTConfiguration verifyingConfiguration = new JWTConfiguration(); | final JwtTokenManager tokenManager = verifyingConfiguration.buildTokenManager(); |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.resources.model.User; | package com.lewisd.authrite.auth;
public class JWTConfiguration {
private String jwtSecret = "secret";
private int jwtExpirySeconds = 3600;
private String cookieName = "jwtToken";
@JsonProperty
public String getJwtSecret() {
return jwtSecret;
}
public void setJwtSecret(final String jwtSecret) {
this.jwtSecret = jwtSecret;
}
@JsonProperty
public int getJwtExpirySeconds() {
return jwtExpirySeconds;
}
public void setJwtExpirySeconds(final int jwtExpirySeconds) {
this.jwtExpirySeconds = jwtExpirySeconds;
}
@JsonProperty
public String getCookieName() {
return cookieName;
}
public void setCookieName(final String cookieName) {
this.cookieName = cookieName;
}
| // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.resources.model.User;
package com.lewisd.authrite.auth;
public class JWTConfiguration {
private String jwtSecret = "secret";
private int jwtExpirySeconds = 3600;
private String cookieName = "jwtToken";
@JsonProperty
public String getJwtSecret() {
return jwtSecret;
}
public void setJwtSecret(final String jwtSecret) {
this.jwtSecret = jwtSecret;
}
@JsonProperty
public int getJwtExpirySeconds() {
return jwtExpirySeconds;
}
public void setJwtExpirySeconds(final int jwtExpirySeconds) {
this.jwtExpirySeconds = jwtExpirySeconds;
}
@JsonProperty
public String getCookieName() {
return cookieName;
}
public void setCookieName(final String cookieName) {
this.cookieName = cookieName;
}
| public JWTAuthFilter<User> buildAuthFilter() { |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lewisd.authrite.resources.model.User;
import java.util.Map; | package com.lewisd.authrite.auth;
public class JwtTokenManager {
private final JWTSigner jwtSigner;
private final JWTSigner.Options jwtOptions;
private final JWTVerifier jwtVerifier;
private final ObjectMapper jsonMapper;
public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
jwtSigner = new JWTSigner(jwtSecret);
jwtVerifier = new JWTVerifier(jwtSecret);
jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
jsonMapper = new ObjectMapper();
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public JWTSigner getJwtSigner() {
return jwtSigner;
}
public JWTSigner.Options getJwtOptions() {
return jwtOptions;
}
public JWTVerifier getJwtVerifier() {
return jwtVerifier;
}
@SuppressWarnings("unchecked") | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JwtTokenManager.java
import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lewisd.authrite.resources.model.User;
import java.util.Map;
package com.lewisd.authrite.auth;
public class JwtTokenManager {
private final JWTSigner jwtSigner;
private final JWTSigner.Options jwtOptions;
private final JWTVerifier jwtVerifier;
private final ObjectMapper jsonMapper;
public JwtTokenManager(final String jwtSecret, final int jwtExpirySeconds) {
jwtSigner = new JWTSigner(jwtSecret);
jwtVerifier = new JWTVerifier(jwtSecret);
jwtOptions = new JWTSigner.Options().setExpirySeconds(jwtExpirySeconds);
jsonMapper = new ObjectMapper();
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public JWTSigner getJwtSigner() {
return jwtSigner;
}
public JWTSigner.Options getJwtOptions() {
return jwtOptions;
}
public JWTVerifier getJwtVerifier() {
return jwtVerifier;
}
@SuppressWarnings("unchecked") | public Map<String, Object> toJWTClaim(final User user) { |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/requests/PasswordChangeRequest.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty; | package com.lewisd.authrite.resources.requests;
public class PasswordChangeRequest {
@NotEmpty
private final String oldPassword;
@NotEmpty | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/requests/PasswordChangeRequest.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
package com.lewisd.authrite.resources.requests;
public class PasswordChangeRequest {
@NotEmpty
private final String oldPassword;
@NotEmpty | @Length(min = PasswordManagementConfiguration.MIN_LENGTH, max = PasswordManagementConfiguration.MAX_LENGTH) |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBUser.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordDigest.java
// public final class PasswordDigest {
// private final String digest;
//
// private PasswordDigest(final String digest) {
// this.digest = digest;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public boolean checkPassword(final String passwordToCheck) {
// return BCrypt.checkpw(passwordToCheck, digest);
// }
//
// public static PasswordDigest fromDigest(final String digest) {
// return new PasswordDigest(digest);
// }
//
// public static PasswordDigest generateFromPassword(final int bcryptCost, final String password) {
// final String salt = BCrypt.gensalt(bcryptCost);
// return PasswordDigest.fromDigest(BCrypt.hashpw(password, salt));
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
| import com.lewisd.authrite.auth.PasswordDigest;
import com.lewisd.authrite.auth.Roles;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID; | package com.lewisd.authrite.jdbc.model;
public class DBUser {
private UUID id;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private Date lastLoginDate;
private Date lastPasswordChangeDate;
private Date emailValidatedDate;
private String email;
private String displayName; | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordDigest.java
// public final class PasswordDigest {
// private final String digest;
//
// private PasswordDigest(final String digest) {
// this.digest = digest;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public boolean checkPassword(final String passwordToCheck) {
// return BCrypt.checkpw(passwordToCheck, digest);
// }
//
// public static PasswordDigest fromDigest(final String digest) {
// return new PasswordDigest(digest);
// }
//
// public static PasswordDigest generateFromPassword(final int bcryptCost, final String password) {
// final String salt = BCrypt.gensalt(bcryptCost);
// return PasswordDigest.fromDigest(BCrypt.hashpw(password, salt));
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBUser.java
import com.lewisd.authrite.auth.PasswordDigest;
import com.lewisd.authrite.auth.Roles;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
package com.lewisd.authrite.jdbc.model;
public class DBUser {
private UUID id;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private Date lastLoginDate;
private Date lastPasswordChangeDate;
private Date emailValidatedDate;
private String email;
private String displayName; | private PasswordDigest passwordDigest; |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBUser.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordDigest.java
// public final class PasswordDigest {
// private final String digest;
//
// private PasswordDigest(final String digest) {
// this.digest = digest;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public boolean checkPassword(final String passwordToCheck) {
// return BCrypt.checkpw(passwordToCheck, digest);
// }
//
// public static PasswordDigest fromDigest(final String digest) {
// return new PasswordDigest(digest);
// }
//
// public static PasswordDigest generateFromPassword(final int bcryptCost, final String password) {
// final String salt = BCrypt.gensalt(bcryptCost);
// return PasswordDigest.fromDigest(BCrypt.hashpw(password, salt));
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
| import com.lewisd.authrite.auth.PasswordDigest;
import com.lewisd.authrite.auth.Roles;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID; | package com.lewisd.authrite.jdbc.model;
public class DBUser {
private UUID id;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private Date lastLoginDate;
private Date lastPasswordChangeDate;
private Date emailValidatedDate;
private String email;
private String displayName;
private PasswordDigest passwordDigest; | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordDigest.java
// public final class PasswordDigest {
// private final String digest;
//
// private PasswordDigest(final String digest) {
// this.digest = digest;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public boolean checkPassword(final String passwordToCheck) {
// return BCrypt.checkpw(passwordToCheck, digest);
// }
//
// public static PasswordDigest fromDigest(final String digest) {
// return new PasswordDigest(digest);
// }
//
// public static PasswordDigest generateFromPassword(final int bcryptCost, final String password) {
// final String salt = BCrypt.gensalt(bcryptCost);
// return PasswordDigest.fromDigest(BCrypt.hashpw(password, salt));
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBUser.java
import com.lewisd.authrite.auth.PasswordDigest;
import com.lewisd.authrite.auth.Roles;
import javax.annotation.Nullable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
package com.lewisd.authrite.jdbc.model;
public class DBUser {
private UUID id;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private Date lastLoginDate;
private Date lastPasswordChangeDate;
private Date emailValidatedDate;
private String email;
private String displayName;
private PasswordDigest passwordDigest; | private Set<Roles> roles; |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/DslTools.java | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/TestContext.java
// public class TestContext {
// public static final String ADMIN_EMAIL = "[email protected]";
// public static final String ADMIN_DISPLAY_NAME = "Admin";
// public final AliasStore<String> displayNames = new AliasStore<>(new UsernameGenerator(20)::generate);
// public final AliasStore<String> emailAddresses = new AliasStore<>(EmailAddressGenerator::defaultGenerate);
// public final AliasStore<String> passwords = new AliasStore<>(PasswordGenerator::defaultGenerate);
// public final DateStore dates = new DateStore();
//
// private final Map<String, UUID> userIdsByEmail = new HashMap<>();
// private final Map<UUID, String> emailsByUserId = new HashMap<>();
//
// public TestContext() {
// emailAddresses.store(ADMIN_EMAIL, ADMIN_EMAIL);
// displayNames.store(ADMIN_DISPLAY_NAME, ADMIN_DISPLAY_NAME);
// addUser(new User(UUID.fromString("46c668be-e2d2-4452-96a9-a8a0452ac922"),
// ADMIN_EMAIL,
// ADMIN_DISPLAY_NAME,
// Sets.newHashSet(Roles.PLAYER, Roles.ADMIN)
// ));
// }
//
// public void addUser(final User user) {
// userIdsByEmail.put(user.getEmail(), user.getId());
// emailsByUserId.put(user.getId(), user.getEmail());
// }
//
// public UUID getUserId(final String email) {
// return userIdsByEmail.get(email);
// }
//
// public String getUserEmail(final UUID id) {
// return emailsByUserId.get(id);
// }
//
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java
// public class User {
//
// private UUID id;
// private String email;
// private String displayName;
// private Set<Roles> roles;
// private Date createdDate;
// private Date modifiedDate;
// private Date deletedDate;
// private Date lastLoginDate;
// private Date lastPasswordChangeDate;
// private Date emailValidatedDate;
//
// public User() {
// // for deserialization
// }
//
// public User(final UUID id, final String email, final String displayName, final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles;
// }
//
// public UUID getId() {
// return id;
// }
//
// public void setId(final UUID id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(final String displayName) {
// this.displayName = displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public void setRoles(final Set<Roles> roles) {
// this.roles = roles;
// }
//
// public Date getCreatedDate() {
// return createdDate;
// }
//
// public void setCreatedDate(final Date createdDate) {
// this.createdDate = createdDate;
// }
//
// public Date getModifiedDate() {
// return modifiedDate;
// }
//
// public void setModifiedDate(final Date modifiedDate) {
// this.modifiedDate = modifiedDate;
// }
//
// public Date getDeletedDate() {
// return deletedDate;
// }
//
// public void setDeletedDate(final Date deletedDate) {
// this.deletedDate = deletedDate;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public void setLastLoginDate(final Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// }
//
// public Date getLastPasswordChangeDate() {
// return lastPasswordChangeDate;
// }
//
// public void setLastPasswordChangeDate(final Date lastPasswordChangeDate) {
// this.lastPasswordChangeDate = lastPasswordChangeDate;
// }
//
// public Date getEmailValidatedDate() {
// return emailValidatedDate;
// }
//
// public void setEmailValidatedDate(final Date emailValidatedDate) {
// this.emailValidatedDate = emailValidatedDate;
// }
// }
| import com.lewisd.authrite.acctests.framework.context.TestContext;
import com.lewisd.authrite.acctests.model.User;
import java.util.UUID; | package com.lewisd.authrite.acctests.framework.driver;
public class DslTools {
private final TestContext testContext;
public DslTools(final TestContext testContext) {
this.testContext = testContext;
}
public void generateFakeUserId(final String alias) {
final String email = testContext.emailAddresses.resolve(alias);
final UUID userId = UUID.randomUUID(); | // Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/context/TestContext.java
// public class TestContext {
// public static final String ADMIN_EMAIL = "[email protected]";
// public static final String ADMIN_DISPLAY_NAME = "Admin";
// public final AliasStore<String> displayNames = new AliasStore<>(new UsernameGenerator(20)::generate);
// public final AliasStore<String> emailAddresses = new AliasStore<>(EmailAddressGenerator::defaultGenerate);
// public final AliasStore<String> passwords = new AliasStore<>(PasswordGenerator::defaultGenerate);
// public final DateStore dates = new DateStore();
//
// private final Map<String, UUID> userIdsByEmail = new HashMap<>();
// private final Map<UUID, String> emailsByUserId = new HashMap<>();
//
// public TestContext() {
// emailAddresses.store(ADMIN_EMAIL, ADMIN_EMAIL);
// displayNames.store(ADMIN_DISPLAY_NAME, ADMIN_DISPLAY_NAME);
// addUser(new User(UUID.fromString("46c668be-e2d2-4452-96a9-a8a0452ac922"),
// ADMIN_EMAIL,
// ADMIN_DISPLAY_NAME,
// Sets.newHashSet(Roles.PLAYER, Roles.ADMIN)
// ));
// }
//
// public void addUser(final User user) {
// userIdsByEmail.put(user.getEmail(), user.getId());
// emailsByUserId.put(user.getId(), user.getEmail());
// }
//
// public UUID getUserId(final String email) {
// return userIdsByEmail.get(email);
// }
//
// public String getUserEmail(final UUID id) {
// return emailsByUserId.get(id);
// }
//
// }
//
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java
// public class User {
//
// private UUID id;
// private String email;
// private String displayName;
// private Set<Roles> roles;
// private Date createdDate;
// private Date modifiedDate;
// private Date deletedDate;
// private Date lastLoginDate;
// private Date lastPasswordChangeDate;
// private Date emailValidatedDate;
//
// public User() {
// // for deserialization
// }
//
// public User(final UUID id, final String email, final String displayName, final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles;
// }
//
// public UUID getId() {
// return id;
// }
//
// public void setId(final UUID id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(final String displayName) {
// this.displayName = displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public void setRoles(final Set<Roles> roles) {
// this.roles = roles;
// }
//
// public Date getCreatedDate() {
// return createdDate;
// }
//
// public void setCreatedDate(final Date createdDate) {
// this.createdDate = createdDate;
// }
//
// public Date getModifiedDate() {
// return modifiedDate;
// }
//
// public void setModifiedDate(final Date modifiedDate) {
// this.modifiedDate = modifiedDate;
// }
//
// public Date getDeletedDate() {
// return deletedDate;
// }
//
// public void setDeletedDate(final Date deletedDate) {
// this.deletedDate = deletedDate;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public void setLastLoginDate(final Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// }
//
// public Date getLastPasswordChangeDate() {
// return lastPasswordChangeDate;
// }
//
// public void setLastPasswordChangeDate(final Date lastPasswordChangeDate) {
// this.lastPasswordChangeDate = lastPasswordChangeDate;
// }
//
// public Date getEmailValidatedDate() {
// return emailValidatedDate;
// }
//
// public void setEmailValidatedDate(final Date emailValidatedDate) {
// this.emailValidatedDate = emailValidatedDate;
// }
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/framework/driver/DslTools.java
import com.lewisd.authrite.acctests.framework.context.TestContext;
import com.lewisd.authrite.acctests.model.User;
import java.util.UUID;
package com.lewisd.authrite.acctests.framework.driver;
public class DslTools {
private final TestContext testContext;
public DslTools(final TestContext testContext) {
this.testContext = testContext;
}
public void generateFakeUserId(final String alias) {
final String email = testContext.emailAddresses.resolve(alias);
final UUID userId = UUID.randomUUID(); | final User user = new User(); |
lewisd32/authrite | authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
| import com.lewisd.authrite.auth.Roles;
import java.util.Date;
import java.util.Set;
import java.util.UUID; | package com.lewisd.authrite.acctests.model;
public class User {
private UUID id;
private String email;
private String displayName; | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/Roles.java
// public enum Roles {
// PLAYER {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// RO_ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return userId.equals(principal.getId());
// }
// },
// ADMIN {
// @Override
// protected boolean canReadUser(final User principal, final UUID userId) {
// return true;
// }
//
// @Override
// protected boolean canWriteUser(final User principal, final UUID userId) {
// return true;
// }
// };
//
// public String getName() {
// return name();
// }
//
// public boolean canRead(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canReadUser(principal, resourceId);
// }
// return false;
// }
//
// protected abstract boolean canReadUser(User principal, UUID userId);
//
// public boolean canWrite(final Class<?> resourceClass, final User principal, final UUID resourceId) {
// if (resourceClass == User.class) {
// return canWriteUser(principal, resourceId);
// } else if (resourceClass == Player.class) {
// // TODO: Implement this
// return false;
// }
// return false;
// }
//
// protected abstract boolean canWriteUser(User principal, UUID userId);
// }
// Path: authrite-acctests/src/main/java/com/lewisd/authrite/acctests/model/User.java
import com.lewisd.authrite.auth.Roles;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
package com.lewisd.authrite.acctests.model;
public class User {
private UUID id;
private String email;
private String displayName; | private Set<Roles> roles; |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/requests/CreateUserRequest.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import com.lewisd.authrite.resources.model.User;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid; | package com.lewisd.authrite.resources.requests;
public class CreateUserRequest {
@Valid | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/requests/CreateUserRequest.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import com.lewisd.authrite.resources.model.User;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
package com.lewisd.authrite.resources.requests;
public class CreateUserRequest {
@Valid | private final User user; |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/requests/CreateUserRequest.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import com.lewisd.authrite.resources.model.User;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid; | package com.lewisd.authrite.resources.requests;
public class CreateUserRequest {
@Valid
private final User user;
@NotEmpty | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/requests/CreateUserRequest.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import com.lewisd.authrite.resources.model.User;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
package com.lewisd.authrite.resources.requests;
public class CreateUserRequest {
@Valid
private final User user;
@NotEmpty | @Length(min = PasswordManagementConfiguration.MIN_LENGTH, max = PasswordManagementConfiguration.MAX_LENGTH) |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/requests/UpdateUserRequest.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.resources.model.User;
import javax.validation.Valid; | package com.lewisd.authrite.resources.requests;
public class UpdateUserRequest {
@Valid | // Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/User.java
// public class User implements Principal {
//
// private final UUID id;
// @NotEmpty
// @Email(regexp = ".+@.+\\..+")
// private final String email;
// @NotEmpty
// @Length(min = 3, max = 20)
// private final String displayName;
//
// private final Set<Roles> roles;
//
// @JsonCreator
// public User(@JsonProperty("id") final UUID id,
// @JsonProperty("email") final String email,
// @JsonProperty("displayName") final String displayName,
// @JsonProperty("roles") final Set<Roles> roles) {
// this.id = id;
// this.email = email;
// this.displayName = displayName;
// this.roles = roles == null ? Collections.emptySet() : new HashSet<>(roles);
// }
//
// public UUID getId() {
// return id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Set<Roles> getRoles() {
// return roles;
// }
//
// public static User fromDB(final DBUser user) {
// return new User(
// user.getId(),
// user.getEmail(),
// user.getDisplayName(),
// user.getRoles());
// }
//
// @JsonIgnore
// @Override
// public String getName() {
// return email;
// }
//
// @Override
// public boolean implies(final Subject subject) {
// return false;
// }
//
// public boolean canRead(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canRead(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// public boolean canModify(final Class<?> resourceClass, final UUID userId) {
// for (Roles role : roles) {
// if (role.canWrite(resourceClass, this, userId)) {
// return true;
// }
// }
// return false;
// }
//
// @JsonIgnore
// public boolean isAdminForReading() {
// return roles.contains(Roles.ADMIN) || roles.contains(Roles.RO_ADMIN);
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/requests/UpdateUserRequest.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.resources.model.User;
import javax.validation.Valid;
package com.lewisd.authrite.resources.requests;
public class UpdateUserRequest {
@Valid | private final User user; |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBPlayer.java
// public class DBPlayer {
// private UUID gameId;
// private UUID userId;
// private UUID raceId;
// private int slot;
// private boolean ready;
//
// public DBPlayer(final UUID gameId, final UUID userId, final UUID raceId, final int slot, final boolean ready) {
// this.gameId = gameId;
// this.userId = userId;
// this.raceId = raceId;
// this.slot = slot;
// this.ready = ready;
// }
//
// @JsonProperty
// public UUID getGameId() {
// return gameId;
// }
//
// @JsonProperty
// public void setGameId(final UUID gameId) {
// this.gameId = gameId;
// }
//
// @JsonProperty
// public UUID getUserId() {
// return userId;
// }
//
// @JsonProperty
// public void setUserId(final UUID userId) {
// this.userId = userId;
// }
//
// @JsonProperty
// public UUID getRaceId() {
// return raceId;
// }
//
// @JsonProperty
// public void setRaceId(final UUID raceId) {
// this.raceId = raceId;
// }
//
// @JsonProperty
// public int getSlot() {
// return slot;
// }
//
// @JsonProperty
// public void setSlot(final int slot) {
// this.slot = slot;
// }
//
// @JsonProperty
// public boolean isReady() {
// return ready;
// }
//
// @JsonProperty
// public void setReady(final boolean ready) {
// this.ready = ready;
// }
// }
| import com.google.common.collect.ImmutableList;
import com.lewisd.authrite.jdbc.model.DBPlayer;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import java.util.UUID; | package com.lewisd.authrite.jdbc.dao;
@RegisterMapper(DBPlayerMapper.class)
public interface PlayerDao {
@SqlQuery("select * from players where gameId=:gameId") | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/model/DBPlayer.java
// public class DBPlayer {
// private UUID gameId;
// private UUID userId;
// private UUID raceId;
// private int slot;
// private boolean ready;
//
// public DBPlayer(final UUID gameId, final UUID userId, final UUID raceId, final int slot, final boolean ready) {
// this.gameId = gameId;
// this.userId = userId;
// this.raceId = raceId;
// this.slot = slot;
// this.ready = ready;
// }
//
// @JsonProperty
// public UUID getGameId() {
// return gameId;
// }
//
// @JsonProperty
// public void setGameId(final UUID gameId) {
// this.gameId = gameId;
// }
//
// @JsonProperty
// public UUID getUserId() {
// return userId;
// }
//
// @JsonProperty
// public void setUserId(final UUID userId) {
// this.userId = userId;
// }
//
// @JsonProperty
// public UUID getRaceId() {
// return raceId;
// }
//
// @JsonProperty
// public void setRaceId(final UUID raceId) {
// this.raceId = raceId;
// }
//
// @JsonProperty
// public int getSlot() {
// return slot;
// }
//
// @JsonProperty
// public void setSlot(final int slot) {
// this.slot = slot;
// }
//
// @JsonProperty
// public boolean isReady() {
// return ready;
// }
//
// @JsonProperty
// public void setReady(final boolean ready) {
// this.ready = ready;
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java
import com.google.common.collect.ImmutableList;
import com.lewisd.authrite.jdbc.model.DBPlayer;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import java.util.UUID;
package com.lewisd.authrite.jdbc.dao;
@RegisterMapper(DBPlayerMapper.class)
public interface PlayerDao {
@SqlQuery("select * from players where gameId=:gameId") | ImmutableList<DBPlayer> getPlayersForGame(@Bind("gameId") UUID gameId); |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/PlayersResource.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java
// @RegisterMapper(DBPlayerMapper.class)
// public interface PlayerDao {
//
// @SqlQuery("select * from players where gameId=:gameId")
// ImmutableList<DBPlayer> getPlayersForGame(@Bind("gameId") UUID gameId);
//
// @SqlQuery("select * from players where userId=:userId")
// ImmutableList<DBPlayer> getPlayersForUser(@Bind("userId") UUID userId);
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
| import com.lewisd.authrite.jdbc.dao.PlayerDao;
import com.lewisd.authrite.resources.model.Player;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;
import static java.util.stream.Collectors.toList; | package com.lewisd.authrite.resources;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class PlayersResource {
private final DBI dbi;
@Inject
public PlayersResource(final DBI dbi) {
this.dbi = dbi;
}
@Path("/games/{gameId}/players")
@GET | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java
// @RegisterMapper(DBPlayerMapper.class)
// public interface PlayerDao {
//
// @SqlQuery("select * from players where gameId=:gameId")
// ImmutableList<DBPlayer> getPlayersForGame(@Bind("gameId") UUID gameId);
//
// @SqlQuery("select * from players where userId=:userId")
// ImmutableList<DBPlayer> getPlayersForUser(@Bind("userId") UUID userId);
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/PlayersResource.java
import com.lewisd.authrite.jdbc.dao.PlayerDao;
import com.lewisd.authrite.resources.model.Player;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;
import static java.util.stream.Collectors.toList;
package com.lewisd.authrite.resources;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class PlayersResource {
private final DBI dbi;
@Inject
public PlayersResource(final DBI dbi) {
this.dbi = dbi;
}
@Path("/games/{gameId}/players")
@GET | public List<Player> listPlayersInGame(@PathParam("gameId") final UUID gameId) { |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/resources/PlayersResource.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java
// @RegisterMapper(DBPlayerMapper.class)
// public interface PlayerDao {
//
// @SqlQuery("select * from players where gameId=:gameId")
// ImmutableList<DBPlayer> getPlayersForGame(@Bind("gameId") UUID gameId);
//
// @SqlQuery("select * from players where userId=:userId")
// ImmutableList<DBPlayer> getPlayersForUser(@Bind("userId") UUID userId);
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
| import com.lewisd.authrite.jdbc.dao.PlayerDao;
import com.lewisd.authrite.resources.model.Player;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;
import static java.util.stream.Collectors.toList; | package com.lewisd.authrite.resources;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class PlayersResource {
private final DBI dbi;
@Inject
public PlayersResource(final DBI dbi) {
this.dbi = dbi;
}
@Path("/games/{gameId}/players")
@GET
public List<Player> listPlayersInGame(@PathParam("gameId") final UUID gameId) {
try (final Handle handle = dbi.open()) { | // Path: authrite-service/src/main/java/com/lewisd/authrite/jdbc/dao/PlayerDao.java
// @RegisterMapper(DBPlayerMapper.class)
// public interface PlayerDao {
//
// @SqlQuery("select * from players where gameId=:gameId")
// ImmutableList<DBPlayer> getPlayersForGame(@Bind("gameId") UUID gameId);
//
// @SqlQuery("select * from players where userId=:userId")
// ImmutableList<DBPlayer> getPlayersForUser(@Bind("userId") UUID userId);
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/model/Player.java
// public class Player {
// private final UUID gameId;
//
// public Player(final UUID gameId) {
//
// this.gameId = gameId;
// }
//
// public UUID getGameId() {
// return gameId;
// }
//
// public static Player fromDB(final DBPlayer player) {
// return new Player(
// player.getGameId()
// );
// }
//
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/resources/PlayersResource.java
import com.lewisd.authrite.jdbc.dao.PlayerDao;
import com.lewisd.authrite.resources.model.Player;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.UUID;
import static java.util.stream.Collectors.toList;
package com.lewisd.authrite.resources;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class PlayersResource {
private final DBI dbi;
@Inject
public PlayersResource(final DBI dbi) {
this.dbi = dbi;
}
@Path("/games/{gameId}/players")
@GET
public List<Player> listPlayersInGame(@PathParam("gameId") final UUID gameId) {
try (final Handle handle = dbi.open()) { | final PlayerDao playerDao = handle.attach(PlayerDao.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.