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
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/service/TeamServiceImpl.java
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String name; // // public static TeamDto map(Team team) { // return TeamDto.builder() // .id(team.getId()) // .name(team.getName()) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamEditRequest { // @NotEmpty // private String name; // } // // Path: spat-services/src/main/java/com/pcalouche/spat/entity/Team.java // @Entity // @Table(name = "teams") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Team { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Team)) { // return false; // } // Team castedObj = (Team) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/TeamRepository.java // @Repository // public interface TeamRepository extends JpaRepository<Team, Integer> { // Optional<Team> findByName(String name); // }
import com.pcalouche.spat.api.dto.TeamDto; import com.pcalouche.spat.api.dto.TeamEditRequest; import com.pcalouche.spat.entity.Team; import com.pcalouche.spat.repository.TeamRepository; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
package com.pcalouche.spat.service; @Service public class TeamServiceImpl implements TeamService { private final TeamRepository teamRepository; public TeamServiceImpl(TeamRepository teamRepository) { this.teamRepository = teamRepository; } @Override @Transactional(readOnly = true) public Optional<TeamDto> findById(Integer id) { return teamRepository.findById(id) .map(TeamDto::map); } @Override public Optional<TeamDto> findByName(String name) { return teamRepository.findByName(name) .map(TeamDto::map); } @Override @Transactional(readOnly = true) public List<TeamDto> findAll() { return teamRepository.findAll(Sort.by("name")).stream() .map(TeamDto::map) .collect(Collectors.toList()); } @Override @Transactional public TeamDto create(TeamEditRequest teamEditRequest) {
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String name; // // public static TeamDto map(Team team) { // return TeamDto.builder() // .id(team.getId()) // .name(team.getName()) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamEditRequest { // @NotEmpty // private String name; // } // // Path: spat-services/src/main/java/com/pcalouche/spat/entity/Team.java // @Entity // @Table(name = "teams") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Team { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Team)) { // return false; // } // Team castedObj = (Team) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/TeamRepository.java // @Repository // public interface TeamRepository extends JpaRepository<Team, Integer> { // Optional<Team> findByName(String name); // } // Path: spat-services/src/main/java/com/pcalouche/spat/service/TeamServiceImpl.java import com.pcalouche.spat.api.dto.TeamDto; import com.pcalouche.spat.api.dto.TeamEditRequest; import com.pcalouche.spat.entity.Team; import com.pcalouche.spat.repository.TeamRepository; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; package com.pcalouche.spat.service; @Service public class TeamServiceImpl implements TeamService { private final TeamRepository teamRepository; public TeamServiceImpl(TeamRepository teamRepository) { this.teamRepository = teamRepository; } @Override @Transactional(readOnly = true) public Optional<TeamDto> findById(Integer id) { return teamRepository.findById(id) .map(TeamDto::map); } @Override public Optional<TeamDto> findByName(String name) { return teamRepository.findByName(name) .map(TeamDto::map); } @Override @Transactional(readOnly = true) public List<TeamDto> findAll() { return teamRepository.findAll(Sort.by("name")).stream() .map(TeamDto::map) .collect(Collectors.toList()); } @Override @Transactional public TeamDto create(TeamEditRequest teamEditRequest) {
Team team = teamRepository.save(
pcalouche/spat
spat-services/src/test/java/com/pcalouche/spat/security/util/SecurityUtilsTest.java
// Path: spat-services/src/main/java/com/pcalouche/spat/config/SpatProperties.java // @Getter // @Setter // @Component // @ConfigurationProperties(prefix = "spat") // @Validated // public class SpatProperties { // /** // * The current version. This is set use Spring Boot's automatic // * property expansion. // */ // private String version; // /** // * What origins to allow access from // */ // private String[] corsAllowedOrigins; // /** // * The signing key used for JWTs. // */ // @NotEmpty // private String jwtSigningKey; // /** // * How long JWT tokens are good for // */ // @NonNull // private Duration jwtTokenDuration; // /** // * How long JWT refresh tokens are good for // */ // @NotNull // private Duration refreshTokenDuration; // /** // * The hostname of the environment // */ // @NotEmpty // private String hostname; // // public boolean isHttpsEnvironment() { // return !"localhost".equals(hostname); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // }
import com.pcalouche.spat.config.SpatProperties; import com.pcalouche.spat.entity.User; import io.jsonwebtoken.Claims; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.*; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.util.Base64; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .buildRequest(new MockServletContext()); assertThatThrownBy(() -> SecurityUtils.getDecodedBasicAuthFromRequest(request)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Basic Authentication header is invalid"); } @Test public void testGetDecodedBasicAuthFromRequestBadHeaderPrefixThrowsException() { MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .header(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BASIC_PREFIX + Base64.getEncoder().encodeToString("invalidHeader".getBytes())) .buildRequest(new MockServletContext()); assertThatThrownBy(() -> SecurityUtils.getDecodedBasicAuthFromRequest(request)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Basic Authentication header is invalid"); } @Test public void testGetTokenFromRequest() { MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .header(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BEARER_PREFIX + "YWN0aXZlVXNlcjpwYXNzd29yZA==") .buildRequest(new MockServletContext()); request.addHeader(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BEARER_PREFIX + "YWN0aXZlVXNlcjpwYXNzd29yZA=="); assertThat(SecurityUtils.getTokenFromRequest(request)).isNotEmpty(); } @Test public void testValidateUserAccountStatusAccountExpiredException() {
// Path: spat-services/src/main/java/com/pcalouche/spat/config/SpatProperties.java // @Getter // @Setter // @Component // @ConfigurationProperties(prefix = "spat") // @Validated // public class SpatProperties { // /** // * The current version. This is set use Spring Boot's automatic // * property expansion. // */ // private String version; // /** // * What origins to allow access from // */ // private String[] corsAllowedOrigins; // /** // * The signing key used for JWTs. // */ // @NotEmpty // private String jwtSigningKey; // /** // * How long JWT tokens are good for // */ // @NonNull // private Duration jwtTokenDuration; // /** // * How long JWT refresh tokens are good for // */ // @NotNull // private Duration refreshTokenDuration; // /** // * The hostname of the environment // */ // @NotEmpty // private String hostname; // // public boolean isHttpsEnvironment() { // return !"localhost".equals(hostname); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // Path: spat-services/src/test/java/com/pcalouche/spat/security/util/SecurityUtilsTest.java import com.pcalouche.spat.config.SpatProperties; import com.pcalouche.spat.entity.User; import io.jsonwebtoken.Claims; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; import org.springframework.security.authentication.*; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.util.Base64; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .buildRequest(new MockServletContext()); assertThatThrownBy(() -> SecurityUtils.getDecodedBasicAuthFromRequest(request)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Basic Authentication header is invalid"); } @Test public void testGetDecodedBasicAuthFromRequestBadHeaderPrefixThrowsException() { MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .header(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BASIC_PREFIX + Base64.getEncoder().encodeToString("invalidHeader".getBytes())) .buildRequest(new MockServletContext()); assertThatThrownBy(() -> SecurityUtils.getDecodedBasicAuthFromRequest(request)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Basic Authentication header is invalid"); } @Test public void testGetTokenFromRequest() { MockHttpServletRequest request = MockMvcRequestBuilders.get("/some-endpoint") .header(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BEARER_PREFIX + "YWN0aXZlVXNlcjpwYXNzd29yZA==") .buildRequest(new MockServletContext()); request.addHeader(HttpHeaders.AUTHORIZATION, SecurityUtils.AUTH_HEADER_BEARER_PREFIX + "YWN0aXZlVXNlcjpwYXNzd29yZA=="); assertThat(SecurityUtils.getTokenFromRequest(request)).isNotEmpty(); } @Test public void testValidateUserAccountStatusAccountExpiredException() {
User user = User.builder()
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/service/UserService.java
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/UserDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String username; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @JsonProperty("roles") // @Builder.Default // private Set<RoleDto> roleDtos = new HashSet<>(); // // public static UserDto map(User user) { // return UserDto.builder() // .id(user.getId()) // .username(user.getUsername()) // .accountNonExpired(user.isAccountNonExpired()) // .accountNonLocked(user.isAccountNonLocked()) // .credentialsNonExpired(user.isCredentialsNonExpired()) // .enabled(user.isEnabled()) // .roleDtos( // user.getRoles().stream() // .map(RoleDto::map) // .collect(Collectors.toSet()) // ) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/UserEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserEditRequest { // @NotEmpty // private String username; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @Builder.Default // @JsonProperty("roles") // private Set<RoleDto> roleDtos = new HashSet<>(); // }
import com.pcalouche.spat.api.dto.UserDto; import com.pcalouche.spat.api.dto.UserEditRequest; import java.util.List; import java.util.Optional;
package com.pcalouche.spat.service; public interface UserService { Optional<UserDto> findById(Integer id); Optional<UserDto> findByUsername(String username); List<UserDto> findAll();
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/UserDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String username; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @JsonProperty("roles") // @Builder.Default // private Set<RoleDto> roleDtos = new HashSet<>(); // // public static UserDto map(User user) { // return UserDto.builder() // .id(user.getId()) // .username(user.getUsername()) // .accountNonExpired(user.isAccountNonExpired()) // .accountNonLocked(user.isAccountNonLocked()) // .credentialsNonExpired(user.isCredentialsNonExpired()) // .enabled(user.isEnabled()) // .roleDtos( // user.getRoles().stream() // .map(RoleDto::map) // .collect(Collectors.toSet()) // ) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/UserEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserEditRequest { // @NotEmpty // private String username; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @Builder.Default // @JsonProperty("roles") // private Set<RoleDto> roleDtos = new HashSet<>(); // } // Path: spat-services/src/main/java/com/pcalouche/spat/service/UserService.java import com.pcalouche.spat.api.dto.UserDto; import com.pcalouche.spat.api.dto.UserEditRequest; import java.util.List; import java.util.Optional; package com.pcalouche.spat.service; public interface UserService { Optional<UserDto> findById(Integer id); Optional<UserDto> findByUsername(String username); List<UserDto> findAll();
UserDto create(UserEditRequest userEditRequest);
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/service/TeamService.java
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String name; // // public static TeamDto map(Team team) { // return TeamDto.builder() // .id(team.getId()) // .name(team.getName()) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamEditRequest { // @NotEmpty // private String name; // }
import com.pcalouche.spat.api.dto.TeamDto; import com.pcalouche.spat.api.dto.TeamEditRequest; import java.util.List; import java.util.Optional;
package com.pcalouche.spat.service; public interface TeamService { Optional<TeamDto> findById(Integer id); Optional<TeamDto> findByName(String name); List<TeamDto> findAll();
// Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamDto { // @EqualsAndHashCode.Exclude // private Integer id; // private String name; // // public static TeamDto map(Team team) { // return TeamDto.builder() // .id(team.getId()) // .name(team.getName()) // .build(); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamEditRequest.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class TeamEditRequest { // @NotEmpty // private String name; // } // Path: spat-services/src/main/java/com/pcalouche/spat/service/TeamService.java import com.pcalouche.spat.api.dto.TeamDto; import com.pcalouche.spat.api.dto.TeamEditRequest; import java.util.List; import java.util.Optional; package com.pcalouche.spat.service; public interface TeamService { Optional<TeamDto> findById(Integer id); Optional<TeamDto> findByName(String name); List<TeamDto> findAll();
TeamDto create(TeamEditRequest teamEditRequest);
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/api/dto/RoleDto.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/Role.java // @Entity // @Table(name = "roles") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // @ManyToMany(mappedBy = "roles") // private Set<User> users; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Role)) { // return false; // } // Role castedObj = (Role) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // }
import com.pcalouche.spat.entity.Role; import lombok.*;
package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class RoleDto { @EqualsAndHashCode.Exclude private Integer id; private String name;
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/Role.java // @Entity // @Table(name = "roles") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // @ManyToMany(mappedBy = "roles") // private Set<User> users; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Role)) { // return false; // } // Role castedObj = (Role) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // } // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/RoleDto.java import com.pcalouche.spat.entity.Role; import lombok.*; package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class RoleDto { @EqualsAndHashCode.Exclude private Integer id; private String name;
public static RoleDto map(Role role) {
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/Team.java // @Entity // @Table(name = "teams") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Team { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Team)) { // return false; // } // Team castedObj = (Team) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // }
import com.pcalouche.spat.entity.Team; import lombok.*;
package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class TeamDto { @EqualsAndHashCode.Exclude private Integer id; private String name;
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/Team.java // @Entity // @Table(name = "teams") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class Team { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String name; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof Team)) { // return false; // } // Team castedObj = (Team) o; // return Objects.equals(name, castedObj.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(name); // } // } // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/TeamDto.java import com.pcalouche.spat.entity.Team; import lombok.*; package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class TeamDto { @EqualsAndHashCode.Exclude private Integer id; private String name;
public static TeamDto map(Team team) {
pcalouche/spat
spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // }
import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify;
package com.pcalouche.spat.security.provider; @ExtendWith(SpringExtension.class) public class LoginAuthenticationProviderTest { private LoginAuthenticationProvider loginAuthenticationProvider; @MockBean
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // } // Path: spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; package com.pcalouche.spat.security.provider; @ExtendWith(SpringExtension.class) public class LoginAuthenticationProviderTest { private LoginAuthenticationProvider loginAuthenticationProvider; @MockBean
private UserRepository userRepository;
pcalouche/spat
spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // }
import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify;
package com.pcalouche.spat.security.provider; @ExtendWith(SpringExtension.class) public class LoginAuthenticationProviderTest { private LoginAuthenticationProvider loginAuthenticationProvider; @MockBean private UserRepository userRepository; @BeforeEach public void before() { Mockito.reset(userRepository);
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // } // Path: spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; package com.pcalouche.spat.security.provider; @ExtendWith(SpringExtension.class) public class LoginAuthenticationProviderTest { private LoginAuthenticationProvider loginAuthenticationProvider; @MockBean private UserRepository userRepository; @BeforeEach public void before() { Mockito.reset(userRepository);
User activeUser = User.builder()
pcalouche/spat
spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // }
import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify;
@Test public void testAuthenticateThrowsBadCredentialsForNullUser() { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("bogusUser", "password"); assertThatThrownBy(() -> loginAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Bad credentials for username: bogusUser"); verify(userRepository, Mockito.times(1)).findByUsername("bogusUser"); } @Test public void testAuthenticateThrowsBadCredentialsForBadPassword() { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("activeUser", "badPassword"); assertThatThrownBy(() -> loginAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Bad credentials for username: activeUser"); verify(userRepository, Mockito.times(1)).findByUsername("activeUser"); } @Test public void testSupportValidAuthenticationClass() { assertThat(loginAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)) .isTrue(); } @Test public void testSupportInvalidAuthenticationClass() {
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // // Path: spat-services/src/main/java/com/pcalouche/spat/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // Optional<User> findByUsername(String username); // } // // Path: spat-services/src/main/java/com/pcalouche/spat/security/authentication/JwtAuthenticationToken.java // public class JwtAuthenticationToken extends AbstractAuthenticationToken { // private final String subject; // private final String token; // // public JwtAuthenticationToken(String token) { // super(null); // this.token = token; // subject = null; // setAuthenticated(false); // } // // public JwtAuthenticationToken(String subject, // Collection<? extends GrantedAuthority> authorities) { // super(authorities); // this.subject = subject; // this.token = null; // setAuthenticated(true); // } // // @Override // public String getPrincipal() { // return subject; // } // // @Override // public String getCredentials() { // return token; // } // } // Path: spat-services/src/test/java/com/pcalouche/spat/security/provider/LoginAuthenticationProviderTest.java import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @Test public void testAuthenticateThrowsBadCredentialsForNullUser() { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("bogusUser", "password"); assertThatThrownBy(() -> loginAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Bad credentials for username: bogusUser"); verify(userRepository, Mockito.times(1)).findByUsername("bogusUser"); } @Test public void testAuthenticateThrowsBadCredentialsForBadPassword() { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("activeUser", "badPassword"); assertThatThrownBy(() -> loginAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Bad credentials for username: activeUser"); verify(userRepository, Mockito.times(1)).findByUsername("activeUser"); } @Test public void testSupportValidAuthenticationClass() { assertThat(loginAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)) .isTrue(); } @Test public void testSupportInvalidAuthenticationClass() {
assertThat(loginAuthenticationProvider.supports(JwtAuthenticationToken.class))
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/api/ControllerExceptionAdvice.java
// Path: spat-services/src/main/java/com/pcalouche/spat/exception/ApiErrorResponse.java // @Getter // @EqualsAndHashCode // public class ApiErrorResponse { // private static final ObjectMapper objectMapper = new ObjectMapper(); // private static final String VALIDATION_MESSAGES = "Validation failed. See validation messages."; // private final String timestamp; // private final String path; // private final String message; // private final String exception; // @JsonIgnore // private final HttpStatus httpStatus; // @JsonInclude(JsonInclude.Include.NON_NULL) // private final Map<String, String> validationMessages; // // public ApiErrorResponse(Exception e, HttpServletRequest request) { // timestamp = ZonedDateTime.now().toOffsetDateTime().toString(); // path = StringUtils.isNotBlank(request.getQueryString()) ? // request.getRequestURI() + "?" + request.getQueryString() // : // request.getRequestURI(); // exception = e.getClass().getName(); // // if (e instanceof AuthenticationException || // e instanceof JwtException) { // httpStatus = HttpStatus.UNAUTHORIZED; // } else if (e instanceof AccessDeniedException) { // httpStatus = HttpStatus.FORBIDDEN; // } else if (e instanceof HttpMessageConversionException || // e instanceof MethodArgumentNotValidException || // e instanceof MethodArgumentTypeMismatchException || // e instanceof BindException) { // httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; // } else if (e instanceof ApiException) { // httpStatus = ((ApiException) e).getStatus(); // } else { // httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; // } // // if (e instanceof MethodArgumentNotValidException || e instanceof BindException) { // message = VALIDATION_MESSAGES; // validationMessages = getValidationMessages(e); // } else { // message = e.getMessage(); // validationMessages = null; // } // } // // public static void writeExceptionToResponse(Exception e, HttpServletRequest request, HttpServletResponse response) // throws IOException { // ApiErrorResponse apiErrorResponse = new ApiErrorResponse(e, request); // response.setStatus(apiErrorResponse.getStatus()); // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // objectMapper.writeValue(response.getWriter(), apiErrorResponse); // } // // private static Map<String, String> getValidationMessages(Exception e) { // Map<String, String> validateMessages = new HashMap<>(); // List<FieldError> fieldErrors; // if (e instanceof MethodArgumentNotValidException) { // MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e; // fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors(); // } else { // BindException bindException = (BindException) e; // fieldErrors = bindException.getBindingResult().getFieldErrors(); // } // fieldErrors.forEach(fieldError -> validateMessages.put(fieldError.getField(), fieldError.getDefaultMessage())); // return validateMessages; // } // // public int getStatus() { // return httpStatus.value(); // } // // public String getReasonPhrase() { // return httpStatus.getReasonPhrase(); // } // }
import com.pcalouche.spat.exception.ApiErrorResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest;
package com.pcalouche.spat.api; @ControllerAdvice public class ControllerExceptionAdvice { private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionAdvice.class); @ExceptionHandler({Exception.class})
// Path: spat-services/src/main/java/com/pcalouche/spat/exception/ApiErrorResponse.java // @Getter // @EqualsAndHashCode // public class ApiErrorResponse { // private static final ObjectMapper objectMapper = new ObjectMapper(); // private static final String VALIDATION_MESSAGES = "Validation failed. See validation messages."; // private final String timestamp; // private final String path; // private final String message; // private final String exception; // @JsonIgnore // private final HttpStatus httpStatus; // @JsonInclude(JsonInclude.Include.NON_NULL) // private final Map<String, String> validationMessages; // // public ApiErrorResponse(Exception e, HttpServletRequest request) { // timestamp = ZonedDateTime.now().toOffsetDateTime().toString(); // path = StringUtils.isNotBlank(request.getQueryString()) ? // request.getRequestURI() + "?" + request.getQueryString() // : // request.getRequestURI(); // exception = e.getClass().getName(); // // if (e instanceof AuthenticationException || // e instanceof JwtException) { // httpStatus = HttpStatus.UNAUTHORIZED; // } else if (e instanceof AccessDeniedException) { // httpStatus = HttpStatus.FORBIDDEN; // } else if (e instanceof HttpMessageConversionException || // e instanceof MethodArgumentNotValidException || // e instanceof MethodArgumentTypeMismatchException || // e instanceof BindException) { // httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; // } else if (e instanceof ApiException) { // httpStatus = ((ApiException) e).getStatus(); // } else { // httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; // } // // if (e instanceof MethodArgumentNotValidException || e instanceof BindException) { // message = VALIDATION_MESSAGES; // validationMessages = getValidationMessages(e); // } else { // message = e.getMessage(); // validationMessages = null; // } // } // // public static void writeExceptionToResponse(Exception e, HttpServletRequest request, HttpServletResponse response) // throws IOException { // ApiErrorResponse apiErrorResponse = new ApiErrorResponse(e, request); // response.setStatus(apiErrorResponse.getStatus()); // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // objectMapper.writeValue(response.getWriter(), apiErrorResponse); // } // // private static Map<String, String> getValidationMessages(Exception e) { // Map<String, String> validateMessages = new HashMap<>(); // List<FieldError> fieldErrors; // if (e instanceof MethodArgumentNotValidException) { // MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e; // fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors(); // } else { // BindException bindException = (BindException) e; // fieldErrors = bindException.getBindingResult().getFieldErrors(); // } // fieldErrors.forEach(fieldError -> validateMessages.put(fieldError.getField(), fieldError.getDefaultMessage())); // return validateMessages; // } // // public int getStatus() { // return httpStatus.value(); // } // // public String getReasonPhrase() { // return httpStatus.getReasonPhrase(); // } // } // Path: spat-services/src/main/java/com/pcalouche/spat/api/ControllerExceptionAdvice.java import com.pcalouche.spat.exception.ApiErrorResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest; package com.pcalouche.spat.api; @ControllerAdvice public class ControllerExceptionAdvice { private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionAdvice.class); @ExceptionHandler({Exception.class})
public ResponseEntity<ApiErrorResponse> handleException(Exception e, HttpServletRequest request) {
pcalouche/spat
spat-services/src/main/java/com/pcalouche/spat/api/dto/UserDto.java
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.pcalouche.spat.entity.User; import lombok.*; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors;
package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class UserDto { @EqualsAndHashCode.Exclude private Integer id; private String username; @Builder.Default private boolean accountNonExpired = true; @Builder.Default private boolean accountNonLocked = true; @Builder.Default private boolean credentialsNonExpired = true; @Builder.Default private boolean enabled = true; @JsonProperty("roles") @Builder.Default private Set<RoleDto> roleDtos = new HashSet<>();
// Path: spat-services/src/main/java/com/pcalouche/spat/entity/User.java // @Entity // @Table(name = "users") // @Getter // @Setter // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class User implements UserDetails { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private Integer id; // @NotBlank // @Column(unique = true, nullable = false) // private String username; // @NotBlank // @Column(nullable = false) // private String password; // @Builder.Default // private boolean accountNonExpired = true; // @Builder.Default // private boolean accountNonLocked = true; // @Builder.Default // private boolean credentialsNonExpired = true; // @Builder.Default // private boolean enabled = true; // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) // @Builder.Default // private Set<Role> roles = new HashSet<>(); // @Transient // @Setter(AccessLevel.NONE) // private Set<SimpleGrantedAuthority> authorities; // // @Override // public Set<SimpleGrantedAuthority> getAuthorities() { // if (authorities == null) { // authorities = new HashSet<>(); // if (roles != null) { // for (Role role : roles) { // authorities.add(new SimpleGrantedAuthority(role.getName())); // } // } // } // return authorities; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (!(o instanceof User)) { // return false; // } // User castedObj = (User) o; // return Objects.equals(username, castedObj.getUsername()); // } // // @Override // public int hashCode() { // return Objects.hash(username); // } // } // Path: spat-services/src/main/java/com/pcalouche/spat/api/dto/UserDto.java import com.fasterxml.jackson.annotation.JsonProperty; import com.pcalouche.spat.entity.User; import lombok.*; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; package com.pcalouche.spat.api.dto; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class UserDto { @EqualsAndHashCode.Exclude private Integer id; private String username; @Builder.Default private boolean accountNonExpired = true; @Builder.Default private boolean accountNonLocked = true; @Builder.Default private boolean credentialsNonExpired = true; @Builder.Default private boolean enabled = true; @JsonProperty("roles") @Builder.Default private Set<RoleDto> roleDtos = new HashSet<>();
public static UserDto map(User user) {
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/persistence/PersistenceTargetClass.java // public class PersistenceTargetClass { // public static void dummy() { // System.out.println("I'm just here to match pointcuts"); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {}
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.persistence.PersistenceTargetClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend; public class IllBehavedFrontendClass implements IllBehaved { public void illBehavedMethod() {
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/persistence/PersistenceTargetClass.java // public class PersistenceTargetClass { // public static void dummy() { // System.out.println("I'm just here to match pointcuts"); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.persistence.PersistenceTargetClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend; public class IllBehavedFrontendClass implements IllBehaved { public void illBehavedMethod() {
PersistenceTargetClass.dummy();
mostlymagic/hacking-java
3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractCompilerTest.java
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // }
import com.google.common.base.Joiner; import java.util.List; import java.util.stream.Collectors; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.SelfDescribing; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.junit.Before; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine;
package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractCompilerTest extends CompilationHelper { DefectAnalysisEngine engine; protected abstract DefectAnalysisEngine instantiateEngine(); @Before public void setupEngine() { this.engine = instantiateEngine(); }
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractCompilerTest.java import com.google.common.base.Joiner; import java.util.List; import java.util.stream.Collectors; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.SelfDescribing; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.junit.Before; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractCompilerTest extends CompilationHelper { DefectAnalysisEngine engine; protected abstract DefectAnalysisEngine instantiateEngine(); @Before public void setupEngine() { this.engine = instantiateEngine(); }
protected Matcher<CompilationResult> isSuccess() {
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/persistence/PersistenceTargetClass.java // public class PersistenceTargetClass { // public static void dummy() { // System.out.println("I'm just here to match pointcuts"); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // }
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.persistence.PersistenceTargetClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service; public class WellBehavedServiceClass implements WellBehaved { public void wellBehavedMethod() {
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/persistence/PersistenceTargetClass.java // public class PersistenceTargetClass { // public static void dummy() { // System.out.println("I'm just here to match pointcuts"); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.persistence.PersistenceTargetClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service; public class WellBehavedServiceClass implements WellBehaved { public void wellBehavedMethod() {
PersistenceTargetClass.dummy();
mostlymagic/hacking-java
1_valueobjects/3_cglib/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/cglib/UserFactory.java
// Path: 1_valueobjects/3_cglib/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/cglib/DtoFactory.java // static Class<?> createBeanClass( // /* fully qualified class name */ // final String className, // /* bean properties, name -> type */ // final Map<String, Class<?>> properties) { // // final BeanGenerator beanGenerator = new BeanGenerator(); // // /* use our own hard coded class name instead of a real naming policy */ // beanGenerator.setNamingPolicy(new NamingPolicy() { // @Override public String getClassName(final String prefix, // final String source, // final Object key, // final Predicate names) { // return className; // } // }); // BeanGenerator.addProperties(beanGenerator, properties); // return (Class<?>) beanGenerator.createClass(); // }
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.time.LocalDate; import java.util.List; import static org.zalando.techtalks.hackingjava.valueobjects.cglib.DtoFactory.createBeanClass;
package org.zalando.techtalks.hackingjava.valueobjects.cglib; public class UserFactory { public static Object createUser(final String firstName, final String lastName, final LocalDate birthDate, final String street, final int zipCode, final String city) { final Object address = DtoFactory.instantiateDto(Types.ADDRESS, ImmutableMap.of( "street", street, "zipCode", zipCode, "city", city )); final ImmutableList<Object> addresses = ImmutableList.of(address); final Object user = DtoFactory.instantiateDto(Types.USER, ImmutableMap.of("firstName", firstName, "lastName", lastName, "addresses", addresses, "birthDate", birthDate), ImmutableList.of("lastName", "firstName", "birthDate") ); return user; } static class Types { private static final String PACKAGE = "org.zalando.techtalks.hackingjava.valueobjects.cglib.dto"; private static final Class<?> USER; private static final Class<?> ADDRESS; static {
// Path: 1_valueobjects/3_cglib/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/cglib/DtoFactory.java // static Class<?> createBeanClass( // /* fully qualified class name */ // final String className, // /* bean properties, name -> type */ // final Map<String, Class<?>> properties) { // // final BeanGenerator beanGenerator = new BeanGenerator(); // // /* use our own hard coded class name instead of a real naming policy */ // beanGenerator.setNamingPolicy(new NamingPolicy() { // @Override public String getClassName(final String prefix, // final String source, // final Object key, // final Predicate names) { // return className; // } // }); // BeanGenerator.addProperties(beanGenerator, properties); // return (Class<?>) beanGenerator.createClass(); // } // Path: 1_valueobjects/3_cglib/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/cglib/UserFactory.java import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.time.LocalDate; import java.util.List; import static org.zalando.techtalks.hackingjava.valueobjects.cglib.DtoFactory.createBeanClass; package org.zalando.techtalks.hackingjava.valueobjects.cglib; public class UserFactory { public static Object createUser(final String firstName, final String lastName, final LocalDate birthDate, final String street, final int zipCode, final String city) { final Object address = DtoFactory.instantiateDto(Types.ADDRESS, ImmutableMap.of( "street", street, "zipCode", zipCode, "city", city )); final ImmutableList<Object> addresses = ImmutableList.of(address); final Object user = DtoFactory.instantiateDto(Types.USER, ImmutableMap.of("firstName", firstName, "lastName", lastName, "addresses", addresses, "birthDate", birthDate), ImmutableList.of("lastName", "firstName", "birthDate") ); return user; } static class Types { private static final String PACKAGE = "org.zalando.techtalks.hackingjava.valueobjects.cglib.dto"; private static final Class<?> USER; private static final Class<?> ADDRESS; static {
USER = createBeanClass(PACKAGE + ".User",
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJPolicyEnforcementTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJPolicyEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedClass.class; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJPolicyEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJPolicyEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedClass.class; }
@Override protected Class<? extends IllBehaved> illBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJPolicyEnforcementTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJPolicyEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedClass.class; } @Override protected String expectedErrorMessage() { return "Hashtable and Vector are deprecated classes"; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJPolicyEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJPolicyEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedClass.class; } @Override protected String expectedErrorMessage() { return "Hashtable and Vector are deprecated classes"; }
@Override protected DefectAnalysisEngine instantiateEngine() {
mostlymagic/hacking-java
1_valueobjects/2_autovalue/src/test/java/org/zalando/techtalks/hackingjava/valueobjects/autovalue/builder/BuilderUserTest.java
// Path: 1_valueobjects/x_tests/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/tests/BaseUserTest.java // public abstract class BaseUserTest { // protected static final String FIRST_NAME = "Fred"; // protected static final String LAST_NAME = "Flintstone"; // protected static final LocalDate BIRTH_DATE = LocalDate.MIN; // protected static final String STREET = "301 Cobblestone Way"; // protected static final int ZIP_CODE = 70777; // protected static final String CITY = "Bedrock"; // // @Test // public void equalsAndHashCodeAreSymmetrical() { // final Object user1 = createUser(); // final Object user2 = createUser(); // assertThat(user1, is(equalTo(user2))); // assertThat(user2, is(equalTo(user1))); // assertThat(user1.hashCode(), is(equalTo(user2.hashCode()))); // } // // @Test // public void toStringIsConsistent() { // assertThat(createUser().toString(), is(equalTo(createUser().toString()))); // final String s = createUser().toString(); // assertThat(s, containsString(FIRST_NAME)); // assertThat(s, containsString(LAST_NAME)); // assertThat(s, containsString(CITY)); // } // // @SuppressWarnings({"unchecked", "rawtypes"}) @Test // public void compareToIsSymmetrical() { // final Object left = createUser(); // final Object right = createUser(); // assertThat(left, instanceOf(Comparable.class)); // assertThat(right, instanceOf(Comparable.class)); // assertThat(((Comparable) left).compareTo(right), // is(equalTo(((Comparable) right).compareTo(left)))); // } // // @Test // public void propertyMapHasCorrectValues() { // final Object instance = createUser(); // final Map<String, Object> userPropertyMap = getPropertyMap(instance); // assertThat(userPropertyMap, hasEntry("firstName", FIRST_NAME)); // assertThat(userPropertyMap, hasEntry("lastName", LAST_NAME)); // assertThat(userPropertyMap, hasEntry("birthDate", BIRTH_DATE)); // assertThat(userPropertyMap, hasKey("addresses")); // // // final Object addresses = userPropertyMap.get("addresses"); // assertThat(addresses, is(instanceOf(List.class))); // final List<?> list = List.class.cast(addresses); // assertThat(list, hasSize(1)); // // final Map<String, Object> addressPropertyMap = getPropertyMap(list.get(0)); // assertThat(addressPropertyMap, hasEntry("street", STREET)); // assertThat(addressPropertyMap, hasEntry("zipCode", ZIP_CODE)); // assertThat(addressPropertyMap, hasEntry("city", CITY)); // // // } // // private static Map<String, Object> getPropertyMap(final Object instance) { // final Map<String, Object> propertyMap = new TreeMap<>(); // try { // Arrays.stream(Introspector.getBeanInfo(instance.getClass(), Object.class) // .getPropertyDescriptors()) // .filter((it) -> it.getReadMethod() != null) // .forEach((propertyDescriptor) -> { // final Method method = propertyDescriptor.getReadMethod(); // try { // final Object result = method.invoke(instance); // propertyMap.put(propertyDescriptor.getName(), result); // } catch (IllegalAccessException | InvocationTargetException e) { // throw new IllegalStateException(e); // } // }); // } catch (IntrospectionException e) { // throw new IllegalStateException(e); // } // return propertyMap; // } // // protected abstract Object createUser(); // } // // Path: 1_valueobjects/2_autovalue/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/autovalue/builder/User.java // public static Builder userBuilder() {return new AutoValue_User.Builder();}
import org.zalando.techtalks.hackingjava.valueobjects.tests.BaseUserTest; import static org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder.Address .addressBuilder; import static org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder.User.userBuilder;
package org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder; public class BuilderUserTest extends BaseUserTest { @Override protected Object createUser() {
// Path: 1_valueobjects/x_tests/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/tests/BaseUserTest.java // public abstract class BaseUserTest { // protected static final String FIRST_NAME = "Fred"; // protected static final String LAST_NAME = "Flintstone"; // protected static final LocalDate BIRTH_DATE = LocalDate.MIN; // protected static final String STREET = "301 Cobblestone Way"; // protected static final int ZIP_CODE = 70777; // protected static final String CITY = "Bedrock"; // // @Test // public void equalsAndHashCodeAreSymmetrical() { // final Object user1 = createUser(); // final Object user2 = createUser(); // assertThat(user1, is(equalTo(user2))); // assertThat(user2, is(equalTo(user1))); // assertThat(user1.hashCode(), is(equalTo(user2.hashCode()))); // } // // @Test // public void toStringIsConsistent() { // assertThat(createUser().toString(), is(equalTo(createUser().toString()))); // final String s = createUser().toString(); // assertThat(s, containsString(FIRST_NAME)); // assertThat(s, containsString(LAST_NAME)); // assertThat(s, containsString(CITY)); // } // // @SuppressWarnings({"unchecked", "rawtypes"}) @Test // public void compareToIsSymmetrical() { // final Object left = createUser(); // final Object right = createUser(); // assertThat(left, instanceOf(Comparable.class)); // assertThat(right, instanceOf(Comparable.class)); // assertThat(((Comparable) left).compareTo(right), // is(equalTo(((Comparable) right).compareTo(left)))); // } // // @Test // public void propertyMapHasCorrectValues() { // final Object instance = createUser(); // final Map<String, Object> userPropertyMap = getPropertyMap(instance); // assertThat(userPropertyMap, hasEntry("firstName", FIRST_NAME)); // assertThat(userPropertyMap, hasEntry("lastName", LAST_NAME)); // assertThat(userPropertyMap, hasEntry("birthDate", BIRTH_DATE)); // assertThat(userPropertyMap, hasKey("addresses")); // // // final Object addresses = userPropertyMap.get("addresses"); // assertThat(addresses, is(instanceOf(List.class))); // final List<?> list = List.class.cast(addresses); // assertThat(list, hasSize(1)); // // final Map<String, Object> addressPropertyMap = getPropertyMap(list.get(0)); // assertThat(addressPropertyMap, hasEntry("street", STREET)); // assertThat(addressPropertyMap, hasEntry("zipCode", ZIP_CODE)); // assertThat(addressPropertyMap, hasEntry("city", CITY)); // // // } // // private static Map<String, Object> getPropertyMap(final Object instance) { // final Map<String, Object> propertyMap = new TreeMap<>(); // try { // Arrays.stream(Introspector.getBeanInfo(instance.getClass(), Object.class) // .getPropertyDescriptors()) // .filter((it) -> it.getReadMethod() != null) // .forEach((propertyDescriptor) -> { // final Method method = propertyDescriptor.getReadMethod(); // try { // final Object result = method.invoke(instance); // propertyMap.put(propertyDescriptor.getName(), result); // } catch (IllegalAccessException | InvocationTargetException e) { // throw new IllegalStateException(e); // } // }); // } catch (IntrospectionException e) { // throw new IllegalStateException(e); // } // return propertyMap; // } // // protected abstract Object createUser(); // } // // Path: 1_valueobjects/2_autovalue/src/main/java/org/zalando/techtalks/hackingjava/valueobjects/autovalue/builder/User.java // public static Builder userBuilder() {return new AutoValue_User.Builder();} // Path: 1_valueobjects/2_autovalue/src/test/java/org/zalando/techtalks/hackingjava/valueobjects/autovalue/builder/BuilderUserTest.java import org.zalando.techtalks.hackingjava.valueobjects.tests.BaseUserTest; import static org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder.Address .addressBuilder; import static org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder.User.userBuilder; package org.zalando.techtalks.hackingjava.valueobjects.autovalue.builder; public class BuilderUserTest extends BaseUserTest { @Override protected Object createUser() {
return userBuilder()
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() {
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() {
return WellBehavedServiceClass.class;
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; }
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; }
@Override protected Class<? extends IllBehaved> illBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() {
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() {
return IllBehavedFrontendClass.class;
mostlymagic/hacking-java
3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedFrontendClass.class; } @Override protected String expectedErrorMessage() { return "The persistence package may not be accessed from the frontend package"; }
// Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/frontend/IllBehavedFrontendClass.java // public class IllBehavedFrontendClass implements IllBehaved { // public void illBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/3_aspectj/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/service/WellBehavedServiceClass.java // public class WellBehavedServiceClass implements WellBehaved { // public void wellBehavedMethod() { // PersistenceTargetClass.dummy(); // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/3_aspectj/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/aspectj/AspectJArchitectureEnforcementTest.java import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.frontend.IllBehavedFrontendClass; import org.zalando.techtalks.hackingjava.defectanalysis.aspectj.service.WellBehavedServiceClass; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.aspectj; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class AspectJArchitectureEnforcementTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedServiceClass.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedFrontendClass.class; } @Override protected String expectedErrorMessage() { return "The persistence package may not be accessed from the frontend package"; }
@Override protected DefectAnalysisEngine instantiateEngine() {
mostlymagic/hacking-java
x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/compilertesting/CompilerRun.java
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // }
import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import static java.util.stream.Collectors.toList; import static javax.tools.Diagnostic.Kind.ERROR; import static javax.tools.Diagnostic.Kind.WARNING;
compilerFlags.add(additionalFlag); } return this; } public CompilerRun setLocation(final StandardLocation location, final File firstPath, final File... morePaths) { try { final List<File> paths = new ArrayList<>(morePaths.length + 1); paths.add(firstPath); paths.addAll(Arrays.asList(morePaths)); fileManager.setLocation(location, paths); return this; } catch (IOException e) { throw new IllegalStateException(e); } } public CompilerRun addAnnotationProcessor(final String annotationProcessor) { annotationProcessorClasses.add(annotationProcessor); return this; } public CompilerRun addAnnotationProcessor(final Class<?> annotationProcessor) { annotationProcessorClasses.add(annotationProcessor.getName()); return this; }
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/compilertesting/CompilerRun.java import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import static java.util.stream.Collectors.toList; import static javax.tools.Diagnostic.Kind.ERROR; import static javax.tools.Diagnostic.Kind.WARNING; compilerFlags.add(additionalFlag); } return this; } public CompilerRun setLocation(final StandardLocation location, final File firstPath, final File... morePaths) { try { final List<File> paths = new ArrayList<>(morePaths.length + 1); paths.add(firstPath); paths.addAll(Arrays.asList(morePaths)); fileManager.setLocation(location, paths); return this; } catch (IOException e) { throw new IllegalStateException(e); } } public CompilerRun addAnnotationProcessor(final String annotationProcessor) { annotationProcessorClasses.add(annotationProcessor); return this; } public CompilerRun addAnnotationProcessor(final Class<?> annotationProcessor) { annotationProcessorClasses.add(annotationProcessor.getName()); return this; }
public CompilationResult compile() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; }
@Override protected Class<? extends IllBehaved> illBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedRegex.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/InvalidPatternSyntax"; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedRegex.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/InvalidPatternSyntax"; }
@Override protected DefectAnalysisEngine instantiateEngine() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedRegex.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/InvalidPatternSyntax"; } @Override protected DefectAnalysisEngine instantiateEngine() {
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/regex/ErrorProneRegexBugDetectionTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.regex; public class ErrorProneRegexBugDetectionTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellBehavedRegex.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllBehavedRegex.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/InvalidPatternSyntax"; } @Override protected DefectAnalysisEngine instantiateEngine() {
return new ErrorProneAnalysisEngine(ImmutableSet.of("InvalidPatternSyntax"));
mostlymagic/hacking-java
x_common/reflection/src/test/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelperTest.java
// Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static <T> T instantiate(final Class<? extends T> type, final Object... params) { // try { // final Constructor<T> constructor = findCompatibleConstructor(type, params); // constructor.setAccessible(true); // return constructor.newInstance(params); // } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // } // // Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static Object invokeMethod(final Object targetObject, // final String methodName, // final Object... params) { // try { // final List<Method> methodsByName = findMethodsByName(targetObject.getClass(), // methodName); // final Method method = // methodsByName.stream() // // .filter(candidate -> candidate.getParameterCount() == params.length) // // .findFirst() // // .orElseThrow(ReflectionHelper::noAppropriateMethodFound); // // method.setAccessible(true); // return method.invoke(targetObject, params); // // } catch (InvocationTargetException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // // }
import java.util.Objects; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.instantiate; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.invokeMethod;
package org.zalando.techtalks.hackingjava.common.reflection; public class ReflectionHelperTest { static class NotMuchHere { @Override public boolean equals(final Object obj) { return obj instanceof NotMuchHere; } @Override public int hashCode() { return 1; } } @Test public void instantiateWithDefaultConstructor() {
// Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static <T> T instantiate(final Class<? extends T> type, final Object... params) { // try { // final Constructor<T> constructor = findCompatibleConstructor(type, params); // constructor.setAccessible(true); // return constructor.newInstance(params); // } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // } // // Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static Object invokeMethod(final Object targetObject, // final String methodName, // final Object... params) { // try { // final List<Method> methodsByName = findMethodsByName(targetObject.getClass(), // methodName); // final Method method = // methodsByName.stream() // // .filter(candidate -> candidate.getParameterCount() == params.length) // // .findFirst() // // .orElseThrow(ReflectionHelper::noAppropriateMethodFound); // // method.setAccessible(true); // return method.invoke(targetObject, params); // // } catch (InvocationTargetException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // // } // Path: x_common/reflection/src/test/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelperTest.java import java.util.Objects; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.instantiate; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.invokeMethod; package org.zalando.techtalks.hackingjava.common.reflection; public class ReflectionHelperTest { static class NotMuchHere { @Override public boolean equals(final Object obj) { return obj instanceof NotMuchHere; } @Override public int hashCode() { return 1; } } @Test public void instantiateWithDefaultConstructor() {
assertThat(instantiate(NotMuchHere.class),
mostlymagic/hacking-java
x_common/reflection/src/test/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelperTest.java
// Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static <T> T instantiate(final Class<? extends T> type, final Object... params) { // try { // final Constructor<T> constructor = findCompatibleConstructor(type, params); // constructor.setAccessible(true); // return constructor.newInstance(params); // } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // } // // Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static Object invokeMethod(final Object targetObject, // final String methodName, // final Object... params) { // try { // final List<Method> methodsByName = findMethodsByName(targetObject.getClass(), // methodName); // final Method method = // methodsByName.stream() // // .filter(candidate -> candidate.getParameterCount() == params.length) // // .findFirst() // // .orElseThrow(ReflectionHelper::noAppropriateMethodFound); // // method.setAccessible(true); // return method.invoke(targetObject, params); // // } catch (InvocationTargetException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // // }
import java.util.Objects; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.instantiate; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.invokeMethod;
public int hashCode() { return Objects.hash(foo, bar); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (obj instanceof TwoArgs) { final TwoArgs other = (TwoArgs) obj; return Objects.equals(this.foo, other.foo) && Objects.equals(this.bar, other.bar); } else { return false; } } } @Test public void instantiateWithParams() { assertThat(instantiate(TwoArgs.class, 123, "abc"), CoreMatchers.is(CoreMatchers.equalTo(new TwoArgs(123, "abc")))); } @Test public void invokeMethodWithoutParam() { class MethodWithoutParam { String foo() { return "bar"; } }
// Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static <T> T instantiate(final Class<? extends T> type, final Object... params) { // try { // final Constructor<T> constructor = findCompatibleConstructor(type, params); // constructor.setAccessible(true); // return constructor.newInstance(params); // } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // } // // Path: x_common/reflection/src/main/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelper.java // public static Object invokeMethod(final Object targetObject, // final String methodName, // final Object... params) { // try { // final List<Method> methodsByName = findMethodsByName(targetObject.getClass(), // methodName); // final Method method = // methodsByName.stream() // // .filter(candidate -> candidate.getParameterCount() == params.length) // // .findFirst() // // .orElseThrow(ReflectionHelper::noAppropriateMethodFound); // // method.setAccessible(true); // return method.invoke(targetObject, params); // // } catch (InvocationTargetException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // // } // Path: x_common/reflection/src/test/java/org/zalando/techtalks/hackingjava/common/reflection/ReflectionHelperTest.java import java.util.Objects; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.instantiate; import static org.zalando.techtalks.hackingjava.common.reflection.ReflectionHelper.invokeMethod; public int hashCode() { return Objects.hash(foo, bar); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (obj instanceof TwoArgs) { final TwoArgs other = (TwoArgs) obj; return Objects.equals(this.foo, other.foo) && Objects.equals(this.bar, other.bar); } else { return false; } } } @Test public void instantiateWithParams() { assertThat(instantiate(TwoArgs.class, 123, "abc"), CoreMatchers.is(CoreMatchers.equalTo(new TwoArgs(123, "abc")))); } @Test public void invokeMethodWithoutParam() { class MethodWithoutParam { String foo() { return "bar"; } }
assertThat(invokeMethod(new MethodWithoutParam(), "foo"), CoreMatchers.is("bar"));
mostlymagic/hacking-java
3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; }
@Override protected Class<? extends IllBehaved> illBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllbehavedNullness.class; } @Override protected String expectedErrorMessage() { return "required: @Initialized @NonNull String"; }
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllbehavedNullness.class; } @Override protected String expectedErrorMessage() { return "required: @Initialized @NonNull String"; }
@Override protected DefectAnalysisEngine instantiateEngine() {
mostlymagic/hacking-java
3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllbehavedNullness.class; } @Override protected String expectedErrorMessage() { return "required: @Initialized @NonNull String"; } @Override protected DefectAnalysisEngine instantiateEngine() {
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/2_checker-framework/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/engine/CheckerFrameworkAnalysisEngine.java // public class CheckerFrameworkAnalysisEngine implements DefectAnalysisEngine { // // private final Class<? extends BaseTypeChecker> checkerClass; // // public CheckerFrameworkAnalysisEngine(final Class<? extends BaseTypeChecker> checkerClass) { // this.checkerClass = checkerClass; // } // // @Override public CompilationResult compile(final File sourceFile) { // return new ForkedRun(CheckerFrameworkAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withJavaC() // .withArg("-d").tempDirAsArg() // .withArg("-processor").withArg(checkerClass) // .withArg(sourceFile.getAbsolutePath()) // .run(); // } // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/2_checker-framework/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/checkerframework/nullness/CheckerFrameworkNullnessTest.java import org.checkerframework.checker.nullness.NullnessChecker; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.engine.CheckerFrameworkAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.checkerframework.nullness; /** * @author Sean Patrick Floyd (sean.floyd@zalando.de) * @since 21.01.2016 */ public class CheckerFrameworkNullnessTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return WellbehavedNullness.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return IllbehavedNullness.class; } @Override protected String expectedErrorMessage() { return "required: @Initialized @NonNull String"; } @Override protected DefectAnalysisEngine instantiateEngine() {
return new CheckerFrameworkAnalysisEngine(NullnessChecker.class);
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override
protected Class<? extends WellBehaved> wellBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override
protected Class<? extends IllBehaved> illBehavedClass() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return FakeErrorProneImmutableUser.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/Immutable"; } @Override
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return FakeErrorProneImmutableUser.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/Immutable"; } @Override
protected DefectAnalysisEngine instantiateEngine() {
mostlymagic/hacking-java
3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // }
import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest;
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return FakeErrorProneImmutableUser.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/Immutable"; } @Override protected DefectAnalysisEngine instantiateEngine() {
// Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/engine/DefectAnalysisEngine.java // public interface DefectAnalysisEngine { // CompilationResult compile(File sourceFile); // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // // Path: 3_defect-analysis/1_errorprone/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/engine/ErrorProneAnalysisEngine.java // public class ErrorProneAnalysisEngine implements DefectAnalysisEngine { // // private final Set<String> activatedChecks; // // public ErrorProneAnalysisEngine(final Set<String> activatedChecks) { // this.activatedChecks = activatedChecks; // } // // static String jarPathFromClass(final Class<?> referenceClass) { // try { // return new File( // referenceClass.getProtectionDomain() // .getCodeSource() // .getLocation() // .toURI() // ).getAbsolutePath(); // } catch (URISyntaxException e) { // throw new IllegalStateException(e); // } // } // // @Override // public CompilationResult compile(final File sourceFile) { // return new ForkedRun(ErrorProneAnalysisEngine.class) // .withAdditionalClassLoaderFromClass(AbstractUser.class) // .withBootClassPathMatcher("com", "google", "errorprone") // .withBootClassPathMatcher("org", "checkerframework") // .withArg(ErrorProneCompiler.class) // .withArg("-d").tempDirAsArg() // .withArg("-Xep:" + Joiner.on(',').join(activatedChecks)) // .withArg(sourceFile.getAbsolutePath()).run(); // // } // // } // // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java // public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { // // protected abstract Class<? extends WellBehaved> wellBehavedClass(); // // protected abstract Class<? extends IllBehaved> illBehavedClass(); // // @Test // public void detectWellBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass())); // assertThat(result, isSuccess()); // } // // @Test // public void detectIllBehavedClass() { // final CompilationResult result = engine.compile(sourceFileFor(illBehavedClass())); // assertThat(result, isFailureWithExpectedMessage(expectedErrorMessage())); // } // // protected abstract String expectedErrorMessage(); // // } // Path: 3_defect-analysis/1_errorprone/src/test/java/org/zalando/techtalks/hackingjava/defectanalysis/errorprone/immutable/ErrorProneImmutableUserTest.java import com.google.common.collect.ImmutableSet; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine.ErrorProneAnalysisEngine; import org.zalando.techtalks.hackingjava.defectanalysis.tests.AbstractDefectDetectionTest; package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable; public class ErrorProneImmutableUserTest extends AbstractDefectDetectionTest { @Override protected Class<? extends WellBehaved> wellBehavedClass() { return ProperErrorProneImmutableUser.class; } @Override protected Class<? extends IllBehaved> illBehavedClass() { return FakeErrorProneImmutableUser.class; } @Override protected String expectedErrorMessage() { return "http://errorprone.info/bugpattern/Immutable"; } @Override protected DefectAnalysisEngine instantiateEngine() {
return new ErrorProneAnalysisEngine(ImmutableSet.of("Immutable"));
mostlymagic/hacking-java
3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // }
import org.junit.Test; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import static org.junit.Assert.assertThat;
package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { protected abstract Class<? extends WellBehaved> wellBehavedClass();
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java import org.junit.Test; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import static org.junit.Assert.assertThat; package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { protected abstract Class<? extends WellBehaved> wellBehavedClass();
protected abstract Class<? extends IllBehaved> illBehavedClass();
mostlymagic/hacking-java
3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // }
import org.junit.Test; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import static org.junit.Assert.assertThat;
package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { protected abstract Class<? extends WellBehaved> wellBehavedClass(); protected abstract Class<? extends IllBehaved> illBehavedClass(); @Test public void detectWellBehavedClass() {
// Path: x_common/compiler-testing/src/main/java/org/zalando/techtalks/hackingjava/common/compiler/CompilationResult.java // public final class CompilationResult { // // private final boolean success; // private final List<String> warnings; // private final List<String> errors; // // public boolean isSuccess() { // return success; // } // // public List<String> getWarnings() { // return Collections.unmodifiableList(warnings); // } // // public List<String> getErrors() { // return Collections.unmodifiableList(errors); // } // // public CompilationResult(final boolean success, final List<String> warnings, final List<String> errors) { // this.success = success; // this.warnings = new ArrayList<>(warnings); // this.errors = new ArrayList<>(errors); // } // // @Override // public int hashCode() { // return Objects.hash(success, warnings, errors); // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // final CompilationResult other = (CompilationResult) obj; // return Objects.equals(this.success, other.success) && Objects.equals(this.warnings, other.warnings) // && Objects.equals(this.errors, other.errors); // } // // @Override // public String toString() { // return "CompilationResult{" + "success=" + success + ", warnings=" + warnings + ", errors=" + errors + '}'; // } // } // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/IllBehaved.java // public interface IllBehaved {} // // Path: 3_defect-analysis/x_baseline/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/baseline/marker/WellBehaved.java // public interface WellBehaved { // } // Path: 3_defect-analysis/x_tests/src/main/java/org/zalando/techtalks/hackingjava/defectanalysis/tests/AbstractDefectDetectionTest.java import org.junit.Test; import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved; import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.WellBehaved; import static org.junit.Assert.assertThat; package org.zalando.techtalks.hackingjava.defectanalysis.tests; public abstract class AbstractDefectDetectionTest extends AbstractCompilerTest { protected abstract Class<? extends WellBehaved> wellBehavedClass(); protected abstract Class<? extends IllBehaved> illBehavedClass(); @Test public void detectWellBehavedClass() {
final CompilationResult result = engine.compile(sourceFileFor(wellBehavedClass()));
google/kiwi-solver
src/main/java/kiwi/trail/Trail.java
// Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // // Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import kiwi.util.Stack; import kiwi.util.StackInt;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; /** * {@code Trail} contains the chronological sequences of changes to undo. */ public class Trail { private long timestamp = 0L;
// Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // // Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/trail/Trail.java import kiwi.util.Stack; import kiwi.util.StackInt; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; /** * {@code Trail} contains the chronological sequences of changes to undo. */ public class Trail { private long timestamp = 0L;
private final Stack<Change> changes = new Stack<Change>();
google/kiwi-solver
src/main/java/kiwi/trail/Trail.java
// Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // // Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import kiwi.util.Stack; import kiwi.util.StackInt;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; /** * {@code Trail} contains the chronological sequences of changes to undo. */ public class Trail { private long timestamp = 0L; private final Stack<Change> changes = new Stack<Change>();
// Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // // Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/trail/Trail.java import kiwi.util.Stack; import kiwi.util.StackInt; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; /** * {@code Trail} contains the chronological sequences of changes to undo. */ public class Trail { private long timestamp = 0L; private final Stack<Change> changes = new Stack<Change>();
private final StackInt levels = new StackInt();
google/kiwi-solver
src/main/java/kiwi/trail/TrailedInt.java
// Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import kiwi.util.StackInt;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; public class TrailedInt implements Change { private final Trail trail;
// Path: src/main/java/kiwi/util/StackInt.java // public class StackInt { // // private int[] array = new int[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // public int top() { // return array[index - 1]; // } // // public void push(int elem) { // if (index == array.length) // growStack(); // array[index] = elem; // index++; // } // // public int pop() { // return array[--index]; // } // // private void growStack() { // int[] newArray = new int[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/trail/TrailedInt.java import kiwi.util.StackInt; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.trail; public class TrailedInt implements Change { private final Trail trail;
private final StackInt oldValues = new StackInt();
google/kiwi-solver
src/main/java/kiwi/variable/IntVar.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // }
import java.util.Arrays; import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; /** * Superclass to be instantiated by any integer variable. * * <p> * An {@code IntVar} basically represents the set of integer values that can be * assigned to the variable. A variable is assigned when its domain becomes a * singleton, i.e, it contains a single value. The variable cannot be empty. * Operation that directly impact the domain of the variable must return false * if the operation would have lead to an empty domain. * </p> * * <p> * An {@code IntVar} must be able to restore its state when a backtrack occurs. * </p> */ public abstract class IntVar { /** * A constant holding the minimum value an {@code IntVar} can be assigned to. */ public static final int MIN_VALUE = -1000000000; /** * A constant holding the maximum value an {@code IntVar} can be assigned to. */ public static final int MAX_VALUE = 1000000000; /** * Returns the {@code PropagationQueue} associated to this variable. * * @return the {@code PropagationQueue} of this {@code IntVar}. */
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // Path: src/main/java/kiwi/variable/IntVar.java import java.util.Arrays; import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; /** * Superclass to be instantiated by any integer variable. * * <p> * An {@code IntVar} basically represents the set of integer values that can be * assigned to the variable. A variable is assigned when its domain becomes a * singleton, i.e, it contains a single value. The variable cannot be empty. * Operation that directly impact the domain of the variable must return false * if the operation would have lead to an empty domain. * </p> * * <p> * An {@code IntVar} must be able to restore its state when a backtrack occurs. * </p> */ public abstract class IntVar { /** * A constant holding the minimum value an {@code IntVar} can be assigned to. */ public static final int MIN_VALUE = -1000000000; /** * A constant holding the maximum value an {@code IntVar} can be assigned to. */ public static final int MAX_VALUE = 1000000000; /** * Returns the {@code PropagationQueue} associated to this variable. * * @return the {@code PropagationQueue} of this {@code IntVar}. */
public abstract PropagationQueue propagQueue();
google/kiwi-solver
src/main/java/kiwi/variable/IntVar.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // }
import java.util.Arrays; import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; /** * Superclass to be instantiated by any integer variable. * * <p> * An {@code IntVar} basically represents the set of integer values that can be * assigned to the variable. A variable is assigned when its domain becomes a * singleton, i.e, it contains a single value. The variable cannot be empty. * Operation that directly impact the domain of the variable must return false * if the operation would have lead to an empty domain. * </p> * * <p> * An {@code IntVar} must be able to restore its state when a backtrack occurs. * </p> */ public abstract class IntVar { /** * A constant holding the minimum value an {@code IntVar} can be assigned to. */ public static final int MIN_VALUE = -1000000000; /** * A constant holding the maximum value an {@code IntVar} can be assigned to. */ public static final int MAX_VALUE = 1000000000; /** * Returns the {@code PropagationQueue} associated to this variable. * * @return the {@code PropagationQueue} of this {@code IntVar}. */ public abstract PropagationQueue propagQueue(); /** * Returns the {@code Trail} associated to this {@code IntVar}. * * @return the {@code Trail} of this {@code IntVar}. */
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // Path: src/main/java/kiwi/variable/IntVar.java import java.util.Arrays; import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; /** * Superclass to be instantiated by any integer variable. * * <p> * An {@code IntVar} basically represents the set of integer values that can be * assigned to the variable. A variable is assigned when its domain becomes a * singleton, i.e, it contains a single value. The variable cannot be empty. * Operation that directly impact the domain of the variable must return false * if the operation would have lead to an empty domain. * </p> * * <p> * An {@code IntVar} must be able to restore its state when a backtrack occurs. * </p> */ public abstract class IntVar { /** * A constant holding the minimum value an {@code IntVar} can be assigned to. */ public static final int MIN_VALUE = -1000000000; /** * A constant holding the maximum value an {@code IntVar} can be assigned to. */ public static final int MAX_VALUE = 1000000000; /** * Returns the {@code PropagationQueue} associated to this variable. * * @return the {@code PropagationQueue} of this {@code IntVar}. */ public abstract PropagationQueue propagQueue(); /** * Returns the {@code Trail} associated to this {@code IntVar}. * * @return the {@code Trail} of this {@code IntVar}. */
public abstract Trail trail();
google/kiwi-solver
src/main/java/kiwi/variable/IntVarSingleton.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // }
import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; public class IntVarSingleton extends IntVar { private final PropagationQueue pQueue;
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // Path: src/main/java/kiwi/variable/IntVarSingleton.java import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.variable; public class IntVarSingleton extends IntVar { private final PropagationQueue pQueue;
private final Trail trail;
google/kiwi-solver
src/main/java/kiwi/variable/IntVarSingleton.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // }
import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail;
return this.value == value; } @Override public boolean assign(int value) { return this.value == value; } @Override public boolean remove(int value) { return this.value != value; } @Override public boolean updateMin(int value) { return this.value >= value; } @Override public boolean updateMax(int value) { return this.value <= value; } @Override public int copyDomain(int[] array) { array[0] = value; return 1; } @Override
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/propagation/Propagator.java // public abstract class Propagator { // // /** // * Indicates if the propagator is contained in the propagation queue. // */ // protected boolean enqueued; // // /** // * Indicates if the propagator might need to be called again just after // * propagation. // */ // protected boolean idempotent; // // /** // * Initializes the propagator and performs its initial propagation // * // * @return false if the propagation failed. // */ // public abstract boolean setup(); // // /** // * Propagates the last domain changes // * // * @return false if the propagation failed. // */ // public abstract boolean propagate(); // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // Path: src/main/java/kiwi/variable/IntVarSingleton.java import kiwi.propagation.PropagationQueue; import kiwi.propagation.Propagator; import kiwi.trail.Trail; return this.value == value; } @Override public boolean assign(int value) { return this.value == value; } @Override public boolean remove(int value) { return this.value != value; } @Override public boolean updateMin(int value) { return this.value >= value; } @Override public boolean updateMax(int value) { return this.value <= value; } @Override public int copyDomain(int[] array) { array[0] = value; return 1; } @Override
public void watchChange(Propagator propagator) {}
google/kiwi-solver
src/main/java/kiwi/search/DFSearch.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue;
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/search/DFSearch.java import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue;
private final Trail trail;
google/kiwi-solver
src/main/java/kiwi/search/DFSearch.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue; private final Trail trail;
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/search/DFSearch.java import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue; private final Trail trail;
private final Stack<Decision> decisions = new Stack<>();
google/kiwi-solver
src/main/java/kiwi/search/DFSearch.java
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // }
import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack;
/* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue; private final Trail trail; private final Stack<Decision> decisions = new Stack<>();
// Path: src/main/java/kiwi/propagation/PropagationQueue.java // public class PropagationQueue { // // // The propagation queue that contains all the propagators waiting for // // propagation. A propagator is considered to be enqueued only if its // // enqueued boolean is set to true. // private final ArrayDeque<Propagator> queue = new ArrayDeque<Propagator>(); // // /** // * Enqueues the propagator for propagation. // * // * <p> // * This method does nothing if the propagator is already enqueued. // * </p> // * // * @param propagator the propagator to be scheduled for propagation. // */ // public void enqueue(Propagator propagator) { // if (!propagator.enqueued) { // queue.addLast(propagator); // propagator.enqueued = true; // } // } // // /** // * Propagates the pending propagators. // * // * <p> // * Propagate all the propagators contained in the propagation queue. // * Propagation is likely to enqueue additional propagators while it is // * running. The propagation stops either when the queue is empty, or if a // * propagator failed (meaning that the problem is infeasible). // * </p> // * // * <p> // * The method returns true if the propagation succeeded or false if a // * propagator failed. The queue is empty at the end of the propagation and all // * propagators contained in the queue have their enqueued boolean set to // * false. // * </p> // * // * @return true if propagation succeeded, false otherwise. // */ // public boolean propagate() { // boolean feasible = true; // while (!queue.isEmpty()) { // Propagator propagator = queue.removeFirst(); // // Dequeue the propagator only if it is not idempotent. This allows the // // propagator to enqueue itself back in the propagation queue if it // // changed the domain of at least one of its variable. // propagator.enqueued = propagator.idempotent; // // Propagate only if the problem is still feasible. // feasible = feasible && propagator.propagate(); // // Dequeue the propagator no matter what. // propagator.enqueued = false; // } // return feasible; // } // } // // Path: src/main/java/kiwi/trail/Trail.java // public class Trail { // // private long timestamp = 0L; // // private final Stack<Change> changes = new Stack<Change>(); // private final StackInt levels = new StackInt(); // // public long getTimestamp() { // return timestamp; // } // // public void store(Change change) { // changes.push(change); // } // // public void newLevel() { // levels.push(changes.getSize()); // timestamp++; // } // // public void undoLevel() { // if (levels.getSize() > 0) // undoUntil(levels.pop()); // timestamp++; // } // // public void undoAll() { // while (levels.getSize() > 0) { // undoUntil(levels.pop()); // } // timestamp++; // } // // private void undoUntil(int size) { // while (changes.getSize() > size) { // changes.pop().undo(); // } // } // } // // Path: src/main/java/kiwi/util/Action.java // public interface Action { // public void execute(); // } // // Path: src/main/java/kiwi/util/Stack.java // public class Stack<T> { // // private Object[] array = new Object[16]; // // private int index = 0; // // public int getSize() { // return index; // } // // public boolean isEmpty() { // return index == 0; // } // // @SuppressWarnings("unchecked") // public T top() { // return (T) array[index - 1]; // } // // public void push(T elem) { // if (index == array.length) { // growStack(); // } // array[index] = (Object) elem; // index++; // } // // public void clear() { // while (index > 0) { // index--; // array[index] = null; // } // } // // @SuppressWarnings("unchecked") // public T pop() { // return (T) array[--index]; // } // // @SuppressWarnings("unchecked") // public void forEach(Consumer<T> c) { // for (int i = 0; i < index; i++) { // c.accept((T) array[i]); // } // } // // private void growStack() { // Object[] newArray = new Object[index * 2]; // System.arraycopy(array, 0, newArray, 0, index); // array = newArray; // } // } // Path: src/main/java/kiwi/search/DFSearch.java import java.util.function.Predicate; import kiwi.propagation.PropagationQueue; import kiwi.trail.Trail; import kiwi.util.Action; import kiwi.util.Stack; /* * Copyright 2016, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kiwi.search; public class DFSearch { private final PropagationQueue pQueue; private final Trail trail; private final Stack<Decision> decisions = new Stack<>();
private final Stack<Action> solutionActions = new Stack<>();
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/BootstrapperImpl.java
// Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.Bootstrapper; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class BootstrapperImpl implements Bootstrapper { private final String unauthorizedPlace;
// Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/BootstrapperImpl.java import javax.inject.Inject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.Bootstrapper; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class BootstrapperImpl implements Bootstrapper { private final String unauthorizedPlace;
private final CurrentUser currentUser;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/BootstrapperImpl.java
// Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.Bootstrapper; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class BootstrapperImpl implements Bootstrapper { private final String unauthorizedPlace; private final CurrentUser currentUser; private final PlaceManager placeManager; private final RestDispatch dispatcher;
// Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/BootstrapperImpl.java import javax.inject.Inject; import com.google.gwt.user.client.rpc.AsyncCallback; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.Bootstrapper; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class BootstrapperImpl implements Bootstrapper { private final String unauthorizedPlace; private final CurrentUser currentUser; private final PlaceManager placeManager; private final RestDispatch dispatcher;
private final UserService userService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.security; @Component public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); private final ObjectMapper mapper; @Autowired AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { this.mapper = messageConverter.getObjectMapper(); } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal();
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.security; @Component public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); private final ObjectMapper mapper; @Autowired AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { this.mapper = messageConverter.getObjectMapper(); } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal();
User user = userDetails.getUser();
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.security; @Service public class NuvolaUserDetailsService implements UserDetailsService {
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.security; @Service public class NuvolaUserDetailsService implements UserDetailsService {
private final UserService userService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.security; @Service public class NuvolaUserDetailsService implements UserDetailsService { private final UserService userService; @Autowired NuvolaUserDetailsService(UserService userService) { this.userService = userService; } public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.security; @Service public class NuvolaUserDetailsService implements UserDetailsService { private final UserService userService; @Autowired NuvolaUserDetailsService(UserService userService) { this.userService = userService; } public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByUsername(username);
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired
private NuvolaUserDetailsService userDetailsService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired
private HttpAuthenticationEntryPoint authenticationEntryPoint;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired
private AuthSuccessHandler authSuccessHandler;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired private AuthSuccessHandler authSuccessHandler; @Autowired
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired private AuthSuccessHandler authSuccessHandler; @Autowired
private AuthFailureHandler authFailureHandler;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired private AuthSuccessHandler authSuccessHandler; @Autowired private AuthFailureHandler authFailureHandler; @Autowired
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; package com.nuvola.myproject.server.spring; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) @ComponentScan(value = "com.nuvola.**.security") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ResourcePaths.User.ROOT + ResourcePaths.User.LOGIN; @Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired private AuthSuccessHandler authSuccessHandler; @Autowired private AuthFailureHandler authFailureHandler; @Autowired
private HttpLogoutSuccessHandler logoutSuccessHandler;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths;
return authenticationProvider; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/MyProject/*").permitAll() .antMatchers("/favicon.ico").permitAll() .antMatchers("/index.html").permitAll() .anyRequest().authenticated() .and() .authenticationProvider(authenticationProvider()) .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .formLogin() .permitAll() .loginProcessingUrl(LOGIN_PATH)
// Path: src/main/java/com/nuvola/myproject/server/security/AuthFailureHandler.java // @Component // public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { // @Override // public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, // AuthenticationException exception) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // // PrintWriter writer = response.getWriter(); // writer.write(exception.getMessage()); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/AuthSuccessHandler.java // @Component // public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { // private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class); // // private final ObjectMapper mapper; // // @Autowired // AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { // this.mapper = messageConverter.getObjectMapper(); // } // // @Override // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // response.setStatus(HttpServletResponse.SC_OK); // // NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); // User user = userDetails.getUser(); // userDetails.setUser(user); // // LOGGER.info(userDetails.getUsername() + " got is connected "); // // PrintWriter writer = response.getWriter(); // mapper.writeValue(writer, user); // writer.flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpAuthenticationEntryPoint.java // @Component // public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { // @Override // public void commence(HttpServletRequest request, HttpServletResponse response, // AuthenticationException authException) throws IOException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/HttpLogoutSuccessHandler.java // @Component // public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { // @Override // public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) // throws IOException { // response.setStatus(HttpServletResponse.SC_OK); // response.getWriter().flush(); // } // } // // Path: src/main/java/com/nuvola/myproject/server/security/NuvolaUserDetailsService.java // @Service // public class NuvolaUserDetailsService implements UserDetailsService { // private final UserService userService; // // @Autowired // NuvolaUserDetailsService(UserService userService) { // this.userService = userService; // } // // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userService.getUserByUsername(username); // if (user == null) { // throw new UsernameNotFoundException(username); // } // // List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // List<String> permissions = userService.getPermissions(user.getLogin()); // for (String permission : permissions) { // grantedAuthorities.add(new SimpleGrantedAuthority(permission)); // } // // return new NuvolaUserDetails(user, grantedAuthorities); // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public class Parameters { // public static final String USERNAME = "username"; // public static final String PASSWORD = "password"; // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public class ResourcePaths { // public class User { // public static final String ROOT = "/user"; // public static final String LOGIN = "/login"; // } // } // Path: src/main/java/com/nuvola/myproject/server/spring/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.nuvola.myproject.server.security.AuthFailureHandler; import com.nuvola.myproject.server.security.AuthSuccessHandler; import com.nuvola.myproject.server.security.HttpAuthenticationEntryPoint; import com.nuvola.myproject.server.security.HttpLogoutSuccessHandler; import com.nuvola.myproject.server.security.NuvolaUserDetailsService; import com.nuvola.myproject.shared.Parameters; import com.nuvola.myproject.shared.ResourcePaths; return authenticationProvider; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/MyProject/*").permitAll() .antMatchers("/favicon.ico").permitAll() .antMatchers("/index.html").permitAll() .anyRequest().authenticated() .and() .authenticationProvider(authenticationProvider()) .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .formLogin() .permitAll() .loginProcessingUrl(LOGIN_PATH)
.usernameParameter(Parameters.USERNAME)
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard
@NameToken(NameTokens.HOME)
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard @NameToken(NameTokens.HOME) interface MyProxy extends ProxyPlace<ApplicationPresenter> { } interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { void displayUserName(String userName); } private final RestDispatch dispatch;
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard @NameToken(NameTokens.HOME) interface MyProxy extends ProxyPlace<ApplicationPresenter> { } interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { void displayUserName(String userName); } private final RestDispatch dispatch;
private final UserService userService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard @NameToken(NameTokens.HOME) interface MyProxy extends ProxyPlace<ApplicationPresenter> { } interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { void displayUserName(String userName); } private final RestDispatch dispatch; private final UserService userService;
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.client.application; public class ApplicationPresenter extends Presenter<MyView, MyProxy> implements ApplicationUiHandlers { @ProxyStandard @NameToken(NameTokens.HOME) interface MyProxy extends ProxyPlace<ApplicationPresenter> { } interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { void displayUserName(String userName); } private final RestDispatch dispatch; private final UserService userService;
private final CurrentUser currentUser;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User;
this.userService = userService; this.currentUser = currentUser; this.placeManager = placeManager; getView().setUiHandlers(this); } @Override public void logout() { dispatch.execute(userService.logout(), new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert("Error during logging out the connected user..."); } @Override public void onSuccess(Void result) { PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.getLogin()) .build(); currentUser.setLoggedIn(false); placeManager.revealPlace(placeRequest); } }); } @Override protected void onReveal() { super.onReveal();
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // @ProxyStandard // @NameToken(NameTokens.HOME) // interface MyProxy extends ProxyPlace<ApplicationPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java // interface MyView extends View, HasUiHandlers<ApplicationUiHandlers> { // void displayUserName(String userName); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/client/application/ApplicationPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.application.ApplicationPresenter.MyProxy; import com.nuvola.myproject.client.application.ApplicationPresenter.MyView; import com.nuvola.myproject.client.security.CurrentUser; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.shared.model.User; this.userService = userService; this.currentUser = currentUser; this.placeManager = placeManager; getView().setUiHandlers(this); } @Override public void logout() { dispatch.execute(userService.logout(), new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert("Error during logging out the connected user..."); } @Override public void onSuccess(Void result) { PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.getLogin()) .build(); currentUser.setLoggedIn(false); placeManager.revealPlace(placeRequest); } }); } @Override protected void onReveal() { super.onReveal();
dispatch.execute(userService.getCurrentUser(), new AsyncCallback<User>() {
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/controller/UserController.java
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController {
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/server/controller/UserController.java import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController {
private final UserService userService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/controller/UserController.java
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private final UserService userService; @Autowired UserController(UserService userService) { this.userService = userService; }
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/server/controller/UserController.java import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private final UserService userService; @Autowired UserController(UserService userService) { this.userService = userService; }
@RequestMapping(value = LOGIN, method = GET)
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/controller/UserController.java
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private final UserService userService; @Autowired UserController(UserService userService) { this.userService = userService; } @RequestMapping(value = LOGIN, method = GET) @PermitAll ResponseEntity<Boolean> isCurrentUserLoggedIn() { return new ResponseEntity<>(userService.isCurrentUserLoggedIn(), OK); } @RequestMapping(method = GET)
// Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/server/controller/UserController.java import javax.annotation.security.PermitAll; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.ResponseEntity.ok; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.server.controller; @RestController @RequestMapping(value = ROOT, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private final UserService userService; @Autowired UserController(UserService userService) { this.userService = userService; } @RequestMapping(value = LOGIN, method = GET) @PermitAll ResponseEntity<Boolean> isCurrentUserLoggedIn() { return new ResponseEntity<>(userService.isCurrentUserLoggedIn(), OK); } @RequestMapping(method = GET)
ResponseEntity<User> getCurrentUser() {
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { }
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { }
@NameToken(NameTokens.LOGIN)
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { } @NameToken(NameTokens.LOGIN) @ProxyStandard @NoGatekeeper interface MyProxy extends ProxyPlace<LoginPresenter> { } private final PlaceManager placeManager; private final RestDispatch dispatcher;
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { } @NameToken(NameTokens.LOGIN) @ProxyStandard @NoGatekeeper interface MyProxy extends ProxyPlace<LoginPresenter> { } private final PlaceManager placeManager; private final RestDispatch dispatcher;
private final UserService userService;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { } @NameToken(NameTokens.LOGIN) @ProxyStandard @NoGatekeeper interface MyProxy extends ProxyPlace<LoginPresenter> { } private final PlaceManager placeManager; private final RestDispatch dispatcher; private final UserService userService;
// Path: src/main/java/com/nuvola/myproject/client/NameTokens.java // public class NameTokens { // public static final String HOME = "/home"; // public static final String LOGIN = "/login"; // // public static String getHome() { // return HOME; // } // // public static String getLogin() { // return LOGIN; // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // @NameToken(NameTokens.LOGIN) // @ProxyStandard // @NoGatekeeper // interface MyProxy extends ProxyPlace<LoginPresenter> { // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java // interface MyView extends View, HasUiHandlers<LoginUiHandlers> { // } // // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java // @Path(ROOT) // public interface UserService { // @POST // @Path(LOGIN) // @Consumes(APPLICATION_FORM_URLENCODED) // RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); // // @DELETE // @Path(LOGIN) // RestAction<Void> logout(); // // @GET // @Path(LOGIN) // RestAction<Boolean> isCurrentUserLoggedIn(); // // @GET // RestAction<User> getCurrentUser(); // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/login/LoginPresenter.java import javax.inject.Inject; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.dispatch.rest.client.RestDispatch; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.NoGatekeeper; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.nuvola.myproject.client.NameTokens; import com.nuvola.myproject.client.login.LoginPresenter.MyProxy; import com.nuvola.myproject.client.login.LoginPresenter.MyView; import com.nuvola.myproject.client.services.UserService; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client.login; public class LoginPresenter extends Presenter<MyView, MyProxy> implements LoginUiHandlers { interface MyView extends View, HasUiHandlers<LoginUiHandlers> { } @NameToken(NameTokens.LOGIN) @ProxyStandard @NoGatekeeper interface MyProxy extends ProxyPlace<LoginPresenter> { } private final PlaceManager placeManager; private final RestDispatch dispatcher; private final UserService userService;
private final CurrentUser currentUser;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/services/UserService.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST
@Path(LOGIN)
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/services/UserService.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED)
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED)
RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password);
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/services/UserService.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED)
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED)
RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password);
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/services/UserService.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user";
import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT;
package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED) RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); @DELETE @Path(LOGIN) RestAction<Void> logout(); @GET @Path(LOGIN) RestAction<Boolean> isCurrentUserLoggedIn(); @GET
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String PASSWORD = "password"; // // Path: src/main/java/com/nuvola/myproject/shared/Parameters.java // public static final String USERNAME = "username"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String LOGIN = "/login"; // // Path: src/main/java/com/nuvola/myproject/shared/ResourcePaths.java // public static final String ROOT = "/user"; // Path: src/main/java/com/nuvola/myproject/client/services/UserService.java import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.gwtplatform.dispatch.rest.shared.RestAction; import com.nuvola.myproject.shared.model.User; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static com.nuvola.myproject.shared.Parameters.PASSWORD; import static com.nuvola.myproject.shared.Parameters.USERNAME; import static com.nuvola.myproject.shared.ResourcePaths.User.LOGIN; import static com.nuvola.myproject.shared.ResourcePaths.User.ROOT; package com.nuvola.myproject.client.services; @Path(ROOT) public interface UserService { @POST @Path(LOGIN) @Consumes(APPLICATION_FORM_URLENCODED) RestAction<Void> login(@FormParam(USERNAME) String username, @FormParam(PASSWORD) String password); @DELETE @Path(LOGIN) RestAction<Void> logout(); @GET @Path(LOGIN) RestAction<Boolean> isCurrentUserLoggedIn(); @GET
RestAction<User> getCurrentUser();
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/service/impl/UserServiceImpl.java
// Path: src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java // @Component // public class LoggedInChecker { // public User getLoggedInUser() { // User user = null; // // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // if (authentication != null) { // Object principal = authentication.getPrincipal(); // // // principal can be "anonymousUser" (String) // if (principal instanceof NuvolaUserDetails) { // NuvolaUserDetails userDetails = (NuvolaUserDetails) principal; // user = userDetails.getUser(); // } // } // // return user; // } // } // // Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.security.LoggedInChecker; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.service.impl; @Service public class UserServiceImpl implements UserService { private final static String USER_TEST = "root";
// Path: src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java // @Component // public class LoggedInChecker { // public User getLoggedInUser() { // User user = null; // // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // if (authentication != null) { // Object principal = authentication.getPrincipal(); // // // principal can be "anonymousUser" (String) // if (principal instanceof NuvolaUserDetails) { // NuvolaUserDetails userDetails = (NuvolaUserDetails) principal; // user = userDetails.getUser(); // } // } // // return user; // } // } // // Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/service/impl/UserServiceImpl.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.security.LoggedInChecker; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.service.impl; @Service public class UserServiceImpl implements UserService { private final static String USER_TEST = "root";
private final LoggedInChecker loggedInChecker;
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/service/impl/UserServiceImpl.java
// Path: src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java // @Component // public class LoggedInChecker { // public User getLoggedInUser() { // User user = null; // // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // if (authentication != null) { // Object principal = authentication.getPrincipal(); // // // principal can be "anonymousUser" (String) // if (principal instanceof NuvolaUserDetails) { // NuvolaUserDetails userDetails = (NuvolaUserDetails) principal; // user = userDetails.getUser(); // } // } // // return user; // } // } // // Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.security.LoggedInChecker; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.service.impl; @Service public class UserServiceImpl implements UserService { private final static String USER_TEST = "root"; private final LoggedInChecker loggedInChecker; @Autowired UserServiceImpl(LoggedInChecker loggedInChecker) { this.loggedInChecker = loggedInChecker; } @Override
// Path: src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java // @Component // public class LoggedInChecker { // public User getLoggedInUser() { // User user = null; // // Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // if (authentication != null) { // Object principal = authentication.getPrincipal(); // // // principal can be "anonymousUser" (String) // if (principal instanceof NuvolaUserDetails) { // NuvolaUserDetails userDetails = (NuvolaUserDetails) principal; // user = userDetails.getUser(); // } // } // // return user; // } // } // // Path: src/main/java/com/nuvola/myproject/server/service/UserService.java // public interface UserService { // User getUserByUsername(String username); // // List<String> getPermissions(String username); // // User getCurrentUser(); // // Boolean isCurrentUserLoggedIn(); // } // // Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/service/impl/UserServiceImpl.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.stereotype.Service; import com.nuvola.myproject.server.security.LoggedInChecker; import com.nuvola.myproject.server.service.UserService; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.service.impl; @Service public class UserServiceImpl implements UserService { private final static String USER_TEST = "root"; private final LoggedInChecker loggedInChecker; @Autowired UserServiceImpl(LoggedInChecker loggedInChecker) { this.loggedInChecker = loggedInChecker; } @Override
public User getUserByUsername(String username) {
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.nuvola.myproject.shared.model.User;
package com.nuvola.myproject.server.security; @Component public class LoggedInChecker {
// Path: src/main/java/com/nuvola/myproject/shared/model/User.java // public class User { // private String login; // private String email; // private String firstName; // private String lastName; // private String password; // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/nuvola/myproject/server/security/LoggedInChecker.java import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.nuvola.myproject.shared.model.User; package com.nuvola.myproject.server.security; @Component public class LoggedInChecker {
public User getLoggedInUser() {
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/MyModule.java
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build());
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/MyModule.java import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build());
bind(CurrentUser.class).asEagerSingleton();
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/MyModule.java
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin());
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/MyModule.java import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin());
install(new ServiceModule());
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/MyModule.java
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin()); install(new ServiceModule());
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/MyModule.java import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin()); install(new ServiceModule());
install(new LoginModule());
imrabti/gwtp-spring-security
src/main/java/com/nuvola/myproject/client/MyModule.java
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // }
import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser;
package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin()); install(new ServiceModule()); install(new LoginModule());
// Path: src/main/java/com/nuvola/myproject/client/application/ApplicationModule.java // public class ApplicationModule extends AbstractPresenterModule { // @Override // protected void configure() { // bind(ApplicationPresenter.class).asEagerSingleton(); // bind(ApplicationPresenter.MyProxy.class).asEagerSingleton(); // bind(ApplicationPresenter.MyView.class).to(ApplicationView.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/login/LoginModule.java // public class LoginModule extends AbstractPresenterModule { // @Override // protected void configure() { // bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class, LoginView.class, // LoginPresenter.MyProxy.class); // } // } // // Path: src/main/java/com/nuvola/myproject/client/services/ServiceModule.java // public class ServiceModule extends AbstractGinModule { // @Override // protected void configure() { // install(new RestDispatchAsyncModule.Builder().build()); // } // // @Provides // @RestApplicationPath // String getApplicationPath() { // String baseUrl = GWT.getHostPageBaseURL(); // if (baseUrl.endsWith("/")) { // baseUrl = baseUrl.substring(0, baseUrl.length() - 1); // } // // return baseUrl; // } // } // // Path: src/main/java/com/nuvola/myproject/client/security/CurrentUser.java // public class CurrentUser { // private boolean loggedIn; // // public boolean isLoggedIn() { // return loggedIn; // } // // public void setLoggedIn(boolean loggedIn) { // this.loggedIn = loggedIn; // } // } // Path: src/main/java/com/nuvola/myproject/client/MyModule.java import com.google.gwt.inject.client.AbstractGinModule; import com.gwtplatform.mvp.client.annotations.DefaultPlace; import com.gwtplatform.mvp.client.annotations.ErrorPlace; import com.gwtplatform.mvp.client.annotations.UnauthorizedPlace; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.gwtplatform.mvp.client.proxy.DefaultPlaceManager; import com.gwtplatform.mvp.shared.proxy.RouteTokenFormatter; import com.nuvola.myproject.client.application.ApplicationModule; import com.nuvola.myproject.client.login.LoginModule; import com.nuvola.myproject.client.services.ServiceModule; import com.nuvola.myproject.client.security.CurrentUser; package com.nuvola.myproject.client; public class MyModule extends AbstractGinModule { @Override protected void configure() { install(new DefaultModule.Builder() .placeManager(DefaultPlaceManager.class) .tokenFormatter(RouteTokenFormatter.class) .build()); bind(CurrentUser.class).asEagerSingleton(); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.getHome()); bindConstant().annotatedWith(UnauthorizedPlace.class).to(NameTokens.getLogin()); install(new ServiceModule()); install(new LoginModule());
install(new ApplicationModule());
TheCount/jhilbert
src/main/java/jhilbert/expressions/Anonymiser.java
// Path: src/main/java/jhilbert/data/DVConstraints.java // public interface DVConstraints extends Iterable<Variable[]>, Serializable { // // /** // * Adds the specified variables to these <code>DVConstraints</code> // * by adding each non-diagonal pair. // * // * @param vars variables to be added. // * // * @throws DataException if the same variable appears twice in the // * specified array. // */ // public void add(Variable... vars) throws ConstraintException; // // /** // * Adds the entire DV constraints specified to these // * <code>DVConstraints</code>. // * // * @param dvConstraints DV constraints to add // */ // public void add(DVConstraints dvConstraints); // // /** // * Adds the cartesian product of the two specified sets of variables. // * // * @param varSet1 first set. // * @param varSet2 second set. // * // * @throws ConstraintException if the two sets are not disjoint. // */ // public void addProduct(Set<Variable> varSet1, Set<Variable> varSet2) throws ConstraintException; // // /** // * Checks whether the specified variable pair is contained in these // * <code>DVConstraints</code>. // * // * @param var1 first variable. // * @param var2 second variable. // * // * @return <code>true</code> if {<code>var1</code>, <code>var2</code>} // * is contained in these constraints, <code>false</code> // * otherwise. // */ // public boolean contains(Variable var1, Variable var2); // // /** // * Checks whther the specified DV constraints are contained in these // * DV constraints. // * // * @param dv other disjoint variable constraints. // * // * @return <code>true</code> if <code>dv</code> is contained in these // * constraints, <code>false</code> otherwise. // */ // public boolean contains(DVConstraints dv); // // /** // * Removes all variable pairs from these <code>DVConstraints</code> // * whose elements are not both contained in the specified set. // * // * @param varSet variable set to restrict these constraints to. // */ // public void restrict(Set<Variable> varSet); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // }
import java.util.Set; import jhilbert.data.DVConstraints; import jhilbert.data.Variable;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * An <code>Anonymiser</code> replaces {@link Variable}s in {@link Expression}s * with unnamed variables according to a replacement set which must be * provided to constructors of implementing classes. */ public interface Anonymiser { /** * Returns an anonymised version of the specified variable. * If the variable is not from the set of variables inherent to this * <code>Anonymiser</code>, a dummy variable will be returned. * Repeated calls to this method will result in consistent assignments * of variables. * * @param var variable to anonymise. * * @return the anonymised variable. */ public Variable anonymise(Variable var); /** * Anonymises the specified {@link DVConstraints} by calling * {@link #anonymise(Variable)} on each variable in the constraints. * * @param dv disjoint variable constraints. * * @return anonymised disjoint variable constraints. */
// Path: src/main/java/jhilbert/data/DVConstraints.java // public interface DVConstraints extends Iterable<Variable[]>, Serializable { // // /** // * Adds the specified variables to these <code>DVConstraints</code> // * by adding each non-diagonal pair. // * // * @param vars variables to be added. // * // * @throws DataException if the same variable appears twice in the // * specified array. // */ // public void add(Variable... vars) throws ConstraintException; // // /** // * Adds the entire DV constraints specified to these // * <code>DVConstraints</code>. // * // * @param dvConstraints DV constraints to add // */ // public void add(DVConstraints dvConstraints); // // /** // * Adds the cartesian product of the two specified sets of variables. // * // * @param varSet1 first set. // * @param varSet2 second set. // * // * @throws ConstraintException if the two sets are not disjoint. // */ // public void addProduct(Set<Variable> varSet1, Set<Variable> varSet2) throws ConstraintException; // // /** // * Checks whether the specified variable pair is contained in these // * <code>DVConstraints</code>. // * // * @param var1 first variable. // * @param var2 second variable. // * // * @return <code>true</code> if {<code>var1</code>, <code>var2</code>} // * is contained in these constraints, <code>false</code> // * otherwise. // */ // public boolean contains(Variable var1, Variable var2); // // /** // * Checks whther the specified DV constraints are contained in these // * DV constraints. // * // * @param dv other disjoint variable constraints. // * // * @return <code>true</code> if <code>dv</code> is contained in these // * constraints, <code>false</code> otherwise. // */ // public boolean contains(DVConstraints dv); // // /** // * Removes all variable pairs from these <code>DVConstraints</code> // * whose elements are not both contained in the specified set. // * // * @param varSet variable set to restrict these constraints to. // */ // public void restrict(Set<Variable> varSet); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // } // Path: src/main/java/jhilbert/expressions/Anonymiser.java import java.util.Set; import jhilbert.data.DVConstraints; import jhilbert.data.Variable; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * An <code>Anonymiser</code> replaces {@link Variable}s in {@link Expression}s * with unnamed variables according to a replacement set which must be * provided to constructors of implementing classes. */ public interface Anonymiser { /** * Returns an anonymised version of the specified variable. * If the variable is not from the set of variables inherent to this * <code>Anonymiser</code>, a dummy variable will be returned. * Repeated calls to this method will result in consistent assignments * of variables. * * @param var variable to anonymise. * * @return the anonymised variable. */ public Variable anonymise(Variable var); /** * Anonymises the specified {@link DVConstraints} by calling * {@link #anonymise(Variable)} on each variable in the constraints. * * @param dv disjoint variable constraints. * * @return anonymised disjoint variable constraints. */
public DVConstraints anonymise(DVConstraints dv);
TheCount/jhilbert
src/main/java/jhilbert/expressions/Matcher.java
// Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // }
import java.util.Map; import java.util.Set; import jhilbert.data.Variable;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * The <code>Matcher</code> interface makes concrete the different notions of * equality of expressions. * As such, a <code>Matcher</code> is solely concerned with * {@link Variable}/{@link Variable} comparisons. For * {@link Variable}/{@link Expression} comparisons, use a {@link Substituter}. * <p> * <code>Matcher</code> currently supports two notions of equality: * <ol> * <li><strong>Definition equivalence:</strong> When source and target * expression are unfolded to * {@link jhilbert.data.Functor#definitionDepth} zero, they are equal, * with no substitutions necessary whatsoever. * <li><strong>Variable equivalence:</strong> When source and target expression * can be made <em>definition equivalent</em> with a well-formed * translation of dummy variables. In order to avoid unsound replacement * of dummy variables with non-dummies, a blacklist of * not-to-dummy-assignable variables may be specified, causing an * exception to be thrown if such an assignment would be necessary. * </ol> * A single matcher can be used several times for simultaneous well-formed * matching. */ public interface Matcher { /** * Checks the source and the target expression for <em>definition * equivalence</em> as specified in the interface description. * * @param source source expression. * @param target target expression. * * @return <code>true</code> if <code>source</code> and * <code>target</code> are equal as specified, <code>false</code> * otherwise. */ public boolean checkDEquality(Expression source, Expression target); /** * Checks the source and the target expression for <em>variable * equivalence</em> as specified in the interface description. * The internal variable assignment map is updated accordingly. This * means it may be left in an undefined state if this method throws an * exception or returns <code>false</code>. * * @param source source expression. * @param target target expression. * @param blacklist list of not-to-dummy-assignable variables. * * @return <code>true</code> if <code>source</code> and * <code>target</code> are equal as specified, <code>false</code> * otherwise. * * @throws UnifyException if an otherwise well-formed assignment is * forbidden by the <code>blacklist</code>. */
// Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // } // Path: src/main/java/jhilbert/expressions/Matcher.java import java.util.Map; import java.util.Set; import jhilbert.data.Variable; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * The <code>Matcher</code> interface makes concrete the different notions of * equality of expressions. * As such, a <code>Matcher</code> is solely concerned with * {@link Variable}/{@link Variable} comparisons. For * {@link Variable}/{@link Expression} comparisons, use a {@link Substituter}. * <p> * <code>Matcher</code> currently supports two notions of equality: * <ol> * <li><strong>Definition equivalence:</strong> When source and target * expression are unfolded to * {@link jhilbert.data.Functor#definitionDepth} zero, they are equal, * with no substitutions necessary whatsoever. * <li><strong>Variable equivalence:</strong> When source and target expression * can be made <em>definition equivalent</em> with a well-formed * translation of dummy variables. In order to avoid unsound replacement * of dummy variables with non-dummies, a blacklist of * not-to-dummy-assignable variables may be specified, causing an * exception to be thrown if such an assignment would be necessary. * </ol> * A single matcher can be used several times for simultaneous well-formed * matching. */ public interface Matcher { /** * Checks the source and the target expression for <em>definition * equivalence</em> as specified in the interface description. * * @param source source expression. * @param target target expression. * * @return <code>true</code> if <code>source</code> and * <code>target</code> are equal as specified, <code>false</code> * otherwise. */ public boolean checkDEquality(Expression source, Expression target); /** * Checks the source and the target expression for <em>variable * equivalence</em> as specified in the interface description. * The internal variable assignment map is updated accordingly. This * means it may be left in an undefined state if this method throws an * exception or returns <code>false</code>. * * @param source source expression. * @param target target expression. * @param blacklist list of not-to-dummy-assignable variables. * * @return <code>true</code> if <code>source</code> and * <code>target</code> are equal as specified, <code>false</code> * otherwise. * * @throws UnifyException if an otherwise well-formed assignment is * forbidden by the <code>blacklist</code>. */
public boolean checkVEquality(Expression source, Expression target, Set<Variable> blacklist) throws UnifyException;
TheCount/jhilbert
src/main/java/jhilbert/scanners/impl/AbstractScanner.java
// Path: src/main/java/jhilbert/scanners/Scanner.java // public interface Scanner<E> { // // /** // * Resets the context of this scanner. // * Clears the context. That is, a call to {@link #getContextString} // * immediately following a call to this method will return an empty // * string. // */ // public void resetContext(); // // /** // * Returns the current context of this scanner. // * // * @return a String representation of the current context. // */ // public String getContextString(); // // /** // * Obtains the next token. // * // * @return the token, or <code>null</code> if there are no more tokens. // * // * @throws ScannerException if this scanner is unable to produce a // * token due to either an input problem or because of a syntax // * error in the input source. // * // * @see #putToken // */ // public E getToken() throws ScannerException; // // /** // * Put a token back. // * This method provides a means of &quot;unwinding&quot; the Scanner. // * The tokens put back are returned by {@link #getToken()} on a first // * in, last out basis. // * <p> // * The token to be put back must have been obtained by the thus far // * last call to to {@link #getToken}, or, if more than token is put back // * between calls to {@link #getToken}, the tokens must be provided in // * proper reverse order with no omissions. Otherwise the scanner may // * end up in an undefined state. // * // * @param token token to be put back. // * // * @see #getToken // */ // public void putToken(E token); // // } // // Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // }
import java.util.Stack; import jhilbert.scanners.Scanner; import jhilbert.scanners.ScannerException;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Basic implementation of the scanner interface. * This class implements methods to handle the putting back of tokens * as well as context manipulation. * * @param E token type. */ abstract class AbstractScanner<E> implements Scanner<E> { /** * Stack for putting back tokens. */ private final Stack<E> tokenStack; /** * Current scanner context. */ private final StringBuilder context; /** * Creates a new <code>AbstractScanner</code> with empty * context. */ protected AbstractScanner() { tokenStack = new Stack(); context = new StringBuilder(); } public void resetContext() { context.setLength(0); } /** * Appends the specified character to the current context. * * @param c character to append. */ protected void appendToContext(final char c) { context.append(c); } /** * Appends the specified character sequence to the current context. * * @param s character sequence to append. */ protected void appendToContext(final CharSequence s) { context.append(s); } public String getContextString() { return context.toString(); } /** * Obtains a new token. * This method is called by this class's implementation of the * {@link #getToken} method whenever all tokens which have been put * back are exhausted. * <p> * This method must be implemented by subclasses. * * @return the new token, or <code>null</code> if there are no more * tokens. * * @throws ScannerException for the same reasons as {@link #getToken} * does. * * @see #getToken */
// Path: src/main/java/jhilbert/scanners/Scanner.java // public interface Scanner<E> { // // /** // * Resets the context of this scanner. // * Clears the context. That is, a call to {@link #getContextString} // * immediately following a call to this method will return an empty // * string. // */ // public void resetContext(); // // /** // * Returns the current context of this scanner. // * // * @return a String representation of the current context. // */ // public String getContextString(); // // /** // * Obtains the next token. // * // * @return the token, or <code>null</code> if there are no more tokens. // * // * @throws ScannerException if this scanner is unable to produce a // * token due to either an input problem or because of a syntax // * error in the input source. // * // * @see #putToken // */ // public E getToken() throws ScannerException; // // /** // * Put a token back. // * This method provides a means of &quot;unwinding&quot; the Scanner. // * The tokens put back are returned by {@link #getToken()} on a first // * in, last out basis. // * <p> // * The token to be put back must have been obtained by the thus far // * last call to to {@link #getToken}, or, if more than token is put back // * between calls to {@link #getToken}, the tokens must be provided in // * proper reverse order with no omissions. Otherwise the scanner may // * end up in an undefined state. // * // * @param token token to be put back. // * // * @see #getToken // */ // public void putToken(E token); // // } // // Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // Path: src/main/java/jhilbert/scanners/impl/AbstractScanner.java import java.util.Stack; import jhilbert.scanners.Scanner; import jhilbert.scanners.ScannerException; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Basic implementation of the scanner interface. * This class implements methods to handle the putting back of tokens * as well as context manipulation. * * @param E token type. */ abstract class AbstractScanner<E> implements Scanner<E> { /** * Stack for putting back tokens. */ private final Stack<E> tokenStack; /** * Current scanner context. */ private final StringBuilder context; /** * Creates a new <code>AbstractScanner</code> with empty * context. */ protected AbstractScanner() { tokenStack = new Stack(); context = new StringBuilder(); } public void resetContext() { context.setLength(0); } /** * Appends the specified character to the current context. * * @param c character to append. */ protected void appendToContext(final char c) { context.append(c); } /** * Appends the specified character sequence to the current context. * * @param s character sequence to append. */ protected void appendToContext(final CharSequence s) { context.append(s); } public String getContextString() { return context.toString(); } /** * Obtains a new token. * This method is called by this class's implementation of the * {@link #getToken} method whenever all tokens which have been put * back are exhausted. * <p> * This method must be implemented by subclasses. * * @return the new token, or <code>null</code> if there are no more * tokens. * * @throws ScannerException for the same reasons as {@link #getToken} * does. * * @see #getToken */
protected abstract E getNewToken() throws ScannerException;
TheCount/jhilbert
src/main/java/jhilbert/expressions/Translator.java
// Path: src/main/java/jhilbert/data/Functor.java // public interface Functor extends Term { // // /** // * Returns an unmodifiable {@link List} of input {@link Kind}s. // * // * @return unmodifiable list of input kinds. // */ // public List<? extends Kind> getInputKinds(); // // /** // * Returns the definition depth of this <code>Functor</code>. // * This functor is convertible to a {@link Definition} if and only if // * the returned depth is greater than zero. // * // * @return the definition depth, a non-negative integer. // */ // public int definitionDepth(); // // public Namespace<? extends Functor> getNamespace(); // // public Functor getOriginalName(); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // }
import java.util.Map; import jhilbert.data.Functor; import jhilbert.data.Variable;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * Translates {@link Expression}s under given {@link jhilbert.data.Kind} and * {@link jhilbert.data.Functor} maps. Implementations must provide a * constructor which accepts these mappings. */ public interface Translator { /** * Translates the specified {@link Expression}. * This method does not check for translation sanity, such as matching * place count and kinds, checking for namespace sanity, etc. * * @param expression expression. * * @throws ExpressionException if a kind or a functor is encountered * for which no mapping exists. */ public Expression translate(final Expression expression) throws ExpressionException; /** * Translates the specified {@link Variable}. * Behaves just as {@link #translate(Expression)} with a * single-variable expression as argument. * * @param variable variable. * * @throws Expression if a kind or a functor is encountered * for which no mapping exists. */
// Path: src/main/java/jhilbert/data/Functor.java // public interface Functor extends Term { // // /** // * Returns an unmodifiable {@link List} of input {@link Kind}s. // * // * @return unmodifiable list of input kinds. // */ // public List<? extends Kind> getInputKinds(); // // /** // * Returns the definition depth of this <code>Functor</code>. // * This functor is convertible to a {@link Definition} if and only if // * the returned depth is greater than zero. // * // * @return the definition depth, a non-negative integer. // */ // public int definitionDepth(); // // public Namespace<? extends Functor> getNamespace(); // // public Functor getOriginalName(); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // } // Path: src/main/java/jhilbert/expressions/Translator.java import java.util.Map; import jhilbert.data.Functor; import jhilbert.data.Variable; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * Translates {@link Expression}s under given {@link jhilbert.data.Kind} and * {@link jhilbert.data.Functor} maps. Implementations must provide a * constructor which accepts these mappings. */ public interface Translator { /** * Translates the specified {@link Expression}. * This method does not check for translation sanity, such as matching * place count and kinds, checking for namespace sanity, etc. * * @param expression expression. * * @throws ExpressionException if a kind or a functor is encountered * for which no mapping exists. */ public Expression translate(final Expression expression) throws ExpressionException; /** * Translates the specified {@link Variable}. * Behaves just as {@link #translate(Expression)} with a * single-variable expression as argument. * * @param variable variable. * * @throws Expression if a kind or a functor is encountered * for which no mapping exists. */
public Variable translate(final Variable variable) throws ExpressionException;
TheCount/jhilbert
src/main/java/jhilbert/expressions/Translator.java
// Path: src/main/java/jhilbert/data/Functor.java // public interface Functor extends Term { // // /** // * Returns an unmodifiable {@link List} of input {@link Kind}s. // * // * @return unmodifiable list of input kinds. // */ // public List<? extends Kind> getInputKinds(); // // /** // * Returns the definition depth of this <code>Functor</code>. // * This functor is convertible to a {@link Definition} if and only if // * the returned depth is greater than zero. // * // * @return the definition depth, a non-negative integer. // */ // public int definitionDepth(); // // public Namespace<? extends Functor> getNamespace(); // // public Functor getOriginalName(); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // }
import java.util.Map; import jhilbert.data.Functor; import jhilbert.data.Variable;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * Translates {@link Expression}s under given {@link jhilbert.data.Kind} and * {@link jhilbert.data.Functor} maps. Implementations must provide a * constructor which accepts these mappings. */ public interface Translator { /** * Translates the specified {@link Expression}. * This method does not check for translation sanity, such as matching * place count and kinds, checking for namespace sanity, etc. * * @param expression expression. * * @throws ExpressionException if a kind or a functor is encountered * for which no mapping exists. */ public Expression translate(final Expression expression) throws ExpressionException; /** * Translates the specified {@link Variable}. * Behaves just as {@link #translate(Expression)} with a * single-variable expression as argument. * * @param variable variable. * * @throws Expression if a kind or a functor is encountered * for which no mapping exists. */ public Variable translate(final Variable variable) throws ExpressionException; /** * Returns the functor map provided to this <code>Translator</code>. * * @return the functor map. */
// Path: src/main/java/jhilbert/data/Functor.java // public interface Functor extends Term { // // /** // * Returns an unmodifiable {@link List} of input {@link Kind}s. // * // * @return unmodifiable list of input kinds. // */ // public List<? extends Kind> getInputKinds(); // // /** // * Returns the definition depth of this <code>Functor</code>. // * This functor is convertible to a {@link Definition} if and only if // * the returned depth is greater than zero. // * // * @return the definition depth, a non-negative integer. // */ // public int definitionDepth(); // // public Namespace<? extends Functor> getNamespace(); // // public Functor getOriginalName(); // // } // // Path: src/main/java/jhilbert/data/Variable.java // public interface Variable extends Symbol, Term { // // /** // * Reimplemented from {@link Name#getOriginalName}, this method always // * returns <code>null</code> as variables are always local. // * // * @return <code>null</code>. // */ // public Name getOriginalName(); // // /** // * Returns whether this <code>Variable</code> is a dummy variable. // * // * @return <code>true</code> if this <code>Variable</code> is a dummy // * variable, <code>false</code> otherwise. // */ // public boolean isDummy(); // // } // Path: src/main/java/jhilbert/expressions/Translator.java import java.util.Map; import jhilbert.data.Functor; import jhilbert.data.Variable; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * Translates {@link Expression}s under given {@link jhilbert.data.Kind} and * {@link jhilbert.data.Functor} maps. Implementations must provide a * constructor which accepts these mappings. */ public interface Translator { /** * Translates the specified {@link Expression}. * This method does not check for translation sanity, such as matching * place count and kinds, checking for namespace sanity, etc. * * @param expression expression. * * @throws ExpressionException if a kind or a functor is encountered * for which no mapping exists. */ public Expression translate(final Expression expression) throws ExpressionException; /** * Translates the specified {@link Variable}. * Behaves just as {@link #translate(Expression)} with a * single-variable expression as argument. * * @param variable variable. * * @throws Expression if a kind or a functor is encountered * for which no mapping exists. */ public Variable translate(final Variable variable) throws ExpressionException; /** * Returns the functor map provided to this <code>Translator</code>. * * @return the functor map. */
public Map<Functor, Functor> getFunctorMap();
TheCount/jhilbert
src/main/java/jhilbert/data/Statement.java
// Path: src/main/java/jhilbert/expressions/Expression.java // public interface Expression extends TreeNode<Term>, Serializable { // // /** // * Returns the kind of this <code>Expression</code>. // * // * @return kind of this expression. // */ // public Kind getKind(); // // /** // * Returns the sub-expressions of this <code>Expression</code> in // * proper order. // * // * @return list of subexpressions. // */ // public List<Expression> getChildren(); // // /** // * Returns the {@link DVConstraints} applicable to this // * <code>Expression</code>. // * // * @return applicable DVConstraints // * // * @throws ConstraintException if the DV constraints cannot be met // * ever. // */ // public DVConstraints dvConstraints() throws ConstraintException; // // /** // * Returns the {@link Variable}s occurring in this // * <code>Expression</code>, in order of first appearance. // * // * @return variables occurring in this expression. // */ // public LinkedHashSet<Variable> variables(); // // /** // * Returns the totally unfolded version of this expression. // * // * @return totally unfolded expression. // */ // public Expression totalUnfold(); // // }
import java.util.List; import jhilbert.expressions.Expression;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.data; /** * A statement. */ public interface Statement extends Symbol { /** * Returns the {@link DVConstraints} of this <code>Statement</code>. * * @return disjoint variable constraints. */ public DVConstraints getDVConstraints(); /** * Returns the hypotheses of this <code>Statement</code>. * * @return hypotheses of this statement. */
// Path: src/main/java/jhilbert/expressions/Expression.java // public interface Expression extends TreeNode<Term>, Serializable { // // /** // * Returns the kind of this <code>Expression</code>. // * // * @return kind of this expression. // */ // public Kind getKind(); // // /** // * Returns the sub-expressions of this <code>Expression</code> in // * proper order. // * // * @return list of subexpressions. // */ // public List<Expression> getChildren(); // // /** // * Returns the {@link DVConstraints} applicable to this // * <code>Expression</code>. // * // * @return applicable DVConstraints // * // * @throws ConstraintException if the DV constraints cannot be met // * ever. // */ // public DVConstraints dvConstraints() throws ConstraintException; // // /** // * Returns the {@link Variable}s occurring in this // * <code>Expression</code>, in order of first appearance. // * // * @return variables occurring in this expression. // */ // public LinkedHashSet<Variable> variables(); // // /** // * Returns the totally unfolded version of this expression. // * // * @return totally unfolded expression. // */ // public Expression totalUnfold(); // // } // Path: src/main/java/jhilbert/data/Statement.java import java.util.List; import jhilbert.expressions.Expression; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.data; /** * A statement. */ public interface Statement extends Symbol { /** * Returns the {@link DVConstraints} of this <code>Statement</code>. * * @return disjoint variable constraints. */ public DVConstraints getDVConstraints(); /** * Returns the hypotheses of this <code>Statement</code>. * * @return hypotheses of this statement. */
public List<Expression> getHypotheses();
TheCount/jhilbert
src/main/java/jhilbert/scanners/impl/ScannerFactory.java
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // } // // Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // }
import jhilbert.scanners.ScannerException; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import jhilbert.data.Module;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Scanner factory for this implementation. */ public final class ScannerFactory extends jhilbert.scanners.ScannerFactory { // instances are default-constructed. public @Override StreamTokenFeed createTokenFeed(final InputStream in) throws ScannerException { assert (in != null): "Supplied input stream is null"; return new StreamTokenFeed(in); } public @Override @Deprecated IOTokenFeed createTokenFeed(final BufferedReader in, final BufferedWriter out) { assert (in != null): "Supplied input reader is null"; assert (out != null): "Supplied output writer is null"; return new IOTokenFeed(in, out); }
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // } // // Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // Path: src/main/java/jhilbert/scanners/impl/ScannerFactory.java import jhilbert.scanners.ScannerException; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import jhilbert.data.Module; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Scanner factory for this implementation. */ public final class ScannerFactory extends jhilbert.scanners.ScannerFactory { // instances are default-constructed. public @Override StreamTokenFeed createTokenFeed(final InputStream in) throws ScannerException { assert (in != null): "Supplied input stream is null"; return new StreamTokenFeed(in); } public @Override @Deprecated IOTokenFeed createTokenFeed(final BufferedReader in, final BufferedWriter out) { assert (in != null): "Supplied input reader is null"; assert (out != null): "Supplied output writer is null"; return new IOTokenFeed(in, out); }
public @Override MediaWikiTokenFeed createTokenFeed(final InputStream in, final BufferedOutputStream out, final Module module) {
TheCount/jhilbert
src/test/java/jhilbert/MainTest.java
// Path: src/main/java/jhilbert/Main.java // public static boolean isInterface(String fileName) { // return fileName.contains("Interface/") || // fileName.contains("User interface/"); // } // // Path: src/main/java/jhilbert/Main.java // public static boolean isProofModule(String fileName) { // return fileName.contains("Main/") || // fileName.contains("User module/"); // }
import junit.framework.TestCase; import static jhilbert.Main.isInterface; import static jhilbert.Main.isProofModule;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert; public class MainTest extends TestCase { public void testIsInterface() throws Exception {
// Path: src/main/java/jhilbert/Main.java // public static boolean isInterface(String fileName) { // return fileName.contains("Interface/") || // fileName.contains("User interface/"); // } // // Path: src/main/java/jhilbert/Main.java // public static boolean isProofModule(String fileName) { // return fileName.contains("Main/") || // fileName.contains("User module/"); // } // Path: src/test/java/jhilbert/MainTest.java import junit.framework.TestCase; import static jhilbert.Main.isInterface; import static jhilbert.Main.isProofModule; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert; public class MainTest extends TestCase { public void testIsInterface() throws Exception {
assertTrue(isInterface("/foo/bar/Interface/Logic"));
TheCount/jhilbert
src/test/java/jhilbert/MainTest.java
// Path: src/main/java/jhilbert/Main.java // public static boolean isInterface(String fileName) { // return fileName.contains("Interface/") || // fileName.contains("User interface/"); // } // // Path: src/main/java/jhilbert/Main.java // public static boolean isProofModule(String fileName) { // return fileName.contains("Main/") || // fileName.contains("User module/"); // }
import junit.framework.TestCase; import static jhilbert.Main.isInterface; import static jhilbert.Main.isProofModule;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert; public class MainTest extends TestCase { public void testIsInterface() throws Exception { assertTrue(isInterface("/foo/bar/Interface/Logic")); assertTrue(isInterface("Interface/L/o/g/Logic")); assertFalse(isInterface("Main/L/o/g/Logic")); assertTrue(isInterface("User interface/J/o/e/Joe\u001cSandbox")); } public void testIsModule() throws Exception {
// Path: src/main/java/jhilbert/Main.java // public static boolean isInterface(String fileName) { // return fileName.contains("Interface/") || // fileName.contains("User interface/"); // } // // Path: src/main/java/jhilbert/Main.java // public static boolean isProofModule(String fileName) { // return fileName.contains("Main/") || // fileName.contains("User module/"); // } // Path: src/test/java/jhilbert/MainTest.java import junit.framework.TestCase; import static jhilbert.Main.isInterface; import static jhilbert.Main.isProofModule; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert; public class MainTest extends TestCase { public void testIsInterface() throws Exception { assertTrue(isInterface("/foo/bar/Interface/Logic")); assertTrue(isInterface("Interface/L/o/g/Logic")); assertFalse(isInterface("Main/L/o/g/Logic")); assertTrue(isInterface("User interface/J/o/e/Joe\u001cSandbox")); } public void testIsModule() throws Exception {
assertTrue(isProofModule("Main/L/o/g/Logic"));
TheCount/jhilbert
src/main/java/jhilbert/scanners/ScannerFactory.java
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // }
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import jhilbert.data.Module;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners; /** * A factory class for creating {@link TokenFeed}s. */ public abstract class ScannerFactory { /** * Instance. */ private static final ScannerFactory instance = new jhilbert.scanners.impl.ScannerFactory(); /** * Returns a <code>ScannerFactory</code> instance. * * @return a <code>ScannerFactory</code> instance. */ public static ScannerFactory getInstance() { return instance; } /** * Creates a new {@link TokenFeed} from the specified * {@link java.io.InputStream}. * * @param in input stream to create the <code>TokenFeed</code> from. * * @return the new <code>TokenFeed</code>. * * @throws ScannerException if the scanner cannot be created. */ public abstract TokenFeed createTokenFeed(InputStream in) throws ScannerException; /** * Creates a new {@link TokenFeed} from the specified input and * output buffers (for server operation). * FIXME: not needed now that c/s conversation is binary * * @param in input reader. * @param out output writer. */ public @Deprecated abstract TokenFeed createTokenFeed(BufferedReader in, BufferedWriter out); /** * Creates a new {@link TokenFeed} from the specified input and output * streams (for server operation). * * @param in input stream. * @param out buffered output stream. * @param module module being built. */
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // } // Path: src/main/java/jhilbert/scanners/ScannerFactory.java import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import jhilbert.data.Module; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners; /** * A factory class for creating {@link TokenFeed}s. */ public abstract class ScannerFactory { /** * Instance. */ private static final ScannerFactory instance = new jhilbert.scanners.impl.ScannerFactory(); /** * Returns a <code>ScannerFactory</code> instance. * * @return a <code>ScannerFactory</code> instance. */ public static ScannerFactory getInstance() { return instance; } /** * Creates a new {@link TokenFeed} from the specified * {@link java.io.InputStream}. * * @param in input stream to create the <code>TokenFeed</code> from. * * @return the new <code>TokenFeed</code>. * * @throws ScannerException if the scanner cannot be created. */ public abstract TokenFeed createTokenFeed(InputStream in) throws ScannerException; /** * Creates a new {@link TokenFeed} from the specified input and * output buffers (for server operation). * FIXME: not needed now that c/s conversation is binary * * @param in input reader. * @param out output writer. */ public @Deprecated abstract TokenFeed createTokenFeed(BufferedReader in, BufferedWriter out); /** * Creates a new {@link TokenFeed} from the specified input and output * streams (for server operation). * * @param in input stream. * @param out buffered output stream. * @param module module being built. */
public abstract TokenFeed createTokenFeed(InputStream in, BufferedOutputStream out, Module module);
TheCount/jhilbert
src/main/java/jhilbert/storage/ModuleID.java
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // }
import jhilbert.data.Module;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.storage; /** * Class which encapsulates the two pieces of data to uniquely identify a * {@link Module}: its locator and its revision number. */ final class ModuleID { /** * Locator. */ private final String locator; /** * Revision number. */ private final long version; /** * Creates a new <code>ModuleID</code> with the specified locator and * the specified revision. * * @param locator module locator. * @param version revision number. */ public ModuleID(final String locator, final long version) { assert (locator != null): "Supplied locator is null"; assert (version >= -1): "Invalid revision number supplied"; this.locator = locator; this.version = version; } /** * Creates a new <code>ModuleID</code> from the specified * {@link Module}, using the module name as locator. * * @param module module. */
// Path: src/main/java/jhilbert/data/Module.java // public interface Module extends Serializable { // // /** // * Obtains the name of the module. // * The name of the module is an identifier for the interface in which // * the data are defined. If this module contains the data of the // * current main proof module, the empty string is returned. // * // * @return module name, or the empty string, if this is the main proof // * module. // */ // public String getName(); // // /** // * Obtains the revision number of the current module. // * Revision numbers allow for simple versioning of interfaces. They are // * useful for a storage backend to decide where the data goes. // * // * @return the revision number of this module, which must be a // * non-negative integer, or <code>-1</code> if this module is not // * versioned. // */ // public long getRevision(); // // /** // * Obtains the parameters of this module in proper order. // * // * @return parameters of this module. // */ // public List<Parameter> getParameters(); // // /** // * Obtains the parameter by the specified name. // * // * @param name name of parameter. // * // * @return parameter with name <code>name</code>, or <code>null</code> // * if no such parameter exists in this module. // */ // public Parameter getParameter(String name); // // /** // * Adds the specified {@link Parameter} to this <code>Module</code>. // * // * @param parameter parameter to be added. // * // * @throws DataException if a parameter with the same name as // * <code>parameter</code> has previously been added. // */ // public void addParameter(Parameter parameter) throws DataException; // // /** // * Obtains the {@link Namespace} containing the {@link Kind}s defined // * in this module. // * // * @return the kind namespace of this module. // */ // public Namespace<? extends Kind> getKindNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Symbol}s defined // * in this module. // * // * @return the symbol namespace of this module. // */ // public Namespace<? extends Symbol> getSymbolNamespace(); // // /** // * Obtains the {@link Namespace} containing the {@link Functor}s // * defined in this module. // * // * @return the functor namespace of this module. // */ // public Namespace<? extends Functor> getFunctorNamespace(); // // public boolean isProofModule(); // // } // Path: src/main/java/jhilbert/storage/ModuleID.java import jhilbert.data.Module; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.storage; /** * Class which encapsulates the two pieces of data to uniquely identify a * {@link Module}: its locator and its revision number. */ final class ModuleID { /** * Locator. */ private final String locator; /** * Revision number. */ private final long version; /** * Creates a new <code>ModuleID</code> with the specified locator and * the specified revision. * * @param locator module locator. * @param version revision number. */ public ModuleID(final String locator, final long version) { assert (locator != null): "Supplied locator is null"; assert (version >= -1): "Invalid revision number supplied"; this.locator = locator; this.version = version; } /** * Creates a new <code>ModuleID</code> from the specified * {@link Module}, using the module name as locator. * * @param module module. */
public ModuleID(final Module module) {
TheCount/jhilbert
src/main/java/jhilbert/data/Definition.java
// Path: src/main/java/jhilbert/expressions/Expression.java // public interface Expression extends TreeNode<Term>, Serializable { // // /** // * Returns the kind of this <code>Expression</code>. // * // * @return kind of this expression. // */ // public Kind getKind(); // // /** // * Returns the sub-expressions of this <code>Expression</code> in // * proper order. // * // * @return list of subexpressions. // */ // public List<Expression> getChildren(); // // /** // * Returns the {@link DVConstraints} applicable to this // * <code>Expression</code>. // * // * @return applicable DVConstraints // * // * @throws ConstraintException if the DV constraints cannot be met // * ever. // */ // public DVConstraints dvConstraints() throws ConstraintException; // // /** // * Returns the {@link Variable}s occurring in this // * <code>Expression</code>, in order of first appearance. // * // * @return variables occurring in this expression. // */ // public LinkedHashSet<Variable> variables(); // // /** // * Returns the totally unfolded version of this expression. // * // * @return totally unfolded expression. // */ // public Expression totalUnfold(); // // }
import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import jhilbert.expressions.Expression;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.data; /** * A <code>Definition</code>. * See the JHilbert specification for more information. */ public interface Definition extends Functor { /** * Returns the argument variables of this <code>Definition</code>. * * @return argument variables of this definition. */ public LinkedHashSet<Variable> getArguments(); /** * Returns the definiens of this <code>Definition</code>. * The definiens is an {@link Expression} consisting either of a single * {@link Variable}, or its leading {@link Functor} has a definition * depth smaller than this definition. * <p> * Any variables occurring in the definiens, but not in the set * returned by {@link #getArguments} are dummy variables. * * @return the definiens. * * @see Variable#isDummy */
// Path: src/main/java/jhilbert/expressions/Expression.java // public interface Expression extends TreeNode<Term>, Serializable { // // /** // * Returns the kind of this <code>Expression</code>. // * // * @return kind of this expression. // */ // public Kind getKind(); // // /** // * Returns the sub-expressions of this <code>Expression</code> in // * proper order. // * // * @return list of subexpressions. // */ // public List<Expression> getChildren(); // // /** // * Returns the {@link DVConstraints} applicable to this // * <code>Expression</code>. // * // * @return applicable DVConstraints // * // * @throws ConstraintException if the DV constraints cannot be met // * ever. // */ // public DVConstraints dvConstraints() throws ConstraintException; // // /** // * Returns the {@link Variable}s occurring in this // * <code>Expression</code>, in order of first appearance. // * // * @return variables occurring in this expression. // */ // public LinkedHashSet<Variable> variables(); // // /** // * Returns the totally unfolded version of this expression. // * // * @return totally unfolded expression. // */ // public Expression totalUnfold(); // // } // Path: src/main/java/jhilbert/data/Definition.java import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import jhilbert.expressions.Expression; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.data; /** * A <code>Definition</code>. * See the JHilbert specification for more information. */ public interface Definition extends Functor { /** * Returns the argument variables of this <code>Definition</code>. * * @return argument variables of this definition. */ public LinkedHashSet<Variable> getArguments(); /** * Returns the definiens of this <code>Definition</code>. * The definiens is an {@link Expression} consisting either of a single * {@link Variable}, or its leading {@link Functor} has a definition * depth smaller than this definition. * <p> * Any variables occurring in the definiens, but not in the set * returned by {@link #getArguments} are dummy variables. * * @return the definiens. * * @see Variable#isDummy */
public Expression getDefiniens();
TheCount/jhilbert
src/main/java/jhilbert/scanners/impl/StreamTokenFeed.java
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // // Path: src/main/java/jhilbert/scanners/Token.java // public interface Token { // // /** // * Token classes. // */ // public static enum Class { // // /** // * Beginning of a LISP list. // */ // BEGIN_EXP, // // /** // * End of a LISP list. // */ // END_EXP, // // /** // * Atomic LISP symbolic expression. // */ // ATOM // // } // // /** // * Valid ATOM tokens. // */ // public static final Pattern VALID_ATOM // = Pattern.compile("[^\\p{Cn}\\p{Cf}\\p{Cc}\\p{Zs}\\p{Zl}\\p{Zp}\\t\\(\\)\\r\\n\\#]+"); // // /** // * Obtains a string representation of this token. // * // * @return string representation of this token. // */ // public String getTokenString(); // // /** // * Obtains the class of this token. // * // * @return class of this token. // */ // public Class getTokenClass(); // // }
import java.io.InputStream; import jhilbert.scanners.ScannerException; import jhilbert.scanners.Token; import org.apache.log4j.Logger;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * A token feed for stream I/O. */ final class StreamTokenFeed extends AbstractTokenFeed { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(StreamTokenFeed.class); /** * Character scanner. */ private final CharScanner charScanner; /** * Creates a new <code>StreamTokenFeed</code> for the specified input * stream. * * @param in input stream. * * @throws ScannerException if the underlying character scanner cannot * be set up. */
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // // Path: src/main/java/jhilbert/scanners/Token.java // public interface Token { // // /** // * Token classes. // */ // public static enum Class { // // /** // * Beginning of a LISP list. // */ // BEGIN_EXP, // // /** // * End of a LISP list. // */ // END_EXP, // // /** // * Atomic LISP symbolic expression. // */ // ATOM // // } // // /** // * Valid ATOM tokens. // */ // public static final Pattern VALID_ATOM // = Pattern.compile("[^\\p{Cn}\\p{Cf}\\p{Cc}\\p{Zs}\\p{Zl}\\p{Zp}\\t\\(\\)\\r\\n\\#]+"); // // /** // * Obtains a string representation of this token. // * // * @return string representation of this token. // */ // public String getTokenString(); // // /** // * Obtains the class of this token. // * // * @return class of this token. // */ // public Class getTokenClass(); // // } // Path: src/main/java/jhilbert/scanners/impl/StreamTokenFeed.java import java.io.InputStream; import jhilbert.scanners.ScannerException; import jhilbert.scanners.Token; import org.apache.log4j.Logger; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * A token feed for stream I/O. */ final class StreamTokenFeed extends AbstractTokenFeed { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(StreamTokenFeed.class); /** * Character scanner. */ private final CharScanner charScanner; /** * Creates a new <code>StreamTokenFeed</code> for the specified input * stream. * * @param in input stream. * * @throws ScannerException if the underlying character scanner cannot * be set up. */
StreamTokenFeed(final InputStream in) throws ScannerException {
TheCount/jhilbert
src/main/java/jhilbert/scanners/impl/StreamTokenFeed.java
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // // Path: src/main/java/jhilbert/scanners/Token.java // public interface Token { // // /** // * Token classes. // */ // public static enum Class { // // /** // * Beginning of a LISP list. // */ // BEGIN_EXP, // // /** // * End of a LISP list. // */ // END_EXP, // // /** // * Atomic LISP symbolic expression. // */ // ATOM // // } // // /** // * Valid ATOM tokens. // */ // public static final Pattern VALID_ATOM // = Pattern.compile("[^\\p{Cn}\\p{Cf}\\p{Cc}\\p{Zs}\\p{Zl}\\p{Zp}\\t\\(\\)\\r\\n\\#]+"); // // /** // * Obtains a string representation of this token. // * // * @return string representation of this token. // */ // public String getTokenString(); // // /** // * Obtains the class of this token. // * // * @return class of this token. // */ // public Class getTokenClass(); // // }
import java.io.InputStream; import jhilbert.scanners.ScannerException; import jhilbert.scanners.Token; import org.apache.log4j.Logger;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * A token feed for stream I/O. */ final class StreamTokenFeed extends AbstractTokenFeed { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(StreamTokenFeed.class); /** * Character scanner. */ private final CharScanner charScanner; /** * Creates a new <code>StreamTokenFeed</code> for the specified input * stream. * * @param in input stream. * * @throws ScannerException if the underlying character scanner cannot * be set up. */ StreamTokenFeed(final InputStream in) throws ScannerException { assert (in != null): "Supplied input stream is null"; try { charScanner = new CharScanner(in); } catch (ScannerException e) { logger.error("Unable to set up character scanner " + e.getScanner(), e); throw new ScannerException("Unable to set up character scanner", this, e); } }
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // // Path: src/main/java/jhilbert/scanners/Token.java // public interface Token { // // /** // * Token classes. // */ // public static enum Class { // // /** // * Beginning of a LISP list. // */ // BEGIN_EXP, // // /** // * End of a LISP list. // */ // END_EXP, // // /** // * Atomic LISP symbolic expression. // */ // ATOM // // } // // /** // * Valid ATOM tokens. // */ // public static final Pattern VALID_ATOM // = Pattern.compile("[^\\p{Cn}\\p{Cf}\\p{Cc}\\p{Zs}\\p{Zl}\\p{Zp}\\t\\(\\)\\r\\n\\#]+"); // // /** // * Obtains a string representation of this token. // * // * @return string representation of this token. // */ // public String getTokenString(); // // /** // * Obtains the class of this token. // * // * @return class of this token. // */ // public Class getTokenClass(); // // } // Path: src/main/java/jhilbert/scanners/impl/StreamTokenFeed.java import java.io.InputStream; import jhilbert.scanners.ScannerException; import jhilbert.scanners.Token; import org.apache.log4j.Logger; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * A token feed for stream I/O. */ final class StreamTokenFeed extends AbstractTokenFeed { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(StreamTokenFeed.class); /** * Character scanner. */ private final CharScanner charScanner; /** * Creates a new <code>StreamTokenFeed</code> for the specified input * stream. * * @param in input stream. * * @throws ScannerException if the underlying character scanner cannot * be set up. */ StreamTokenFeed(final InputStream in) throws ScannerException { assert (in != null): "Supplied input stream is null"; try { charScanner = new CharScanner(in); } catch (ScannerException e) { logger.error("Unable to set up character scanner " + e.getScanner(), e); throw new ScannerException("Unable to set up character scanner", this, e); } }
protected @Override Token getNewToken() throws ScannerException {
TheCount/jhilbert
src/main/java/jhilbert/scanners/impl/CharScanner.java
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // }
import jhilbert.scanners.ScannerException; import org.apache.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Scanner for characters. * This class is specially tuned for scanning LISP-like input, as LISP * comments (initiated by hashmarks) are stripped, and the {@link Char} class * automatically classifies LISP characters using {@link Char.Class}. */ class CharScanner extends AbstractScanner<Char> { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(CharScanner.class); /** * Input encoding. */ private static final String ENCODING = "UTF-8"; /** * Reader used as input source. */ private final Reader reader; /** * Creates a new <code>CharScanner</code> from the specified * {@link java.io.InputStream}. * * @param in input stream. * * @throws ScannerException if the {@link #ENCODING} is not supported. */
// Path: src/main/java/jhilbert/scanners/ScannerException.java // public class ScannerException extends JHilbertException { // // /** // * Scanner which created the exception. // */ // private final Scanner scanner; // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message. This constructor should only be used by a // * {@link Scanner}, which the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // */ // public ScannerException(final String message, final Scanner scanner) { // this(message, scanner, null); // } // // /** // * Creates a new <code>ScannerException</code> with the specified // * detail message and cause. // * This constructor should only be used by a {@link Scanner}, which // * the constructor is provided with. // * // * @param message detail message. // * @param scanner the scanner which created the exception. // * @param cause the cause. (A <code>null</code> value is permitted, and // * indicates that the cause is nonexistent or unknown.) // */ // public ScannerException(final String message, final Scanner scanner, final Throwable cause) { // super(message, cause); // this.scanner = scanner; // } // // /** // * Obtains the scanner which caused this exception. // * // * @return scanner which caused this exception. // */ // public final Scanner getScanner() { // return scanner; // } // // } // Path: src/main/java/jhilbert/scanners/impl/CharScanner.java import jhilbert.scanners.ScannerException; import org.apache.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; /* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.scanners.impl; /** * Scanner for characters. * This class is specially tuned for scanning LISP-like input, as LISP * comments (initiated by hashmarks) are stripped, and the {@link Char} class * automatically classifies LISP characters using {@link Char.Class}. */ class CharScanner extends AbstractScanner<Char> { /** * Logger for this class. */ private static final Logger logger = Logger.getLogger(CharScanner.class); /** * Input encoding. */ private static final String ENCODING = "UTF-8"; /** * Reader used as input source. */ private final Reader reader; /** * Creates a new <code>CharScanner</code> from the specified * {@link java.io.InputStream}. * * @param in input stream. * * @throws ScannerException if the {@link #ENCODING} is not supported. */
CharScanner(final InputStream in) throws ScannerException {
mslosarz/nextrtc-videochat-with-rest
src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConnectionRepository.java
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Connection.java // @Entity // @Table(name = "Connections") // public class Connection { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @JoinColumn(name = "connection_id") // private int id; // // @JoinColumn(name = "begin") // private Date begin; // // @JoinColumn(name = "closed") // private Date closed; // // @JoinColumn(name = "took") // private Long took; // // @OneToOne // @JoinColumn(name = "member_id") // private Member member; // // @ManyToOne // @JoinColumn(name = "conversation_id") // private Conversation conversation; // // @Deprecated // Connection() { // } // // Connection(Conversation conversation, Member member) { // this.conversation = conversation; // this.member = member; // begin = now().toDate(); // } // // public boolean isClosed() { // return closed != null; // } // // public void close() { // closed = now().toDate(); // took = new Interval(new DateTime(begin), new DateTime(closed)).toDurationMillis(); // } // // public boolean isFor(Conversation conversation) { // return new EqualsBuilder() // .append(this.conversation, conversation) // .isEquals(); // } // // public List<Member> getConversationMembers() { // return conversation.getConnections().stream().map(c -> c.member).collect(toList()); // } // // public Date getBegin() { // return begin; // } // // public long getDuration() { // if (took != null) { // return took; // } // return new Interval(new DateTime(begin), DateTime.now()).toDurationMillis(); // } // }
import org.nextrtc.examples.videochat_with_rest.domain.Connection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional;
package org.nextrtc.examples.videochat_with_rest.repo; @Repository @Transactional
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Connection.java // @Entity // @Table(name = "Connections") // public class Connection { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @JoinColumn(name = "connection_id") // private int id; // // @JoinColumn(name = "begin") // private Date begin; // // @JoinColumn(name = "closed") // private Date closed; // // @JoinColumn(name = "took") // private Long took; // // @OneToOne // @JoinColumn(name = "member_id") // private Member member; // // @ManyToOne // @JoinColumn(name = "conversation_id") // private Conversation conversation; // // @Deprecated // Connection() { // } // // Connection(Conversation conversation, Member member) { // this.conversation = conversation; // this.member = member; // begin = now().toDate(); // } // // public boolean isClosed() { // return closed != null; // } // // public void close() { // closed = now().toDate(); // took = new Interval(new DateTime(begin), new DateTime(closed)).toDurationMillis(); // } // // public boolean isFor(Conversation conversation) { // return new EqualsBuilder() // .append(this.conversation, conversation) // .isEquals(); // } // // public List<Member> getConversationMembers() { // return conversation.getConnections().stream().map(c -> c.member).collect(toList()); // } // // public Date getBegin() { // return begin; // } // // public long getDuration() { // if (took != null) { // return took; // } // return new Interval(new DateTime(begin), DateTime.now()).toDurationMillis(); // } // } // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConnectionRepository.java import org.nextrtc.examples.videochat_with_rest.domain.Connection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; package org.nextrtc.examples.videochat_with_rest.repo; @Repository @Transactional
public interface ConnectionRepository extends JpaRepository<Connection, Integer> {
mslosarz/nextrtc-videochat-with-rest
src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/Call.java // public class Call { // private List<String> otherRtcIds; // private Date started; // private long duration; // private boolean inProgress; // private List<String> otherNames; // // public Call(List<String> members, boolean inProgress, Date begin, long duration) { // this.otherRtcIds = members; // this.started = begin; // this.duration = TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS); // this.inProgress = inProgress; // } // // public List<String> getOtherRtcIds() { // return otherRtcIds; // } // // public Date getStarted() { // return started; // } // // public Long getDuration() { // return duration; // } // // public boolean isInProgress() { // return inProgress; // } // // public List<String> getOtherNames() { // return otherNames; // } // // public void setOtherNames(List<String> otherNames) { // this.otherNames = otherNames; // } // }
import org.joda.time.DateTime; import org.joda.time.Interval; import org.nextrtc.examples.videochat_with_rest.domain.history.Call; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.joda.time.DateTime.now;
public Member(String memberId, User user) { this.rtcId = memberId; this.user = user; this.connected = now().toDate(); } public void disconnectWithReason(Optional<String> reason) { disconnected = now().toDate(); reason.ifPresent(this::setLeftReason); } @Override public String toString() { return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected); } public void leaves(Conversation conversation) { if (connection.isFor(conversation)) { connection.close(); } } private void setLeftReason(String leftReason) { this.leftReason = leftReason; } public int startedBefore(Member p) { return connected.compareTo(p.connected); }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/Call.java // public class Call { // private List<String> otherRtcIds; // private Date started; // private long duration; // private boolean inProgress; // private List<String> otherNames; // // public Call(List<String> members, boolean inProgress, Date begin, long duration) { // this.otherRtcIds = members; // this.started = begin; // this.duration = TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS); // this.inProgress = inProgress; // } // // public List<String> getOtherRtcIds() { // return otherRtcIds; // } // // public Date getStarted() { // return started; // } // // public Long getDuration() { // return duration; // } // // public boolean isInProgress() { // return inProgress; // } // // public List<String> getOtherNames() { // return otherNames; // } // // public void setOtherNames(List<String> otherNames) { // this.otherNames = otherNames; // } // } // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java import org.joda.time.DateTime; import org.joda.time.Interval; import org.nextrtc.examples.videochat_with_rest.domain.history.Call; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.joda.time.DateTime.now; public Member(String memberId, User user) { this.rtcId = memberId; this.user = user; this.connected = now().toDate(); } public void disconnectWithReason(Optional<String> reason) { disconnected = now().toDate(); reason.ifPresent(this::setLeftReason); } @Override public String toString() { return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected); } public void leaves(Conversation conversation) { if (connection.isFor(conversation)) { connection.close(); } } private void setLeftReason(String leftReason) { this.leftReason = leftReason; } public int startedBefore(Member p) { return connected.compareTo(p.connected); }
public Call toCall() {
mslosarz/nextrtc-videochat-with-rest
src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java // @Entity // @Table(name = "Conversations") // public class Conversation { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "conversation_id") // private int id; // // @Column(name = "conversation_name") // private String conversationName; // // @Column(name = "created") // private Date created; // // @Column(name = "destroyed") // private Date destroyed; // // @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY) // private Set<Connection> connections; // // @Deprecated // Conversation() { // } // // public Conversation(String conversationName) { // this.conversationName = conversationName; // created = now().toDate(); // } // // @Override // public String toString() { // return String.format("(%s)[%s - %s]", conversationName, created, destroyed); // } // // public void destroy() { // destroyed = now().toDate(); // connections.stream() // .filter(Connection::isClosed) // .forEach(Connection::close); // } // // public void join(Member member) { // connections.add(new Connection(this, member)); // } // // public boolean equals(Object o) { // if (o == this) return true; // if (!(o instanceof Conversation)) return false; // final Conversation other = (Conversation) o; // return other.id == id; // } // // public int hashCode() { // return id; // } // // public Set<Connection> getConnections() { // return connections; // } // }
import org.nextrtc.examples.videochat_with_rest.domain.Conversation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional;
package org.nextrtc.examples.videochat_with_rest.repo; @Repository @Transactional
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java // @Entity // @Table(name = "Conversations") // public class Conversation { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "conversation_id") // private int id; // // @Column(name = "conversation_name") // private String conversationName; // // @Column(name = "created") // private Date created; // // @Column(name = "destroyed") // private Date destroyed; // // @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY) // private Set<Connection> connections; // // @Deprecated // Conversation() { // } // // public Conversation(String conversationName) { // this.conversationName = conversationName; // created = now().toDate(); // } // // @Override // public String toString() { // return String.format("(%s)[%s - %s]", conversationName, created, destroyed); // } // // public void destroy() { // destroyed = now().toDate(); // connections.stream() // .filter(Connection::isClosed) // .forEach(Connection::close); // } // // public void join(Member member) { // connections.add(new Connection(this, member)); // } // // public boolean equals(Object o) { // if (o == this) return true; // if (!(o instanceof Conversation)) return false; // final Conversation other = (Conversation) o; // return other.id == id; // } // // public int hashCode() { // return id; // } // // public Set<Connection> getConnections() { // return connections; // } // } // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java import org.nextrtc.examples.videochat_with_rest.domain.Conversation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; package org.nextrtc.examples.videochat_with_rest.repo; @Repository @Transactional
public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
mslosarz/nextrtc-videochat-with-rest
src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java // @Entity // @Table(name = "Users") // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private int id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "auth_provider_id") // private String authProviderId; // // @Column(name = "confirmation_key") // private String confirmationKey; // // @Column(name = "role") // private String role = "USER"; // // @Column(name = "email") // private String email; // // @Column(name = "confirmed") // private boolean confirmed = false; // // @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) // private Set<Member> conversationMember; // // @Deprecated // User() { // } // // public User(String username, String password, String email, String confirmationKey) { // this.username = username; // this.password = password; // this.email = email; // this.confirmationKey = confirmationKey; // } // // public User(String username, String email, String authProviderId) { // this.username = username; // this.email = email; // this.authProviderId = authProviderId; // confirmed = true; // } // // public String getUsername() { // return username; // } // // public void confirmEmail() { // confirmed = true; // } // // public History prepareHistory() { // return new History(conversationMember); // } // }
import org.nextrtc.examples.videochat_with_rest.domain.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.transaction.annotation.Transactional; import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.repo; @org.springframework.stereotype.Repository @RepositoryRestResource(exported = false) @Transactional
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java // @Entity // @Table(name = "Users") // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "user_id") // private int id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "auth_provider_id") // private String authProviderId; // // @Column(name = "confirmation_key") // private String confirmationKey; // // @Column(name = "role") // private String role = "USER"; // // @Column(name = "email") // private String email; // // @Column(name = "confirmed") // private boolean confirmed = false; // // @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) // private Set<Member> conversationMember; // // @Deprecated // User() { // } // // public User(String username, String password, String email, String confirmationKey) { // this.username = username; // this.password = password; // this.email = email; // this.confirmationKey = confirmationKey; // } // // public User(String username, String email, String authProviderId) { // this.username = username; // this.email = email; // this.authProviderId = authProviderId; // confirmed = true; // } // // public String getUsername() { // return username; // } // // public void confirmEmail() { // confirmed = true; // } // // public History prepareHistory() { // return new History(conversationMember); // } // } // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java import org.nextrtc.examples.videochat_with_rest.domain.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; package org.nextrtc.examples.videochat_with_rest.repo; @org.springframework.stereotype.Repository @RepositoryRestResource(exported = false) @Transactional
public interface UserRepository extends JpaRepository<User, Integer> {
mslosarz/nextrtc-videochat-with-rest
src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java // @Repository // @Transactional // public interface ConversationRepository extends JpaRepository<Conversation, Integer> { // // @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName") // Conversation getByConversationName(@Param("conversationName") String conversationName); // }
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package org.nextrtc.examples.videochat_with_rest.service; @Service @Transactional public class DestroyConversationService { @Autowired
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java // @Repository // @Transactional // public interface ConversationRepository extends JpaRepository<Conversation, Integer> { // // @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName") // Conversation getByConversationName(@Param("conversationName") String conversationName); // } // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package org.nextrtc.examples.videochat_with_rest.service; @Service @Transactional public class DestroyConversationService { @Autowired
private ConversationRepository conversationRepository;