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
be-hase/relumin
src/test/java/com/behase/relumin/controller/WebControllerTest.java
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock private UserService userService; @Before public void init() { Whitebox.setInternalState(controller, "buildNumber", "1"); Whitebox.setInternalState(controller, "collectStaticsInfoIntervalMillis", "1"); Whitebox.setInternalState(controller, "authEnabled", true); Whitebox.setInternalState(controller, "authAllowAnonymous", true); } @Test public void index_with_auth() throws Exception { ExtendedModelMap model = new ExtendedModelMap(); Authentication authentication = mock(Authentication.class);
// Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/model/Role.java // public class Role implements GrantedAuthority { // private static final long serialVersionUID = -4168971547041673977L; // // private String authority; // // private Role(String authority) { // this.authority = authority; // } // // @Override // public String getAuthority() { // return authority; // } // // public static final Role VIEWER = new Role("VIEWER"); // public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); // // public static Role get(String role) { // switch (role) { // case "VIEWER": // return VIEWER; // case "RELUMIN_ADMIN": // return RELUMIN_ADMIN; // default: // } // throw new InvalidParameterException(String.format("'%s' is invalid role.", role)); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/test/java/com/behase/relumin/controller/WebControllerTest.java import com.behase.relumin.model.LoginUser; import com.behase.relumin.model.Role; import com.behase.relumin.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import org.springframework.ui.ExtendedModelMap; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.behase.relumin.controller; @RunWith(MockitoJUnitRunner.class) public class WebControllerTest { @InjectMocks @Spy private WebController controller = new WebController(); @Mock private UserService userService; @Before public void init() { Whitebox.setInternalState(controller, "buildNumber", "1"); Whitebox.setInternalState(controller, "collectStaticsInfoIntervalMillis", "1"); Whitebox.setInternalState(controller, "authEnabled", true); Whitebox.setInternalState(controller, "authAllowAnonymous", true); } @Test public void index_with_auth() throws Exception { ExtendedModelMap model = new ExtendedModelMap(); Authentication authentication = mock(Authentication.class);
doReturn(new LoginUser("username", "displayName", "rawPassword", Role.VIEWER.getAuthority())).when(userService).getUser(anyString());
be-hase/relumin
src/main/java/com/behase/relumin/controller/MyErrorController.java
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.model.ErrorResponse; import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;
package com.behase.relumin.controller; @Controller public class MyErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @RequestMapping(ERROR_PATH) @ResponseBody
// Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/main/java/com/behase/relumin/controller/MyErrorController.java import com.behase.relumin.model.ErrorResponse; import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; package com.behase.relumin.controller; @Controller public class MyErrorController implements ErrorController { private static final String ERROR_PATH = "/error"; @RequestMapping(ERROR_PATH) @ResponseBody
public ResponseEntity<ErrorResponse> handleError(
be-hase/relumin
src/test/java/com/behase/relumin/support/RedisTribTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*;
package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class RedisTribTest { @Spy private RedisTrib tested = new RedisTrib(); @Mock private TribClusterNode tribClusterNode; @Mock private Jedis jedis; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { } @Test public void getCreateClusterParams_invalid_replica_then_throw_exception() {
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // } // Path: src/test/java/com/behase/relumin/support/RedisTribTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*; package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class RedisTribTest { @Spy private RedisTrib tested = new RedisTrib(); @Mock private TribClusterNode tribClusterNode; @Mock private Jedis jedis; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { } @Test public void getCreateClusterParams_invalid_replica_then_throw_exception() {
expectedEx.expect(InvalidParameterException.class);
be-hase/relumin
src/test/java/com/behase/relumin/support/RedisTribTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*;
package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class RedisTribTest { @Spy private RedisTrib tested = new RedisTrib(); @Mock private TribClusterNode tribClusterNode; @Mock private Jedis jedis; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { } @Test public void getCreateClusterParams_invalid_replica_then_throw_exception() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage(containsString("Replicas must be equal or longer than 0")); // when tested.getCreateClusterParams(-1, Sets.newHashSet()); } @Test public void getCreateClusterParams() { // given doNothing().when(tested).checkCreateParameters(); doNothing().when(tested).allocSlots(); doReturn(Lists.newArrayList()).when(tested).getCreateClusterParams(anyInt(), anySet()); // when
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // } // Path: src/test/java/com/behase/relumin/support/RedisTribTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*; package com.behase.relumin.support; @Slf4j @RunWith(MockitoJUnitRunner.class) public class RedisTribTest { @Spy private RedisTrib tested = new RedisTrib(); @Mock private TribClusterNode tribClusterNode; @Mock private Jedis jedis; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Rule public OutputCapture capture = new OutputCapture(); @Before public void init() { } @Test public void getCreateClusterParams_invalid_replica_then_throw_exception() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage(containsString("Replicas must be equal or longer than 0")); // when tested.getCreateClusterParams(-1, Sets.newHashSet()); } @Test public void getCreateClusterParams() { // given doNothing().when(tested).checkCreateParameters(); doNothing().when(tested).allocSlots(); doReturn(Lists.newArrayList()).when(tested).getCreateClusterParams(anyInt(), anySet()); // when
List<CreateClusterParam> result = tested.getCreateClusterParams(2, Sets.newHashSet());
be-hase/relumin
src/test/java/com/behase/relumin/support/RedisTribTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*;
} @Test public void createCluster() throws Exception { // given List<CreateClusterParam> params = Lists.newArrayList( CreateClusterParam.builder() .startSlotNumber("0") .endSlotNumber("5460") .master("host1:1001") .masterNodeId("nodeId1") .replicas(Lists.newArrayList("host3:1002")) .build(), CreateClusterParam.builder() .startSlotNumber("5461") .endSlotNumber("10921") .master("host2:1001") .masterNodeId("nodeId3") .replicas(Lists.newArrayList("host1:1002")) .build(), CreateClusterParam.builder() .startSlotNumber("10922") .endSlotNumber("16383") .master("host3:1001") .masterNodeId("nodeId5") .replicas(Lists.newArrayList("host2:1002")) .build() ); doReturn(tribClusterNode).when(tested).createTribClusterNode(anyString());
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // } // Path: src/test/java/com/behase/relumin/support/RedisTribTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*; } @Test public void createCluster() throws Exception { // given List<CreateClusterParam> params = Lists.newArrayList( CreateClusterParam.builder() .startSlotNumber("0") .endSlotNumber("5460") .master("host1:1001") .masterNodeId("nodeId1") .replicas(Lists.newArrayList("host3:1002")) .build(), CreateClusterParam.builder() .startSlotNumber("5461") .endSlotNumber("10921") .master("host2:1001") .masterNodeId("nodeId3") .replicas(Lists.newArrayList("host1:1002")) .build(), CreateClusterParam.builder() .startSlotNumber("10922") .endSlotNumber("16383") .master("host3:1001") .masterNodeId("nodeId5") .replicas(Lists.newArrayList("host2:1002")) .build() ); doReturn(tribClusterNode).when(tested).createTribClusterNode(anyString());
doReturn(new ClusterNode()).when(tribClusterNode).getNodeInfo();
be-hase/relumin
src/test/java/com/behase/relumin/support/RedisTribTest.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*;
// then assertThat(tested.getErrors().size(), is(2)); verify(tested, times(2)).fixOpenSlot(anyInt()); } @Test public void getNodeWithMostKeysInSlot() { // given TribClusterNode mock1 = mock(TribClusterNode.class); TribClusterNode mock2 = mock(TribClusterNode.class); TribClusterNode mock3 = mock(TribClusterNode.class); doReturn(jedis).when(mock2).getJedis(); doReturn(jedis).when(mock3).getJedis(); doReturn(true).when(mock1).hasFlag("slave"); doReturn(jedis).when(mock2).getJedis(); doReturn(jedis).when(mock3).getJedis(); doReturn(1l).doReturn(2l).when(jedis).clusterCountKeysInSlot(anyInt()); // when TribClusterNode result = tested.getNodeWithMostKeysInSlot(Lists.newArrayList(mock1, mock2, mock3), 0); // then assertThat(result, is(mock3)); } @Test public void fixOpenSlot_owner_node_is_null_then_throw() {
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // // Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/param/CreateClusterParam.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class CreateClusterParam { // private String startSlotNumber; // private String endSlotNumber; // private String master; // private List<String> replicas = Lists.newArrayList(); // // @JsonIgnore // private String masterNodeId; // } // Path: src/test/java/com/behase/relumin/support/RedisTribTest.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.exception.InvalidParameterException; import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.param.CreateClusterParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.reflection.Whitebox; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.boot.test.OutputCapture; import redis.clients.jedis.Jedis; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.*; // then assertThat(tested.getErrors().size(), is(2)); verify(tested, times(2)).fixOpenSlot(anyInt()); } @Test public void getNodeWithMostKeysInSlot() { // given TribClusterNode mock1 = mock(TribClusterNode.class); TribClusterNode mock2 = mock(TribClusterNode.class); TribClusterNode mock3 = mock(TribClusterNode.class); doReturn(jedis).when(mock2).getJedis(); doReturn(jedis).when(mock3).getJedis(); doReturn(true).when(mock1).hasFlag("slave"); doReturn(jedis).when(mock2).getJedis(); doReturn(jedis).when(mock3).getJedis(); doReturn(1l).doReturn(2l).when(jedis).clusterCountKeysInSlot(anyInt()); // when TribClusterNode result = tested.getNodeWithMostKeysInSlot(Lists.newArrayList(mock1, mock2, mock3), 0); // then assertThat(result, is(mock3)); } @Test public void fixOpenSlot_owner_node_is_null_then_throw() {
expectedEx.expect(ApiException.class);
be-hase/relumin
src/main/java/com/behase/relumin/service/NodeService.java
// Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/SlowLog.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class SlowLog { // private long id; // private String nodeId; // private String hostAndPort; // private long timeStamp; // private long executionTime; // private List<String> args; // }
import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.SlowLog; import java.util.List; import java.util.Map;
package com.behase.relumin.service; public interface NodeService { Map<String, String> getStaticsInfo(ClusterNode clusterNode); Map<String, List<List<Object>>> getStaticsInfoHistory(String clusterName, String nodeId, List<String> fields, long start, long end);
// Path: src/main/java/com/behase/relumin/model/ClusterNode.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ClusterNode { // private String nodeId; // private String hostAndPort; // private Set<String> flags = Sets.newLinkedHashSet(); // private String masterNodeId; // private long pingSent; // private long pongReceived; // private long configEpoch; // private boolean connect; // private Map<Integer, String> migrating = Maps.newLinkedHashMap(); // private Map<Integer, String> importing = Maps.newLinkedHashMap(); // // @JsonIgnore // private Set<Integer> servedSlotsSet = Sets.newTreeSet(); // // public boolean hasFlag(String flag) { // if (flags == null || flags.isEmpty()) { // return false; // } // return flags.contains(flag); // } // // public String getServedSlots() { // return new JedisSupport().slotsDisplay(servedSlotsSet); // } // // public int getSlotCount() { // if (servedSlotsSet == null) { // return 0; // } // return servedSlotsSet.size(); // } // // @JsonIgnore // public String getHost() { // return StringUtils.split(hostAndPort, ":")[0]; // } // // @JsonIgnore // public int getPort() { // return Integer.valueOf(StringUtils.split(hostAndPort, ":")[1]); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // // ClusterNode other = (ClusterNode) obj; // return StringUtils.equalsIgnoreCase(nodeId, other.nodeId); // } // } // // Path: src/main/java/com/behase/relumin/model/SlowLog.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class SlowLog { // private long id; // private String nodeId; // private String hostAndPort; // private long timeStamp; // private long executionTime; // private List<String> args; // } // Path: src/main/java/com/behase/relumin/service/NodeService.java import com.behase.relumin.model.ClusterNode; import com.behase.relumin.model.SlowLog; import java.util.List; import java.util.Map; package com.behase.relumin.service; public interface NodeService { Map<String, String> getStaticsInfo(ClusterNode clusterNode); Map<String, List<List<Object>>> getStaticsInfoHistory(String clusterName, String nodeId, List<String> fields, long start, long end);
List<SlowLog> getSlowLog(ClusterNode clusterNode);
be-hase/relumin
src/main/java/com/behase/relumin/controller/MyControllerAdvice.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package com.behase.relumin.controller; @Slf4j @ControllerAdvice @Configuration public class MyControllerAdvice { @ExceptionHandler(Exception.class) @ResponseBody
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/main/java/com/behase/relumin/controller/MyControllerAdvice.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package com.behase.relumin.controller; @Slf4j @ControllerAdvice @Configuration public class MyControllerAdvice { @ExceptionHandler(Exception.class) @ResponseBody
public ResponseEntity<ErrorResponse> allExceptionHandler(Exception e, HttpServletRequest request,
be-hase/relumin
src/main/java/com/behase/relumin/controller/MyControllerAdvice.java
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // }
import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package com.behase.relumin.controller; @Slf4j @ControllerAdvice @Configuration public class MyControllerAdvice { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<ErrorResponse> allExceptionHandler(Exception e, HttpServletRequest request, HttpServletResponse response) { log.error("handle Exception.", e); return new ResponseEntity<>(new ErrorResponse("500", "Internal server error."), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorResponse missingServletRequestParameterExceptionHandler( MissingServletRequestParameterException e, HttpServletRequest request, HttpServletResponse response) { log.warn("handle Exception.", e); return new ErrorResponse("400", "Invalid parameter."); }
// Path: src/main/java/com/behase/relumin/exception/ApiException.java // public class ApiException extends RuntimeException { // private static final long serialVersionUID = 3285456520279227122L; // // @Getter // @Setter // private ErrorResponse errorResponse; // // @Getter // @Setter // private HttpStatus httpStatus; // // public ApiException(ErrorResponse errorResponse, HttpStatus httpStatus) { // super(errorResponse.getError().getMessage()); // this.errorResponse = errorResponse; // this.httpStatus = httpStatus; // } // // public ApiException(String code, String message, HttpStatus httpStatus) { // super(message); // this.errorResponse = new ErrorResponse(code, message); // this.httpStatus = httpStatus; // } // } // // Path: src/main/java/com/behase/relumin/model/ErrorResponse.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class ErrorResponse { // private Error error; // // public ErrorResponse(String code, String message) { // this.error = new Error(); // this.error.code = code; // this.error.message = message; // } // // @Data // public static class Error { // private String code; // private String message; // } // } // Path: src/main/java/com/behase/relumin/controller/MyControllerAdvice.java import com.behase.relumin.exception.ApiException; import com.behase.relumin.model.ErrorResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package com.behase.relumin.controller; @Slf4j @ControllerAdvice @Configuration public class MyControllerAdvice { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<ErrorResponse> allExceptionHandler(Exception e, HttpServletRequest request, HttpServletResponse response) { log.error("handle Exception.", e); return new ResponseEntity<>(new ErrorResponse("500", "Internal server error."), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorResponse missingServletRequestParameterExceptionHandler( MissingServletRequestParameterException e, HttpServletRequest request, HttpServletResponse response) { log.warn("handle Exception.", e); return new ErrorResponse("400", "Invalid parameter."); }
@ExceptionHandler(ApiException.class)
be-hase/relumin
src/test/java/com/behase/relumin/e2e/UserApiTest.java
// Path: src/main/java/com/behase/relumin/Application.java // @Slf4j // @Configuration // @EnableAutoConfiguration // @EnableScheduling // @EnableWebSecurity // @ComponentScan // public class Application extends WebMvcConfigurerAdapter { // private static final String CONFIG_LOCATION = "config"; // // public static void main(String[] args) throws IOException { // log.info("Starting Relumin..."); // // String configLocation = System.getProperty(CONFIG_LOCATION); // checkArgument(configLocation != null, "Specify config VM parameter."); // // ReluminConfig config = ReluminConfig.create(configLocation); // log.info("config : {}", config); // // SpringApplication app = new SpringApplication(Application.class); // app.setDefaultProperties(config.getProperties()); // app.run(args); // } // } // // Path: src/test/java/com/behase/relumin/TestHelper.java // @Slf4j // @Component // public class TestHelper { // @Value("${test.redis.host}") // private String testRedisHost; // // public String getDataStoreJedis() { // return testRedisHost + ":9000"; // } // // public Set<String> getRedisClusterHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10000-10005")); // } // // public Set<String> getRedisStandAloneHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10010-10015")); // } // // public void resetAllRedis() { // log.info("reset all redis."); // // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(getDataStoreJedis())) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisClusterHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // try { // jedis.clusterReset(JedisCluster.Reset.HARD); // } catch (Exception e) { // } // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisStandAloneHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // jedis.flushAll(); // } catch (Exception e) { // } // } // } // // public void createBasicCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "1") // .param("hostAndPorts", testRedisHost + ":10000-10005") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public void createOnlyMasterCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "0") // .param("hostAndPorts", testRedisHost + ":10000-10002") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public Cluster getCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result = mockMvc.perform( // get("/api/cluster/" + clusterName) // ).andReturn(); // return WebConfig.MAPPER.readValue(result.getResponse().getContentAsString(), Cluster.class); // } // }
import com.behase.relumin.Application; import com.behase.relumin.TestHelper; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
package com.behase.relumin.e2e; /** * Check integration of success behavior */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class)
// Path: src/main/java/com/behase/relumin/Application.java // @Slf4j // @Configuration // @EnableAutoConfiguration // @EnableScheduling // @EnableWebSecurity // @ComponentScan // public class Application extends WebMvcConfigurerAdapter { // private static final String CONFIG_LOCATION = "config"; // // public static void main(String[] args) throws IOException { // log.info("Starting Relumin..."); // // String configLocation = System.getProperty(CONFIG_LOCATION); // checkArgument(configLocation != null, "Specify config VM parameter."); // // ReluminConfig config = ReluminConfig.create(configLocation); // log.info("config : {}", config); // // SpringApplication app = new SpringApplication(Application.class); // app.setDefaultProperties(config.getProperties()); // app.run(args); // } // } // // Path: src/test/java/com/behase/relumin/TestHelper.java // @Slf4j // @Component // public class TestHelper { // @Value("${test.redis.host}") // private String testRedisHost; // // public String getDataStoreJedis() { // return testRedisHost + ":9000"; // } // // public Set<String> getRedisClusterHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10000-10005")); // } // // public Set<String> getRedisStandAloneHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10010-10015")); // } // // public void resetAllRedis() { // log.info("reset all redis."); // // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(getDataStoreJedis())) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisClusterHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // try { // jedis.clusterReset(JedisCluster.Reset.HARD); // } catch (Exception e) { // } // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisStandAloneHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // jedis.flushAll(); // } catch (Exception e) { // } // } // } // // public void createBasicCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "1") // .param("hostAndPorts", testRedisHost + ":10000-10005") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public void createOnlyMasterCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "0") // .param("hostAndPorts", testRedisHost + ":10000-10002") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public Cluster getCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result = mockMvc.perform( // get("/api/cluster/" + clusterName) // ).andReturn(); // return WebConfig.MAPPER.readValue(result.getResponse().getContentAsString(), Cluster.class); // } // } // Path: src/test/java/com/behase/relumin/e2e/UserApiTest.java import com.behase.relumin.Application; import com.behase.relumin.TestHelper; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; package com.behase.relumin.e2e; /** * Check integration of success behavior */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
be-hase/relumin
src/test/java/com/behase/relumin/e2e/UserApiTest.java
// Path: src/main/java/com/behase/relumin/Application.java // @Slf4j // @Configuration // @EnableAutoConfiguration // @EnableScheduling // @EnableWebSecurity // @ComponentScan // public class Application extends WebMvcConfigurerAdapter { // private static final String CONFIG_LOCATION = "config"; // // public static void main(String[] args) throws IOException { // log.info("Starting Relumin..."); // // String configLocation = System.getProperty(CONFIG_LOCATION); // checkArgument(configLocation != null, "Specify config VM parameter."); // // ReluminConfig config = ReluminConfig.create(configLocation); // log.info("config : {}", config); // // SpringApplication app = new SpringApplication(Application.class); // app.setDefaultProperties(config.getProperties()); // app.run(args); // } // } // // Path: src/test/java/com/behase/relumin/TestHelper.java // @Slf4j // @Component // public class TestHelper { // @Value("${test.redis.host}") // private String testRedisHost; // // public String getDataStoreJedis() { // return testRedisHost + ":9000"; // } // // public Set<String> getRedisClusterHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10000-10005")); // } // // public Set<String> getRedisStandAloneHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10010-10015")); // } // // public void resetAllRedis() { // log.info("reset all redis."); // // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(getDataStoreJedis())) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisClusterHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // try { // jedis.clusterReset(JedisCluster.Reset.HARD); // } catch (Exception e) { // } // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisStandAloneHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // jedis.flushAll(); // } catch (Exception e) { // } // } // } // // public void createBasicCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "1") // .param("hostAndPorts", testRedisHost + ":10000-10005") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public void createOnlyMasterCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "0") // .param("hostAndPorts", testRedisHost + ":10000-10002") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public Cluster getCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result = mockMvc.perform( // get("/api/cluster/" + clusterName) // ).andReturn(); // return WebConfig.MAPPER.readValue(result.getResponse().getContentAsString(), Cluster.class); // } // }
import com.behase.relumin.Application; import com.behase.relumin.TestHelper; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
package com.behase.relumin.e2e; /** * Check integration of success behavior */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest public class UserApiTest { @Autowired
// Path: src/main/java/com/behase/relumin/Application.java // @Slf4j // @Configuration // @EnableAutoConfiguration // @EnableScheduling // @EnableWebSecurity // @ComponentScan // public class Application extends WebMvcConfigurerAdapter { // private static final String CONFIG_LOCATION = "config"; // // public static void main(String[] args) throws IOException { // log.info("Starting Relumin..."); // // String configLocation = System.getProperty(CONFIG_LOCATION); // checkArgument(configLocation != null, "Specify config VM parameter."); // // ReluminConfig config = ReluminConfig.create(configLocation); // log.info("config : {}", config); // // SpringApplication app = new SpringApplication(Application.class); // app.setDefaultProperties(config.getProperties()); // app.run(args); // } // } // // Path: src/test/java/com/behase/relumin/TestHelper.java // @Slf4j // @Component // public class TestHelper { // @Value("${test.redis.host}") // private String testRedisHost; // // public String getDataStoreJedis() { // return testRedisHost + ":9000"; // } // // public Set<String> getRedisClusterHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10000-10005")); // } // // public Set<String> getRedisStandAloneHostAndPorts() { // return new JedisSupport().getHostAndPorts(Lists.newArrayList(testRedisHost + ":10010-10015")); // } // // public void resetAllRedis() { // log.info("reset all redis."); // // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(getDataStoreJedis())) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisClusterHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // try { // jedis.flushAll(); // } catch (Exception e) { // } // try { // jedis.clusterReset(JedisCluster.Reset.HARD); // } catch (Exception e) { // } // } catch (Exception e) { // } // } // // for (String hostAndPort : getRedisStandAloneHostAndPorts()) { // try (Jedis jedis = new JedisSupport().getJedisByHostAndPort(hostAndPort)) { // jedis.flushAll(); // } catch (Exception e) { // } // } // } // // public void createBasicCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "1") // .param("hostAndPorts", testRedisHost + ":10000-10005") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public void createOnlyMasterCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result; // // result = mockMvc.perform( // get("/api/trib/create/params") // .param("replicas", "0") // .param("hostAndPorts", testRedisHost + ":10000-10002") // ).andReturn(); // String body = result.getResponse().getContentAsString(); // // mockMvc.perform( // post("/api/trib/create/" + clusterName) // .param("params", body) // .header(HttpHeaders.CONTENT_TYPE, "application/json") // ); // } // // public Cluster getCluster(MockMvc mockMvc, String clusterName) throws Exception { // MvcResult result = mockMvc.perform( // get("/api/cluster/" + clusterName) // ).andReturn(); // return WebConfig.MAPPER.readValue(result.getResponse().getContentAsString(), Cluster.class); // } // } // Path: src/test/java/com/behase/relumin/e2e/UserApiTest.java import com.behase.relumin.Application; import com.behase.relumin.TestHelper; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; package com.behase.relumin.e2e; /** * Check integration of success behavior */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest public class UserApiTest { @Autowired
private TestHelper testHelper;
be-hase/relumin
src/main/java/com/behase/relumin/model/Role.java
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // }
import com.behase.relumin.exception.InvalidParameterException; import org.springframework.security.core.GrantedAuthority;
package com.behase.relumin.model; public class Role implements GrantedAuthority { private static final long serialVersionUID = -4168971547041673977L; private String authority; private Role(String authority) { this.authority = authority; } @Override public String getAuthority() { return authority; } public static final Role VIEWER = new Role("VIEWER"); public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); public static Role get(String role) { switch (role) { case "VIEWER": return VIEWER; case "RELUMIN_ADMIN": return RELUMIN_ADMIN; default: }
// Path: src/main/java/com/behase/relumin/exception/InvalidParameterException.java // public class InvalidParameterException extends ApiException { // private static final long serialVersionUID = -6416726302671334601L; // // public InvalidParameterException(String message) { // super(Constants.ERR_CODE_INVALID_PARAMETER, String.format("Invalid parameter. %s", message), HttpStatus.BAD_REQUEST); // } // } // Path: src/main/java/com/behase/relumin/model/Role.java import com.behase.relumin.exception.InvalidParameterException; import org.springframework.security.core.GrantedAuthority; package com.behase.relumin.model; public class Role implements GrantedAuthority { private static final long serialVersionUID = -4168971547041673977L; private String authority; private Role(String authority) { this.authority = authority; } @Override public String getAuthority() { return authority; } public static final Role VIEWER = new Role("VIEWER"); public static final Role RELUMIN_ADMIN = new Role("RELUMIN_ADMIN"); public static Role get(String role) { switch (role) { case "VIEWER": return VIEWER; case "RELUMIN_ADMIN": return RELUMIN_ADMIN; default: }
throw new InvalidParameterException(String.format("'%s' is invalid role.", role));
be-hase/relumin
src/main/java/com/behase/relumin/controller/WebController.java
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
package com.behase.relumin.controller; @Controller public class WebController { @Autowired
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/WebController.java import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; package com.behase.relumin.controller; @Controller public class WebController { @Autowired
private UserService userService;
be-hase/relumin
src/main/java/com/behase/relumin/controller/WebController.java
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
package com.behase.relumin.controller; @Controller public class WebController { @Autowired private UserService userService; @Value("${build.number}") private String buildNumber; @Value("${scheduler.collectStaticsInfoIntervalMillis:"
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/WebController.java import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; package com.behase.relumin.controller; @Controller public class WebController { @Autowired private UserService userService; @Value("${build.number}") private String buildNumber; @Value("${scheduler.collectStaticsInfoIntervalMillis:"
+ SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS + "}")
be-hase/relumin
src/main/java/com/behase/relumin/controller/WebController.java
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // }
import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
package com.behase.relumin.controller; @Controller public class WebController { @Autowired private UserService userService; @Value("${build.number}") private String buildNumber; @Value("${scheduler.collectStaticsInfoIntervalMillis:" + SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS + "}") private String collectStaticsInfoIntervalMillis; @Value("${auth.enabled}") private boolean authEnabled; @Value("${auth.allowAnonymous}") private boolean authAllowAnonymous; @RequestMapping(value = "/", method = RequestMethod.GET) public String index( Authentication authentication, Model model ) throws Exception { model.addAttribute("buildNumber", buildNumber); model.addAttribute("collectStaticsInfoIntervalMillis", collectStaticsInfoIntervalMillis); model.addAttribute("authEnabled", authEnabled); model.addAttribute("authAllowAnonymous", authAllowAnonymous); if (authEnabled && authentication != null) {
// Path: src/main/java/com/behase/relumin/config/SchedulerConfig.java // @Data // public class SchedulerConfig { // public static final String DEFAULT_REFRESH_CLUSTERS_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS = "120000"; // public static final String DEFAULT_COLLECT_STATICS_INFO_MAX_COUNT = "1500"; // public static final String DEFAULT_COLLECT_SLOW_LOG_MAX_COUNT = "1500"; // // private String refreshClustersIntervalMillis; // // private String collectStaticsInfoIntervalMillis; // private String collectStaticsInfoMaxCount; // private String collectSlowLogMaxCount; // } // // Path: src/main/java/com/behase/relumin/model/LoginUser.java // @Data // @Builder // @NoArgsConstructor // public class LoginUser { // private String username; // private String displayName; // private String password; // private String role; // // public LoginUser(String username, String displayName, String rawPassword, String role) { // this.username = username; // this.displayName = displayName; // this.password = new StandardPasswordEncoder().encode(rawPassword); // this.role = Role.get(role).getAuthority(); // } // // @JsonIgnore // public User getSpringUser() { // return new User(username, password, Lists.newArrayList(Role.get(role))); // } // // public void setRawPassword(String rawPassword) { // this.password = new StandardPasswordEncoder().encode(rawPassword); // } // } // // Path: src/main/java/com/behase/relumin/service/UserService.java // public interface UserService extends UserDetailsService { // LoginUser getUser(String username) throws Exception; // // List<LoginUser> getUsers() throws Exception; // // void addUser(String username, String displayName, String password, String role) throws Exception; // // void changePassword(String username, String oldPassword, String password) throws Exception; // // void updateUser(String username, String displayName, String role) throws Exception; // // void deleteUser(String username) throws Exception; // } // Path: src/main/java/com/behase/relumin/controller/WebController.java import com.behase.relumin.config.SchedulerConfig; import com.behase.relumin.model.LoginUser; import com.behase.relumin.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; package com.behase.relumin.controller; @Controller public class WebController { @Autowired private UserService userService; @Value("${build.number}") private String buildNumber; @Value("${scheduler.collectStaticsInfoIntervalMillis:" + SchedulerConfig.DEFAULT_COLLECT_STATICS_INFO_INTERVAL_MILLIS + "}") private String collectStaticsInfoIntervalMillis; @Value("${auth.enabled}") private boolean authEnabled; @Value("${auth.allowAnonymous}") private boolean authAllowAnonymous; @RequestMapping(value = "/", method = RequestMethod.GET) public String index( Authentication authentication, Model model ) throws Exception { model.addAttribute("buildNumber", buildNumber); model.addAttribute("collectStaticsInfoIntervalMillis", collectStaticsInfoIntervalMillis); model.addAttribute("authEnabled", authEnabled); model.addAttribute("authAllowAnonymous", authAllowAnonymous); if (authEnabled && authentication != null) {
LoginUser loginUser = userService.getUser(authentication.getName());
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/Eval.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/MissingNodeException.java // @SuppressWarnings("serial") // public class MissingNodeException extends RuntimeException { // // public MissingNodeException(String message) { // super(message); // // } // }
import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.MissingNodeException;
package com.kcthota.JSONQuery; public class Eval { private static ScriptEngineManager manager = new ScriptEngineManager(); private static ScriptEngine engine = manager.getEngineByName("nashorn"); private static Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); public static Object eval(JsonNode jsonNode, String expression) { String formattedExpression = replaceTokens(jsonNode, expression); Object returnVal = null; try { returnVal = engine.eval(formattedExpression); } catch (ScriptException e) { //logging } return returnVal; } private static String replaceTokens(JsonNode jsonNode, String expression) { if (expression == null) { return expression; } Query query=Query.q(jsonNode); Matcher matcher = pattern.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String token = matcher.group(1); try { String tokenValue = query.value(token).asText(); matcher.appendReplacement(sb, tokenValue == null ? token : tokenValue);
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/MissingNodeException.java // @SuppressWarnings("serial") // public class MissingNodeException extends RuntimeException { // // public MissingNodeException(String message) { // super(message); // // } // } // Path: src/main/java/com/kcthota/JSONQuery/Eval.java import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.MissingNodeException; package com.kcthota.JSONQuery; public class Eval { private static ScriptEngineManager manager = new ScriptEngineManager(); private static ScriptEngine engine = manager.getEngineByName("nashorn"); private static Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); public static Object eval(JsonNode jsonNode, String expression) { String formattedExpression = replaceTokens(jsonNode, expression); Object returnVal = null; try { returnVal = engine.eval(formattedExpression); } catch (ScriptException e) { //logging } return returnVal; } private static String replaceTokens(JsonNode jsonNode, String expression) { if (expression == null) { return expression; } Query query=Query.q(jsonNode); Matcher matcher = pattern.matcher(expression); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String token = matcher.group(1); try { String tokenValue = query.value(token).asText(); matcher.appendReplacement(sb, tokenValue == null ? token : tokenValue);
} catch(MissingNodeException e) {
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/ToLowerValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the ToLower value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 27, 2015 8:26:16 PM */ public class ToLowerValueExpression extends StringValueExpression { public ToLowerValueExpression(String property) { super(property); } public ToLowerValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/ToLowerValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the ToLower value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 27, 2015 8:26:16 PM */ public class ToLowerValueExpression extends StringValueExpression { public ToLowerValueExpression(String property) { super(property); } public ToLowerValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/test/java/com/kcthota/query/EvalTest.java
// Path: src/main/java/com/kcthota/JSONQuery/Eval.java // public class Eval { // private static ScriptEngineManager manager = new ScriptEngineManager(); // private static ScriptEngine engine = manager.getEngineByName("nashorn"); // // private static Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); // // public static Object eval(JsonNode jsonNode, String expression) { // String formattedExpression = replaceTokens(jsonNode, expression); // Object returnVal = null; // try { // returnVal = engine.eval(formattedExpression); // } catch (ScriptException e) { // //logging // } // return returnVal; // } // // private static String replaceTokens(JsonNode jsonNode, String expression) { // if (expression == null) { // return expression; // } // Query query=Query.q(jsonNode); // Matcher matcher = pattern.matcher(expression); // StringBuffer sb = new StringBuffer(); // while (matcher.find()) { // String token = matcher.group(1); // try { // String tokenValue = query.value(token).asText(); // matcher.appendReplacement(sb, tokenValue == null ? token // : tokenValue); // } catch(MissingNodeException e) { // continue; // } // } // matcher.appendTail(sb); // return sb.toString(); // } // }
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.kcthota.JSONQuery.Eval;
package com.kcthota.query; public class EvalTest { @Test public void booleanExprTest() { ObjectNode node = new ObjectMapper().createObjectNode(); node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota"); node.put("city", "Santa Clara"); node.putArray("interests").add("hiking").add("biking");
// Path: src/main/java/com/kcthota/JSONQuery/Eval.java // public class Eval { // private static ScriptEngineManager manager = new ScriptEngineManager(); // private static ScriptEngine engine = manager.getEngineByName("nashorn"); // // private static Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); // // public static Object eval(JsonNode jsonNode, String expression) { // String formattedExpression = replaceTokens(jsonNode, expression); // Object returnVal = null; // try { // returnVal = engine.eval(formattedExpression); // } catch (ScriptException e) { // //logging // } // return returnVal; // } // // private static String replaceTokens(JsonNode jsonNode, String expression) { // if (expression == null) { // return expression; // } // Query query=Query.q(jsonNode); // Matcher matcher = pattern.matcher(expression); // StringBuffer sb = new StringBuffer(); // while (matcher.find()) { // String token = matcher.group(1); // try { // String tokenValue = query.value(token).asText(); // matcher.appendReplacement(sb, tokenValue == null ? token // : tokenValue); // } catch(MissingNodeException e) { // continue; // } // } // matcher.appendTail(sb); // return sb.toString(); // } // } // Path: src/test/java/com/kcthota/query/EvalTest.java import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.kcthota.JSONQuery.Eval; package com.kcthota.query; public class EvalTest { @Test public void booleanExprTest() { ObjectNode node = new ObjectMapper().createObjectNode(); node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota"); node.put("city", "Santa Clara"); node.putArray("interests").add("hiking").add("biking");
assertThat(Eval.eval(node, "'${city}' == 'Santa Clara'")).isEqualTo(true);
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/ReplaceValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Replaces matching string with new value and returns the changed value * @author Krishna Chaitanya Thota * Apr 28, 2015 7:28:45 PM */ public class ReplaceValueExpression extends StringValueExpression { private String target = ""; private String replacement = ""; public ReplaceValueExpression(String property, String target, String replacement) { super(property); if(target!=null) { this.target = target; } if(replacement!=null) { this.replacement = replacement; } } public ReplaceValueExpression(String property, String target, String replacement, ValueExpression innerExpression) { super(property, innerExpression); if(target!=null) { this.target = target; } if(replacement!=null) { this.replacement = replacement; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/ReplaceValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Replaces matching string with new value and returns the changed value * @author Krishna Chaitanya Thota * Apr 28, 2015 7:28:45 PM */ public class ReplaceValueExpression extends StringValueExpression { private String target = ""; private String replacement = ""; public ReplaceValueExpression(String property, String target, String replacement) { super(property); if(target!=null) { this.target = target; } if(replacement!=null) { this.replacement = replacement; } } public ReplaceValueExpression(String property, String target, String replacement, ValueExpression innerExpression) { super(property, innerExpression); if(target!=null) { this.target = target; } if(replacement!=null) { this.replacement = replacement; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/SubstringValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns substring of a string * * @author Krishna Chaitanya Thota Apr 28, 2015 8:38:07 PM */ public class SubstringValueExpression extends StringValueExpression { private Integer startIndex = 0; private Integer endIndex = null; public SubstringValueExpression(String property, Integer startIndex, Integer endIndex) { super(property); if (startIndex != null) { this.startIndex = startIndex; } if (endIndex != null) { this.endIndex = endIndex; } } public SubstringValueExpression(String property, Integer startIndex, Integer endIndex, ValueExpression innerExpression) { super(property, innerExpression); if (startIndex != null) { this.startIndex = startIndex; } if (endIndex != null) { this.endIndex = endIndex; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if (valueNode == null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/SubstringValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns substring of a string * * @author Krishna Chaitanya Thota Apr 28, 2015 8:38:07 PM */ public class SubstringValueExpression extends StringValueExpression { private Integer startIndex = 0; private Integer endIndex = null; public SubstringValueExpression(String property, Integer startIndex, Integer endIndex) { super(property); if (startIndex != null) { this.startIndex = startIndex; } if (endIndex != null) { this.endIndex = endIndex; } } public SubstringValueExpression(String property, Integer startIndex, Integer endIndex, ValueExpression innerExpression) { super(property, innerExpression); if (startIndex != null) { this.startIndex = startIndex; } if (endIndex != null) { this.endIndex = endIndex; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if (valueNode == null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/ValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/MissingNodeException.java // @SuppressWarnings("serial") // public class MissingNodeException extends RuntimeException { // // public MissingNodeException(String message) { // super(message); // // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.MissingNodeException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class ValueExpression implements Expression { String property; ValueExpression innerExpression=null; public ValueExpression(String property, ValueExpression innerExpression) { this.property = property; this.innerExpression = innerExpression; } public ValueExpression(String property) { this.property = property; } /** * Evaluates the expression on passed JSONNode * @param node JSONNode object * @return returns the value of the property */ public JsonNode evaluate(JsonNode node) { if(innerExpression==null) { return getValue(node, property); } else { return getValue(innerExpression.evaluate(node), property); } } /** * Fetches the value for a property from the passed JsonNode. Throws MissingNodeException if the property doesn't exist * @param node JSONNode Object * @param property Property for which the value should be returned * @return returns the value of the property */ protected JsonNode getValue(JsonNode node, String property) { if(node==null) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/MissingNodeException.java // @SuppressWarnings("serial") // public class MissingNodeException extends RuntimeException { // // public MissingNodeException(String message) { // super(message); // // } // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/ValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.MissingNodeException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class ValueExpression implements Expression { String property; ValueExpression innerExpression=null; public ValueExpression(String property, ValueExpression innerExpression) { this.property = property; this.innerExpression = innerExpression; } public ValueExpression(String property) { this.property = property; } /** * Evaluates the expression on passed JSONNode * @param node JSONNode object * @return returns the value of the property */ public JsonNode evaluate(JsonNode node) { if(innerExpression==null) { return getValue(node, property); } else { return getValue(innerExpression.evaluate(node), property); } } /** * Fetches the value for a property from the passed JsonNode. Throws MissingNodeException if the property doesn't exist * @param node JSONNode Object * @param property Property for which the value should be returned * @return returns the value of the property */ protected JsonNode getValue(JsonNode node, String property) { if(node==null) {
throw new MissingNodeException(property + " is missing");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/ToUpperValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the ToUpper value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 27, 2015 8:18:49 PM */ public class ToUpperValueExpression extends StringValueExpression { public ToUpperValueExpression(String property) { super(property); } public ToUpperValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/ToUpperValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the ToUpper value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 27, 2015 8:18:49 PM */ public class ToUpperValueExpression extends StringValueExpression { public ToUpperValueExpression(String property) { super(property); } public ToUpperValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/AbstractQuery.java
// Path: src/main/java/com/kcthota/JSONQuery/expressions/ComparisonExpression.java // public interface ComparisonExpression extends Expression { // /** // * Evalutes the comparison expression on the passed JsonNode // * @param node JSONNode object on which the expression should be evaluated // * @return Result of the comparison // */ // public boolean evaluate(JsonNode node); // }
import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.expressions.ComparisonExpression;
/** * */ package com.kcthota.JSONQuery; /** * @author Krishna Chaitanya Thota * Apr 23, 2015 11:40:06 PM */ public abstract class AbstractQuery { protected JsonNode node; public AbstractQuery(JsonNode node) { this.node = node; }
// Path: src/main/java/com/kcthota/JSONQuery/expressions/ComparisonExpression.java // public interface ComparisonExpression extends Expression { // /** // * Evalutes the comparison expression on the passed JsonNode // * @param node JSONNode object on which the expression should be evaluated // * @return Result of the comparison // */ // public boolean evaluate(JsonNode node); // } // Path: src/main/java/com/kcthota/JSONQuery/AbstractQuery.java import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.expressions.ComparisonExpression; /** * */ package com.kcthota.JSONQuery; /** * @author Krishna Chaitanya Thota * Apr 23, 2015 11:40:06 PM */ public abstract class AbstractQuery { protected JsonNode node; public AbstractQuery(JsonNode node) { this.node = node; }
public abstract boolean is(ComparisonExpression expr);
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/TrimValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the trimmed value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class TrimValueExpression extends StringValueExpression { public TrimValueExpression(String property) { super(property); } public TrimValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/TrimValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the trimmed value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class TrimValueExpression extends StringValueExpression { public TrimValueExpression(String property) { super(property); } public TrimValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/RoundValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.LongNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Rounds the value and returns long value * @author kc * */ public class RoundValueExpression extends LongValueExpression { public RoundValueExpression(String property) { super(property); } public RoundValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return LongNode.valueOf(Math.round(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return LongNode.valueOf(Math.round(doubleVal)); } catch(NumberFormatException e) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/RoundValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.LongNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Rounds the value and returns long value * @author kc * */ public class RoundValueExpression extends LongValueExpression { public RoundValueExpression(String property) { super(property); } public RoundValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return LongNode.valueOf(Math.round(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return LongNode.valueOf(Math.round(doubleVal)); } catch(NumberFormatException e) {
throw new UnsupportedExprException("Value not parseable to a number");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/GtExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
package com.kcthota.JSONQuery.expressions; /** * Evaluates Greater than * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:57 AM */ public class GtExpression extends SimpleComparisonExpression { public GtExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doGt(expression().evaluate(node), value()); } protected boolean doGt(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue > (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue > (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue > (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue > (Double) passedValue); } else {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/GtExpression.java import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; package com.kcthota.JSONQuery.expressions; /** * Evaluates Greater than * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:57 AM */ public class GtExpression extends SimpleComparisonExpression { public GtExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doGt(expression().evaluate(node), value()); } protected boolean doGt(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue > (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue > (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue > (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue > (Double) passedValue); } else {
throw new UnsupportedExprException("Gt supports only INT, LONG, DOUBLE, FLOAT values");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/FloorValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Floor the value and returns double value * @author kc * */ public class FloorValueExpression extends DoubleValueExpression { public FloorValueExpression(String property) { super(property); } public FloorValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return DoubleNode.valueOf(Math.floor(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return DoubleNode.valueOf(Math.floor(doubleVal)); } catch(NumberFormatException e) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/FloorValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Floor the value and returns double value * @author kc * */ public class FloorValueExpression extends DoubleValueExpression { public FloorValueExpression(String property) { super(property); } public FloorValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return DoubleNode.valueOf(Math.floor(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return DoubleNode.valueOf(Math.floor(doubleVal)); } catch(NumberFormatException e) {
throw new UnsupportedExprException("Value not parseable to a number");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/GeExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
package com.kcthota.JSONQuery.expressions; /** * Evaluates greater than or equal to * @author Krishna Chaitanya Thota * Apr 26, 2015 12:04:07 AM */ public class GeExpression extends SimpleComparisonExpression { public GeExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doGe(expression().evaluate(node), value()); } private boolean doGe(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue >= (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue >= (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue >= (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue >=(Double) passedValue); } else {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/GeExpression.java import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; package com.kcthota.JSONQuery.expressions; /** * Evaluates greater than or equal to * @author Krishna Chaitanya Thota * Apr 26, 2015 12:04:07 AM */ public class GeExpression extends SimpleComparisonExpression { public GeExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doGe(expression().evaluate(node), value()); } private boolean doGe(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue >= (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue >= (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue >= (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue >=(Double) passedValue); } else {
throw new UnsupportedExprException("Ge supports only INT, LONG, DOUBLE, FLOAT values");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/LtExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
package com.kcthota.JSONQuery.expressions; /** * Evaluates less than * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:24 AM */ public class LtExpression extends SimpleComparisonExpression { public LtExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doLt(expression().evaluate(node), value()); } protected boolean doLt(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue < (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue < (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue < (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue < (Double) passedValue); } else {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/LtExpression.java import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; package com.kcthota.JSONQuery.expressions; /** * Evaluates less than * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:24 AM */ public class LtExpression extends SimpleComparisonExpression { public LtExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doLt(expression().evaluate(node), value()); } protected boolean doLt(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue < (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue < (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue < (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue < (Double) passedValue); } else {
throw new UnsupportedExprException("Lt supports only INT, LONG, DOUBLE, FLOAT values");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/PrependToValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Prepends the passed text to the value in the json node and returns a new TextNode * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class PrependToValueExpression extends StringValueExpression { private String prependText = ""; public PrependToValueExpression(String property, String prependText) { super(property); if(prependText!=null) { this.prependText = prependText; } } public PrependToValueExpression(String property, String prependText, ValueExpression innerExpression) { super(property, innerExpression); if(prependText!=null) { this.prependText = prependText; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/PrependToValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Prepends the passed text to the value in the json node and returns a new TextNode * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class PrependToValueExpression extends StringValueExpression { private String prependText = ""; public PrependToValueExpression(String property, String prependText) { super(property); if(prependText!=null) { this.prependText = prependText; } } public PrependToValueExpression(String property, String prependText, ValueExpression innerExpression) { super(property, innerExpression); if(prependText!=null) { this.prependText = prependText; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/CeilValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Ceil the value and returns double value * @author kc * */ public class CeilValueExpression extends DoubleValueExpression { public CeilValueExpression(String property) { super(property); } public CeilValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return DoubleNode.valueOf(Math.ceil(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return DoubleNode.valueOf(Math.ceil(doubleVal)); } catch(NumberFormatException e) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/CeilValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Ceil the value and returns double value * @author kc * */ public class CeilValueExpression extends DoubleValueExpression { public CeilValueExpression(String property) { super(property); } public CeilValueExpression(String property, ValueExpression innerExpression) { super(property, innerExpression); } @Override public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode!=null && valueNode.isNumber()) { return DoubleNode.valueOf(Math.ceil(valueNode.asDouble())); } else if (valueNode!=null && valueNode.isTextual()){ try { Double doubleVal = Double.parseDouble(valueNode.asText()); return DoubleNode.valueOf(Math.ceil(doubleVal)); } catch(NumberFormatException e) {
throw new UnsupportedExprException("Value not parseable to a number");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/LeExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
package com.kcthota.JSONQuery.expressions; /** * Evaluates less than or equal to * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:35 AM */ public class LeExpression extends SimpleComparisonExpression { public LeExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doLe(expression().evaluate(node), value()); } protected boolean doLe(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue <= (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue <= (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue <= (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue <= (Double) passedValue); } else {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/LeExpression.java import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.databind.JsonNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; package com.kcthota.JSONQuery.expressions; /** * Evaluates less than or equal to * @author Krishna Chaitanya Thota * Apr 26, 2015 12:03:35 AM */ public class LeExpression extends SimpleComparisonExpression { public LeExpression(ValueExpression expression, JsonNode value) { super(expression, value); } @Override public boolean evaluate(JsonNode node) { return doLe(expression().evaluate(node), value()); } protected boolean doLe(JsonNode propertyNode, JsonNode passedNode){ if(propertyNode.isNumber() && passedNode.isNumber() && propertyNode.numberType() == passedNode.numberType()) { Number propertyValue = propertyNode.numberValue(); Number passedValue = passedNode.numberValue(); if(propertyNode.numberType() == NumberType.INT) { return ((Integer) propertyValue <= (Integer) passedValue); } else if(propertyNode.numberType() == NumberType.LONG) { return ((Long) propertyValue <= (Long) passedValue); } else if(propertyNode.numberType() == NumberType.FLOAT) { return ((Float) propertyValue <= (Float) passedValue); } else if(propertyNode.numberType() == NumberType.DOUBLE) { return ((Double) propertyValue <= (Double) passedValue); } else {
throw new UnsupportedExprException("Le supports only INT, LONG, DOUBLE, FLOAT values");
kcthota/JSONQuery
src/main/java/com/kcthota/JSONQuery/expressions/AppendToValueExpression.java
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class AppendToValueExpression extends StringValueExpression { private String appendText = ""; public AppendToValueExpression(String property, String appendText) { super(property); if(appendText!=null) { this.appendText = appendText; } } public AppendToValueExpression(String property, String appendText, ValueExpression innerExpression) { super(property, innerExpression); if(appendText!=null) { this.appendText = appendText; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
// Path: src/main/java/com/kcthota/JSONQuery/exceptions/UnsupportedExprException.java // @SuppressWarnings("serial") // public class UnsupportedExprException extends RuntimeException { // // public UnsupportedExprException(String message) { // super(message); // } // // } // Path: src/main/java/com/kcthota/JSONQuery/expressions/AppendToValueExpression.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException; /** * */ package com.kcthota.JSONQuery.expressions; /** * Returns the value of the property in the json node. * @author Krishna Chaitanya Thota * Apr 25, 2015 8:18:49 PM */ public class AppendToValueExpression extends StringValueExpression { private String appendText = ""; public AppendToValueExpression(String property, String appendText) { super(property); if(appendText!=null) { this.appendText = appendText; } } public AppendToValueExpression(String property, String appendText, ValueExpression innerExpression) { super(property, innerExpression); if(appendText!=null) { this.appendText = appendText; } } public JsonNode evaluate(JsonNode node) { JsonNode valueNode = super.evaluate(node); if(valueNode==null || !valueNode.isTextual()) {
throw new UnsupportedExprException("Property value is not a string");
calipho-sib/sparql-playground
src/test/java/swiss/sib/sparql/playground/SparqlServiceIntegrationTest.java
// Path: src/main/java/swiss/sib/sparql/playground/service/SparqlService.java // @Service // public class SparqlService implements InitializingBean { // // private static final Log logger = LogFactory.getLog(SparqlController.class); // // @Autowired // private SesameRepository repository; // // private Map<String, String> prefixes = null; // private String prefixesString; // // // public Query getQuery(String queryStr) throws SparqlTutorialException { // return repository.prepareQuery(queryStr); // } // // // public TupleQueryResult executeSelectQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (TupleQueryResult) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // public boolean executeAskQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (Boolean) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // public Object evaluateQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // private Object evaluateQuery(Query query, SparqlQueryType queryType) throws SparqlTutorialException { // try { // // switch(queryType){ // // case TUPLE_QUERY: return ((TupleQuery)query).evaluate(); // case GRAPH_QUERY: return ((GraphQuery)query).evaluate(); // case BOOLEAN_QUERY: return ((BooleanQuery)query).evaluate(); // default: throw new SparqlTutorialException("Unsupported query type: " + query.getClass().getName()); // // } // //; // } catch (QueryInterruptedException e) { // logger.info("Query interrupted", e); // throw new SparqlTutorialException("Query evaluation took too long"); // } catch (QueryEvaluationException e) { // logger.info("Query evaluation error", e); // throw new SparqlTutorialException("Query evaluation error: " + e.getMessage()); // } // } // // public Map<String, String> getPrefixes() { // return prefixes; // } // // public String getPrefixesString() { // return prefixesString; // } // // public void setPrefixesString(String prefixesString) { // this.prefixesString = prefixesString; // } // // public void setPrefixes(Map<String, String> prefixes) { // this.prefixes = prefixes; // } // // @Override // public void afterPropertiesSet() throws Exception { // this.prefixesString = IOUtils.readFile(Application.FOLDER + "/prefixes.ttl", ""); // // String prefixes[] = this.prefixesString.split("\n"); // Map<String, String> m = new TreeMap<String, String>(); // for(String p : prefixes){ // String[] ptks = p.split(" "); // m.put(ptks[1].replaceAll(":", ""), ptks[2].replaceAll("<", "").replaceAll(">", "")); // } // // this.setPrefixes(m); // } // // public void writeData(OutputStream out) { // if(isDataLoadAllowed()){ // repository.writeTriplesAsTurtle(out, prefixes); // }else { // try { // out.write("Loading data is not supported for native store (only available for memory store)".getBytes()); // } catch (IOException e) { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public long loadData(String data) { // if(isDataLoadAllowed()){ // repository.testLoadTurtleData(data); //check if data is ok first (returns exception if not) // repository.clearData(); // repository.loadTurtleData(data); // return repository.countTriplets(); // }else { // throw new SparqlTutorialException("Loading data is not supported for native store"); // } // // } // // public boolean isDataLoadAllowed() { // return repository.isDataLoadAllowed(); // } // // public long countNumberOfTriples() { // return repository.countTriplets(); // } // // }
import swiss.sib.sparql.playground.service.SparqlService; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore; import org.junit.runner.RunWith; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration;
package swiss.sib.sparql.playground; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {Application.class}) @WebAppConfiguration public class SparqlServiceIntegrationTest { @Autowired
// Path: src/main/java/swiss/sib/sparql/playground/service/SparqlService.java // @Service // public class SparqlService implements InitializingBean { // // private static final Log logger = LogFactory.getLog(SparqlController.class); // // @Autowired // private SesameRepository repository; // // private Map<String, String> prefixes = null; // private String prefixesString; // // // public Query getQuery(String queryStr) throws SparqlTutorialException { // return repository.prepareQuery(queryStr); // } // // // public TupleQueryResult executeSelectQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (TupleQueryResult) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // public boolean executeAskQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (Boolean) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // public Object evaluateQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // private Object evaluateQuery(Query query, SparqlQueryType queryType) throws SparqlTutorialException { // try { // // switch(queryType){ // // case TUPLE_QUERY: return ((TupleQuery)query).evaluate(); // case GRAPH_QUERY: return ((GraphQuery)query).evaluate(); // case BOOLEAN_QUERY: return ((BooleanQuery)query).evaluate(); // default: throw new SparqlTutorialException("Unsupported query type: " + query.getClass().getName()); // // } // //; // } catch (QueryInterruptedException e) { // logger.info("Query interrupted", e); // throw new SparqlTutorialException("Query evaluation took too long"); // } catch (QueryEvaluationException e) { // logger.info("Query evaluation error", e); // throw new SparqlTutorialException("Query evaluation error: " + e.getMessage()); // } // } // // public Map<String, String> getPrefixes() { // return prefixes; // } // // public String getPrefixesString() { // return prefixesString; // } // // public void setPrefixesString(String prefixesString) { // this.prefixesString = prefixesString; // } // // public void setPrefixes(Map<String, String> prefixes) { // this.prefixes = prefixes; // } // // @Override // public void afterPropertiesSet() throws Exception { // this.prefixesString = IOUtils.readFile(Application.FOLDER + "/prefixes.ttl", ""); // // String prefixes[] = this.prefixesString.split("\n"); // Map<String, String> m = new TreeMap<String, String>(); // for(String p : prefixes){ // String[] ptks = p.split(" "); // m.put(ptks[1].replaceAll(":", ""), ptks[2].replaceAll("<", "").replaceAll(">", "")); // } // // this.setPrefixes(m); // } // // public void writeData(OutputStream out) { // if(isDataLoadAllowed()){ // repository.writeTriplesAsTurtle(out, prefixes); // }else { // try { // out.write("Loading data is not supported for native store (only available for memory store)".getBytes()); // } catch (IOException e) { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public long loadData(String data) { // if(isDataLoadAllowed()){ // repository.testLoadTurtleData(data); //check if data is ok first (returns exception if not) // repository.clearData(); // repository.loadTurtleData(data); // return repository.countTriplets(); // }else { // throw new SparqlTutorialException("Loading data is not supported for native store"); // } // // } // // public boolean isDataLoadAllowed() { // return repository.isDataLoadAllowed(); // } // // public long countNumberOfTriples() { // return repository.countTriplets(); // } // // } // Path: src/test/java/swiss/sib/sparql/playground/SparqlServiceIntegrationTest.java import swiss.sib.sparql.playground.service.SparqlService; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore; import org.junit.runner.RunWith; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; package swiss.sib.sparql.playground; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {Application.class}) @WebAppConfiguration public class SparqlServiceIntegrationTest { @Autowired
private SparqlService sparqlService;
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/controller/SparqlController.java
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/service/SparqlService.java // @Service // public class SparqlService implements InitializingBean { // // private static final Log logger = LogFactory.getLog(SparqlController.class); // // @Autowired // private SesameRepository repository; // // private Map<String, String> prefixes = null; // private String prefixesString; // // // public Query getQuery(String queryStr) throws SparqlTutorialException { // return repository.prepareQuery(queryStr); // } // // // public TupleQueryResult executeSelectQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (TupleQueryResult) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // public boolean executeAskQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (Boolean) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // public Object evaluateQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // private Object evaluateQuery(Query query, SparqlQueryType queryType) throws SparqlTutorialException { // try { // // switch(queryType){ // // case TUPLE_QUERY: return ((TupleQuery)query).evaluate(); // case GRAPH_QUERY: return ((GraphQuery)query).evaluate(); // case BOOLEAN_QUERY: return ((BooleanQuery)query).evaluate(); // default: throw new SparqlTutorialException("Unsupported query type: " + query.getClass().getName()); // // } // //; // } catch (QueryInterruptedException e) { // logger.info("Query interrupted", e); // throw new SparqlTutorialException("Query evaluation took too long"); // } catch (QueryEvaluationException e) { // logger.info("Query evaluation error", e); // throw new SparqlTutorialException("Query evaluation error: " + e.getMessage()); // } // } // // public Map<String, String> getPrefixes() { // return prefixes; // } // // public String getPrefixesString() { // return prefixesString; // } // // public void setPrefixesString(String prefixesString) { // this.prefixesString = prefixesString; // } // // public void setPrefixes(Map<String, String> prefixes) { // this.prefixes = prefixes; // } // // @Override // public void afterPropertiesSet() throws Exception { // this.prefixesString = IOUtils.readFile(Application.FOLDER + "/prefixes.ttl", ""); // // String prefixes[] = this.prefixesString.split("\n"); // Map<String, String> m = new TreeMap<String, String>(); // for(String p : prefixes){ // String[] ptks = p.split(" "); // m.put(ptks[1].replaceAll(":", ""), ptks[2].replaceAll("<", "").replaceAll(">", "")); // } // // this.setPrefixes(m); // } // // public void writeData(OutputStream out) { // if(isDataLoadAllowed()){ // repository.writeTriplesAsTurtle(out, prefixes); // }else { // try { // out.write("Loading data is not supported for native store (only available for memory store)".getBytes()); // } catch (IOException e) { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public long loadData(String data) { // if(isDataLoadAllowed()){ // repository.testLoadTurtleData(data); //check if data is ok first (returns exception if not) // repository.clearData(); // repository.loadTurtleData(data); // return repository.countTriplets(); // }else { // throw new SparqlTutorialException("Loading data is not supported for native store"); // } // // } // // public boolean isDataLoadAllowed() { // return repository.isDataLoadAllowed(); // } // // public long countNumberOfTriples() { // return repository.countTriplets(); // } // // }
import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openrdf.query.QueryEvaluationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.service.SparqlService;
package swiss.sib.sparql.playground.controller; /** * Sparql controller that provied SPARQL endpoint in (json, xml, csv and tsv) * Utilities serviecs to get and load turtle data and retrieve common prefixes * * @author Daniel Teixeira http://github.com/ddtxra * */ @RestController public class SparqlController { //private static final Log logger = LogFactory.getLog(SparqlController.class); @Autowired
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/service/SparqlService.java // @Service // public class SparqlService implements InitializingBean { // // private static final Log logger = LogFactory.getLog(SparqlController.class); // // @Autowired // private SesameRepository repository; // // private Map<String, String> prefixes = null; // private String prefixesString; // // // public Query getQuery(String queryStr) throws SparqlTutorialException { // return repository.prepareQuery(queryStr); // } // // // public TupleQueryResult executeSelectQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (TupleQueryResult) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // public boolean executeAskQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return (Boolean) evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // public Object evaluateQuery(String queryStr) { // Query query = repository.prepareQuery(queryStr); // return evaluateQuery(query, SparqlQueryType.getQueryType(query)); // } // // // private Object evaluateQuery(Query query, SparqlQueryType queryType) throws SparqlTutorialException { // try { // // switch(queryType){ // // case TUPLE_QUERY: return ((TupleQuery)query).evaluate(); // case GRAPH_QUERY: return ((GraphQuery)query).evaluate(); // case BOOLEAN_QUERY: return ((BooleanQuery)query).evaluate(); // default: throw new SparqlTutorialException("Unsupported query type: " + query.getClass().getName()); // // } // //; // } catch (QueryInterruptedException e) { // logger.info("Query interrupted", e); // throw new SparqlTutorialException("Query evaluation took too long"); // } catch (QueryEvaluationException e) { // logger.info("Query evaluation error", e); // throw new SparqlTutorialException("Query evaluation error: " + e.getMessage()); // } // } // // public Map<String, String> getPrefixes() { // return prefixes; // } // // public String getPrefixesString() { // return prefixesString; // } // // public void setPrefixesString(String prefixesString) { // this.prefixesString = prefixesString; // } // // public void setPrefixes(Map<String, String> prefixes) { // this.prefixes = prefixes; // } // // @Override // public void afterPropertiesSet() throws Exception { // this.prefixesString = IOUtils.readFile(Application.FOLDER + "/prefixes.ttl", ""); // // String prefixes[] = this.prefixesString.split("\n"); // Map<String, String> m = new TreeMap<String, String>(); // for(String p : prefixes){ // String[] ptks = p.split(" "); // m.put(ptks[1].replaceAll(":", ""), ptks[2].replaceAll("<", "").replaceAll(">", "")); // } // // this.setPrefixes(m); // } // // public void writeData(OutputStream out) { // if(isDataLoadAllowed()){ // repository.writeTriplesAsTurtle(out, prefixes); // }else { // try { // out.write("Loading data is not supported for native store (only available for memory store)".getBytes()); // } catch (IOException e) { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public long loadData(String data) { // if(isDataLoadAllowed()){ // repository.testLoadTurtleData(data); //check if data is ok first (returns exception if not) // repository.clearData(); // repository.loadTurtleData(data); // return repository.countTriplets(); // }else { // throw new SparqlTutorialException("Loading data is not supported for native store"); // } // // } // // public boolean isDataLoadAllowed() { // return repository.isDataLoadAllowed(); // } // // public long countNumberOfTriples() { // return repository.countTriplets(); // } // // } // Path: src/main/java/swiss/sib/sparql/playground/controller/SparqlController.java import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openrdf.query.QueryEvaluationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.service.SparqlService; package swiss.sib.sparql.playground.controller; /** * Sparql controller that provied SPARQL endpoint in (json, xml, csv and tsv) * Utilities serviecs to get and load turtle data and retrieve common prefixes * * @author Daniel Teixeira http://github.com/ddtxra * */ @RestController public class SparqlController { //private static final Log logger = LogFactory.getLog(SparqlController.class); @Autowired
private SparqlService sparqlService;
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/controller/ErrorHandlerController.java
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // }
import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import swiss.sib.sparql.playground.exception.SparqlTutorialException;
package swiss.sib.sparql.playground.controller; /** * A global error handler * @author Daniel Teixeira http://github.com/ddtxra * */ @ControllerAdvice @RestController public class ErrorHandlerController { @ResponseStatus(value = HttpStatus.BAD_REQUEST)
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // Path: src/main/java/swiss/sib/sparql/playground/controller/ErrorHandlerController.java import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import swiss.sib.sparql.playground.exception.SparqlTutorialException; package swiss.sib.sparql.playground.controller; /** * A global error handler * @author Daniel Teixeira http://github.com/ddtxra * */ @ControllerAdvice @RestController public class ErrorHandlerController { @ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(SparqlTutorialException.class)
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/repository/impl/SesameRepositoryImpl.java
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/repository/SesameRepository.java // public interface SesameRepository{ // // void testLoadTurtleData(String data); // void loadTurtleData(String data); // boolean isDataLoadAllowed(); // void clearData(); // // void writeTriplesAsTurtle(OutputStream out, Map<String, String> prefixes); // // Query prepareQuery(String sparqlQuery); // // long countTriplets(); // // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.openrdf.sail.nativerdf.NativeStore; import org.springframework.beans.factory.InitializingBean; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.repository.SesameRepository; import info.aduna.iteration.Iterations;
package swiss.sib.sparql.playground.repository.impl; /** * RDF data store for sesame * * @author Daniel Teixeira http://github.com/ddtxra * */ @org.springframework.stereotype.Repository public class SesameRepositoryImpl implements SesameRepository, InitializingBean { private static final Log logger = LogFactory.getLog(SesameRepositoryImpl.class); // Read documentation: http://rdf4j.org/sesame/2.7/docs/users.docbook?view // http://www.cambridgesemantics.com/semantic-university/sparql-by-example private Repository rep = null; private SailRepository testRepo; private RepositoryConnection conn = null; @Override public Query prepareQuery(String sparqlQuery) { try { return conn.prepareQuery(QueryLanguage.SPARQL, sparqlQuery); } catch (RepositoryException | MalformedQueryException e) { e.printStackTrace();
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/repository/SesameRepository.java // public interface SesameRepository{ // // void testLoadTurtleData(String data); // void loadTurtleData(String data); // boolean isDataLoadAllowed(); // void clearData(); // // void writeTriplesAsTurtle(OutputStream out, Map<String, String> prefixes); // // Query prepareQuery(String sparqlQuery); // // long countTriplets(); // // // } // Path: src/main/java/swiss/sib/sparql/playground/repository/impl/SesameRepositoryImpl.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.openrdf.sail.nativerdf.NativeStore; import org.springframework.beans.factory.InitializingBean; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.repository.SesameRepository; import info.aduna.iteration.Iterations; package swiss.sib.sparql.playground.repository.impl; /** * RDF data store for sesame * * @author Daniel Teixeira http://github.com/ddtxra * */ @org.springframework.stereotype.Repository public class SesameRepositoryImpl implements SesameRepository, InitializingBean { private static final Log logger = LogFactory.getLog(SesameRepositoryImpl.class); // Read documentation: http://rdf4j.org/sesame/2.7/docs/users.docbook?view // http://www.cambridgesemantics.com/semantic-university/sparql-by-example private Repository rep = null; private SailRepository testRepo; private RepositoryConnection conn = null; @Override public Query prepareQuery(String sparqlQuery) { try { return conn.prepareQuery(QueryLanguage.SPARQL, sparqlQuery); } catch (RepositoryException | MalformedQueryException e) { e.printStackTrace();
throw new SparqlTutorialException(e);
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/repository/impl/SesameRepositoryImpl.java
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/repository/SesameRepository.java // public interface SesameRepository{ // // void testLoadTurtleData(String data); // void loadTurtleData(String data); // boolean isDataLoadAllowed(); // void clearData(); // // void writeTriplesAsTurtle(OutputStream out, Map<String, String> prefixes); // // Query prepareQuery(String sparqlQuery); // // long countTriplets(); // // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.openrdf.sail.nativerdf.NativeStore; import org.springframework.beans.factory.InitializingBean; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.repository.SesameRepository; import info.aduna.iteration.Iterations;
package swiss.sib.sparql.playground.repository.impl; /** * RDF data store for sesame * * @author Daniel Teixeira http://github.com/ddtxra * */ @org.springframework.stereotype.Repository public class SesameRepositoryImpl implements SesameRepository, InitializingBean { private static final Log logger = LogFactory.getLog(SesameRepositoryImpl.class); // Read documentation: http://rdf4j.org/sesame/2.7/docs/users.docbook?view // http://www.cambridgesemantics.com/semantic-university/sparql-by-example private Repository rep = null; private SailRepository testRepo; private RepositoryConnection conn = null; @Override public Query prepareQuery(String sparqlQuery) { try { return conn.prepareQuery(QueryLanguage.SPARQL, sparqlQuery); } catch (RepositoryException | MalformedQueryException e) { e.printStackTrace(); throw new SparqlTutorialException(e); } } @PostConstruct public void init() throws Exception { boolean nativeConfig = (System.getProperty("repository.type") != null) && (System.getProperty("repository.type").equals("native")); if (nativeConfig) { logger.info("Found repository type native property!"); } // If native configuration is set File sesameDataFolder = null; File sesameDataValueFile = null; if (nativeConfig) {
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // // Path: src/main/java/swiss/sib/sparql/playground/repository/SesameRepository.java // public interface SesameRepository{ // // void testLoadTurtleData(String data); // void loadTurtleData(String data); // boolean isDataLoadAllowed(); // void clearData(); // // void writeTriplesAsTurtle(OutputStream out, Map<String, String> prefixes); // // Query prepareQuery(String sparqlQuery); // // long countTriplets(); // // // } // Path: src/main/java/swiss/sib/sparql/playground/repository/impl/SesameRepositoryImpl.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.Query; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import org.openrdf.sail.memory.MemoryStore; import org.openrdf.sail.nativerdf.NativeStore; import org.springframework.beans.factory.InitializingBean; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.exception.SparqlTutorialException; import swiss.sib.sparql.playground.repository.SesameRepository; import info.aduna.iteration.Iterations; package swiss.sib.sparql.playground.repository.impl; /** * RDF data store for sesame * * @author Daniel Teixeira http://github.com/ddtxra * */ @org.springframework.stereotype.Repository public class SesameRepositoryImpl implements SesameRepository, InitializingBean { private static final Log logger = LogFactory.getLog(SesameRepositoryImpl.class); // Read documentation: http://rdf4j.org/sesame/2.7/docs/users.docbook?view // http://www.cambridgesemantics.com/semantic-university/sparql-by-example private Repository rep = null; private SailRepository testRepo; private RepositoryConnection conn = null; @Override public Query prepareQuery(String sparqlQuery) { try { return conn.prepareQuery(QueryLanguage.SPARQL, sparqlQuery); } catch (RepositoryException | MalformedQueryException e) { e.printStackTrace(); throw new SparqlTutorialException(e); } } @PostConstruct public void init() throws Exception { boolean nativeConfig = (System.getProperty("repository.type") != null) && (System.getProperty("repository.type").equals("native")); if (nativeConfig) { logger.info("Found repository type native property!"); } // If native configuration is set File sesameDataFolder = null; File sesameDataValueFile = null; if (nativeConfig) {
sesameDataFolder = new File(Application.FOLDER + "/sesame-db");
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // }
import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import javax.imageio.ImageIO; import swiss.sib.sparql.playground.exception.SparqlTutorialException;
package swiss.sib.sparql.playground.utils; /** * IO utitly class * @author Daniel Teixeira http://github.com/ddtxra * */ public class IOUtils { public static String readFile(String path, String orValue) { try { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, Charset.forName("UTF-8")); } catch (IOException e) { if(orValue != null){ return orValue; }else { e.printStackTrace();
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // Path: src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import javax.imageio.ImageIO; import swiss.sib.sparql.playground.exception.SparqlTutorialException; package swiss.sib.sparql.playground.utils; /** * IO utitly class * @author Daniel Teixeira http://github.com/ddtxra * */ public class IOUtils { public static String readFile(String path, String orValue) { try { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, Charset.forName("UTF-8")); } catch (IOException e) { if(orValue != null){ return orValue; }else { e.printStackTrace();
throw new SparqlTutorialException(e);
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/domain/SparqlQueryType.java
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // }
import org.openrdf.query.BooleanQuery; import org.openrdf.query.GraphQuery; import org.openrdf.query.Query; import org.openrdf.query.TupleQuery; import swiss.sib.sparql.playground.exception.SparqlTutorialException;
package swiss.sib.sparql.playground.domain; /** * A sparql query used for the examples * * @author Daniel Teixeira http://github.com/ddtxra * */ public enum SparqlQueryType { TUPLE_QUERY, BOOLEAN_QUERY, GRAPH_QUERY; public static SparqlQueryType getQueryType(Query query){ if (query instanceof TupleQuery) { return SparqlQueryType.TUPLE_QUERY; }else if (query instanceof GraphQuery) { return SparqlQueryType.GRAPH_QUERY; } else if (query instanceof BooleanQuery) { return SparqlQueryType.BOOLEAN_QUERY;
// Path: src/main/java/swiss/sib/sparql/playground/exception/SparqlTutorialException.java // public class SparqlTutorialException extends RuntimeException { // // public SparqlTutorialException(Exception e) { // super(e); // } // // public SparqlTutorialException(String msg) { // super(msg); // } // // private static final long serialVersionUID = 4604803406207435360L; // // } // Path: src/main/java/swiss/sib/sparql/playground/domain/SparqlQueryType.java import org.openrdf.query.BooleanQuery; import org.openrdf.query.GraphQuery; import org.openrdf.query.Query; import org.openrdf.query.TupleQuery; import swiss.sib.sparql.playground.exception.SparqlTutorialException; package swiss.sib.sparql.playground.domain; /** * A sparql query used for the examples * * @author Daniel Teixeira http://github.com/ddtxra * */ public enum SparqlQueryType { TUPLE_QUERY, BOOLEAN_QUERY, GRAPH_QUERY; public static SparqlQueryType getQueryType(Query query){ if (query instanceof TupleQuery) { return SparqlQueryType.TUPLE_QUERY; }else if (query instanceof GraphQuery) { return SparqlQueryType.GRAPH_QUERY; } else if (query instanceof BooleanQuery) { return SparqlQueryType.BOOLEAN_QUERY;
} else throw new SparqlTutorialException("Unsupported query type: " + query.getClass().getName());
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/service/PageService.java
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java // public class IOUtils { // // public static String readFile(String path, String orValue) { // try { // byte[] encoded = Files.readAllBytes(Paths.get(path)); // return new String(encoded, Charset.forName("UTF-8")); // } catch (IOException e) { // if(orValue != null){ // return orValue; // }else { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public static byte[] readImage(String extension, File f) { // // try { // // // Retrieve image from the classpath. // InputStream is = new FileInputStream(f); // // // Prepare buffered image. // BufferedImage img = ImageIO.read(is); // // // Create a byte array output stream. // ByteArrayOutputStream bao = new ByteArrayOutputStream(); // // // Write to output stream // ImageIO.write(img, extension, bao); // // return bao.toByteArray(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // public static void streamFile(File file, OutputStream outStream) { // // try { // // FileInputStream inputStream = new FileInputStream(file); // // byte[] buffer = new byte[4096]; // int bytesRead = -1; // // // write bytes read from the input stream into the output stream // while ((bytesRead = inputStream.read(buffer)) != -1) { // outStream.write(buffer, 0, bytesRead); // } // // inputStream.close(); // outStream.close(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.utils.IOUtils;
package swiss.sib.sparql.playground.service; /** * The page service * * @author Daniel Teixeira http://github.com/ddtxra * */ @Service public class PageService { private static final String ABOUT_PAGE = "99_About"; @Cacheable("page-tree") public Map<String, Object> getPagesTree() throws IOException { Map<String, Object> tree = new HashMap<String, Object>(); List<Object> pages = new ArrayList<Object>(); tree.put("tree", pages);
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java // public class IOUtils { // // public static String readFile(String path, String orValue) { // try { // byte[] encoded = Files.readAllBytes(Paths.get(path)); // return new String(encoded, Charset.forName("UTF-8")); // } catch (IOException e) { // if(orValue != null){ // return orValue; // }else { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public static byte[] readImage(String extension, File f) { // // try { // // // Retrieve image from the classpath. // InputStream is = new FileInputStream(f); // // // Prepare buffered image. // BufferedImage img = ImageIO.read(is); // // // Create a byte array output stream. // ByteArrayOutputStream bao = new ByteArrayOutputStream(); // // // Write to output stream // ImageIO.write(img, extension, bao); // // return bao.toByteArray(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // public static void streamFile(File file, OutputStream outStream) { // // try { // // FileInputStream inputStream = new FileInputStream(file); // // byte[] buffer = new byte[4096]; // int bytesRead = -1; // // // write bytes read from the input stream into the output stream // while ((bytesRead = inputStream.read(buffer)) != -1) { // outStream.write(buffer, 0, bytesRead); // } // // inputStream.close(); // outStream.close(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // // } // Path: src/main/java/swiss/sib/sparql/playground/service/PageService.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.utils.IOUtils; package swiss.sib.sparql.playground.service; /** * The page service * * @author Daniel Teixeira http://github.com/ddtxra * */ @Service public class PageService { private static final String ABOUT_PAGE = "99_About"; @Cacheable("page-tree") public Map<String, Object> getPagesTree() throws IOException { Map<String, Object> tree = new HashMap<String, Object>(); List<Object> pages = new ArrayList<Object>(); tree.put("tree", pages);
for (final File fileEntry : new File(Application.FOLDER + "/pages/").listFiles()) {
calipho-sib/sparql-playground
src/main/java/swiss/sib/sparql/playground/service/PageService.java
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java // public class IOUtils { // // public static String readFile(String path, String orValue) { // try { // byte[] encoded = Files.readAllBytes(Paths.get(path)); // return new String(encoded, Charset.forName("UTF-8")); // } catch (IOException e) { // if(orValue != null){ // return orValue; // }else { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public static byte[] readImage(String extension, File f) { // // try { // // // Retrieve image from the classpath. // InputStream is = new FileInputStream(f); // // // Prepare buffered image. // BufferedImage img = ImageIO.read(is); // // // Create a byte array output stream. // ByteArrayOutputStream bao = new ByteArrayOutputStream(); // // // Write to output stream // ImageIO.write(img, extension, bao); // // return bao.toByteArray(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // public static void streamFile(File file, OutputStream outStream) { // // try { // // FileInputStream inputStream = new FileInputStream(file); // // byte[] buffer = new byte[4096]; // int bytesRead = -1; // // // write bytes read from the input stream into the output stream // while ((bytesRead = inputStream.read(buffer)) != -1) { // outStream.write(buffer, 0, bytesRead); // } // // inputStream.close(); // outStream.close(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.utils.IOUtils;
package swiss.sib.sparql.playground.service; /** * The page service * * @author Daniel Teixeira http://github.com/ddtxra * */ @Service public class PageService { private static final String ABOUT_PAGE = "99_About"; @Cacheable("page-tree") public Map<String, Object> getPagesTree() throws IOException { Map<String, Object> tree = new HashMap<String, Object>(); List<Object> pages = new ArrayList<Object>(); tree.put("tree", pages); for (final File fileEntry : new File(Application.FOLDER + "/pages/").listFiles()) { if (fileEntry.isFile()) { pages.add(buildPage(fileEntry, fileEntry.getName())); } } pages.add(buildPage(new File("README.md"), ABOUT_PAGE + ".md")); return tree; } private Object buildPage(File f, String name) { Map<String, String> m = new HashMap<String, String>(); m.put("path", "generalities/" + name); m.put("type", "blob"); m.put("url", ""); return m; } @Cacheable("page") public String getPage(String page) { if(page.equals(ABOUT_PAGE)){
// Path: src/main/java/swiss/sib/sparql/playground/Application.java // @SpringBootApplication // public class Application { // // private static final Log logger = LogFactory.getLog(Application.class); // // public static String FOLDER = "default"; // // public static void main(String[] args) { // // logger.info("SPARQL Playground\n"); // // // if (args.length > 0) { // String folderAux = args[0]; // if (new File(folderAux).exists()){ // FOLDER = folderAux; // }else logger.info(folderAux + " folder not found"); // } // logger.info("Reading from " + FOLDER); // // SpringApplication.run(Application.class, args); // // String port = null; // if (System.getProperty("server.port") == null) { // port = "8080"; // logger.info("Taking default port 8080. The value of the port can be changed, by adding the jvm option: -Dserver.port=8090"); // } else { // port = System.getProperty("server.port"); // logger.info("server.port option found. Taking port " + port); // } // // String serverUrl = "http://localhost:" + port; // path to your new file // // logger.info("Server started at " + serverUrl); // // } // // @Bean // public CacheManager cacheManager() { // return new ConcurrentMapCacheManager("asset", "queries", "faqs", "page", "page-tree"); // } // // } // // Path: src/main/java/swiss/sib/sparql/playground/utils/IOUtils.java // public class IOUtils { // // public static String readFile(String path, String orValue) { // try { // byte[] encoded = Files.readAllBytes(Paths.get(path)); // return new String(encoded, Charset.forName("UTF-8")); // } catch (IOException e) { // if(orValue != null){ // return orValue; // }else { // e.printStackTrace(); // throw new SparqlTutorialException(e); // } // } // } // // public static byte[] readImage(String extension, File f) { // // try { // // // Retrieve image from the classpath. // InputStream is = new FileInputStream(f); // // // Prepare buffered image. // BufferedImage img = ImageIO.read(is); // // // Create a byte array output stream. // ByteArrayOutputStream bao = new ByteArrayOutputStream(); // // // Write to output stream // ImageIO.write(img, extension, bao); // // return bao.toByteArray(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // public static void streamFile(File file, OutputStream outStream) { // // try { // // FileInputStream inputStream = new FileInputStream(file); // // byte[] buffer = new byte[4096]; // int bytesRead = -1; // // // write bytes read from the input stream into the output stream // while ((bytesRead = inputStream.read(buffer)) != -1) { // outStream.write(buffer, 0, bytesRead); // } // // inputStream.close(); // outStream.close(); // } catch (IOException e) { // throw new SparqlTutorialException(e); // } // } // // // // } // Path: src/main/java/swiss/sib/sparql/playground/service/PageService.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import swiss.sib.sparql.playground.Application; import swiss.sib.sparql.playground.utils.IOUtils; package swiss.sib.sparql.playground.service; /** * The page service * * @author Daniel Teixeira http://github.com/ddtxra * */ @Service public class PageService { private static final String ABOUT_PAGE = "99_About"; @Cacheable("page-tree") public Map<String, Object> getPagesTree() throws IOException { Map<String, Object> tree = new HashMap<String, Object>(); List<Object> pages = new ArrayList<Object>(); tree.put("tree", pages); for (final File fileEntry : new File(Application.FOLDER + "/pages/").listFiles()) { if (fileEntry.isFile()) { pages.add(buildPage(fileEntry, fileEntry.getName())); } } pages.add(buildPage(new File("README.md"), ABOUT_PAGE + ".md")); return tree; } private Object buildPage(File f, String name) { Map<String, String> m = new HashMap<String, String>(); m.put("path", "generalities/" + name); m.put("type", "blob"); m.put("url", ""); return m; } @Cacheable("page") public String getPage(String page) { if(page.equals(ABOUT_PAGE)){
return IOUtils.readFile("README.md", null);
adelbs/ISO8583
src/test/java/org/adelbs/iso8583/clientserver/MockClientMessageExecutor.java
// Path: src/main/java/org/adelbs/iso8583/exception/ConnectionException.java // public class ConnectionException extends Exception { // // private static final long serialVersionUID = 2L; // // public ConnectionException(String message) { // super(message); // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.adelbs.iso8583.exception.ConnectionException;
MockClientMessageExecutor executor = INSTANCES.get(key); if(executor == null){ executor = new MockClientMessageExecutor(host, port); INSTANCES.put(key, executor); } return executor; } public List<MockResult> executeSimultaneous(final int threadsToRun) throws MockISOException{ ExecutorService executor = null; final List<MockResult> results = new ArrayList<MockResult>(); try{ executor = Executors.newFixedThreadPool(threadsToRun); final List<MockISOClient> clients = new ArrayList<MockISOClient>(); for(int i=0;i<threadsToRun;i++){ clients.add(new MockISOClient(host, port)); } final List<Future<MockResult>> taskList = executor.invokeAll(clients); taskList.forEach(task->{ try { results.add((MockResult) task.get()); } catch (Exception e) { e.printStackTrace(); } }); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); e1.printStackTrace();
// Path: src/main/java/org/adelbs/iso8583/exception/ConnectionException.java // public class ConnectionException extends Exception { // // private static final long serialVersionUID = 2L; // // public ConnectionException(String message) { // super(message); // } // // } // Path: src/test/java/org/adelbs/iso8583/clientserver/MockClientMessageExecutor.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.adelbs.iso8583.exception.ConnectionException; MockClientMessageExecutor executor = INSTANCES.get(key); if(executor == null){ executor = new MockClientMessageExecutor(host, port); INSTANCES.put(key, executor); } return executor; } public List<MockResult> executeSimultaneous(final int threadsToRun) throws MockISOException{ ExecutorService executor = null; final List<MockResult> results = new ArrayList<MockResult>(); try{ executor = Executors.newFixedThreadPool(threadsToRun); final List<MockISOClient> clients = new ArrayList<MockISOClient>(); for(int i=0;i<threadsToRun;i++){ clients.add(new MockISOClient(host, port)); } final List<Future<MockResult>> taskList = executor.invokeAll(clients); taskList.forEach(task->{ try { results.add((MockResult) task.get()); } catch (Exception e) { e.printStackTrace(); } }); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); e1.printStackTrace();
} catch (IOException | ConnectionException e) {
adelbs/ISO8583
src/test/java/org/adelbs/iso8583/vo/FieldVOTest.java
// Path: src/main/java/org/adelbs/iso8583/helper/BSInterpreter.java // public class BSInterpreter { // // private static GroovyShell shell; // private String snipetBS; // // public BSInterpreter() { // snipetBS = "Object[] BIT = new Object[255];\n" // + "public boolean ignore() {return false;}\n"; // } // // public boolean evaluate(String dynaCondition) { // boolean result = true; // String cond = (dynaCondition != null) ? dynaCondition.trim() : ""; // if (cond.indexOf("return ignore();") > -1) { // result = false; // } // else if (cond.length() > 0 && !cond.equals("true")) { // final Object condition = getShell().evaluate(snipetBS + dynaCondition); // if (!(condition instanceof Boolean)) throw new IllegalArgumentException("The expression do not generates a boolean result"); // // result = ((boolean) condition); // } // // return result; // } // // public void concatSnipet(String snipet) { // snipetBS += snipet; // } // // private static GroovyShell getShell() { // if (shell == null) { // shell = new GroovyShell(); // shell.evaluate("true"); // } // return shell; // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.adelbs.iso8583.helper.BSInterpreter; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
package org.adelbs.iso8583.vo; public class FieldVOTest { private FieldVO fieldVO; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { this.fieldVO = new FieldVO(); } @After public void tearDown() throws Exception { } @Test public void testIsIgnored_BasicTrueFalse() {
// Path: src/main/java/org/adelbs/iso8583/helper/BSInterpreter.java // public class BSInterpreter { // // private static GroovyShell shell; // private String snipetBS; // // public BSInterpreter() { // snipetBS = "Object[] BIT = new Object[255];\n" // + "public boolean ignore() {return false;}\n"; // } // // public boolean evaluate(String dynaCondition) { // boolean result = true; // String cond = (dynaCondition != null) ? dynaCondition.trim() : ""; // if (cond.indexOf("return ignore();") > -1) { // result = false; // } // else if (cond.length() > 0 && !cond.equals("true")) { // final Object condition = getShell().evaluate(snipetBS + dynaCondition); // if (!(condition instanceof Boolean)) throw new IllegalArgumentException("The expression do not generates a boolean result"); // // result = ((boolean) condition); // } // // return result; // } // // public void concatSnipet(String snipet) { // snipetBS += snipet; // } // // private static GroovyShell getShell() { // if (shell == null) { // shell = new GroovyShell(); // shell.evaluate("true"); // } // return shell; // } // } // Path: src/test/java/org/adelbs/iso8583/vo/FieldVOTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.adelbs.iso8583.helper.BSInterpreter; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; package org.adelbs.iso8583.vo; public class FieldVOTest { private FieldVO fieldVO; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { this.fieldVO = new FieldVO(); } @After public void tearDown() throws Exception { } @Test public void testIsIgnored_BasicTrueFalse() {
BSInterpreter bsInt = new BSInterpreter();
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/payload/PayloadTransformator.java
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // // Path: src/main/java/org/adelbs/iso8583/constants/TypeEnum.java // public enum TypeEnum { // // ALPHANUMERIC, TLV; // // public static TypeEnum getType(String value) { // if ("ALPHANUMERIC".equals(value)) // return TypeEnum.ALPHANUMERIC; // else if ("TLV".equals(value)) // return TypeEnum.TLV; // // return TypeEnum.ALPHANUMERIC; // } // } // // Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // // Path: src/main/java/org/adelbs/iso8583/util/Encoding.java // public interface Encoding { // // String convert(byte[] bytesToConvert); // // byte[] convert(String strToConvert); // // /** // * Some encoding algorithms need more the one byte to represent an ASCII character. // * So its original byte size, after the conversion, may change. // * This method receives the ascii length and returns what would be the ammount of bytes // * necessary to hold this value converted // * // * @param asciiLength length of the ascii value // * @return the length of the converted value // */ // int getEncondedByteLength(final int asciiLength); // // int getMinBitmapSize(); // // // String convertBitmap(byte[] binaryBitmap); // // byte[] convertBitmap(String binaryBitmap); // // }
import java.util.HashMap; import java.util.Map; import org.adelbs.iso8583.constants.EncodingEnum; import org.adelbs.iso8583.constants.TypeEnum; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.adelbs.iso8583.util.Encoding;
package org.adelbs.iso8583.payload; /** * Factory class to handle instances of {@link Transformator} */ public class PayloadTransformator { private final Encoding encoding; private static Map<String, PayloadTransformator> INSTANCES = new HashMap<String, PayloadTransformator>();
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // // Path: src/main/java/org/adelbs/iso8583/constants/TypeEnum.java // public enum TypeEnum { // // ALPHANUMERIC, TLV; // // public static TypeEnum getType(String value) { // if ("ALPHANUMERIC".equals(value)) // return TypeEnum.ALPHANUMERIC; // else if ("TLV".equals(value)) // return TypeEnum.TLV; // // return TypeEnum.ALPHANUMERIC; // } // } // // Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // // Path: src/main/java/org/adelbs/iso8583/util/Encoding.java // public interface Encoding { // // String convert(byte[] bytesToConvert); // // byte[] convert(String strToConvert); // // /** // * Some encoding algorithms need more the one byte to represent an ASCII character. // * So its original byte size, after the conversion, may change. // * This method receives the ascii length and returns what would be the ammount of bytes // * necessary to hold this value converted // * // * @param asciiLength length of the ascii value // * @return the length of the converted value // */ // int getEncondedByteLength(final int asciiLength); // // int getMinBitmapSize(); // // // String convertBitmap(byte[] binaryBitmap); // // byte[] convertBitmap(String binaryBitmap); // // } // Path: src/main/java/org/adelbs/iso8583/payload/PayloadTransformator.java import java.util.HashMap; import java.util.Map; import org.adelbs.iso8583.constants.EncodingEnum; import org.adelbs.iso8583.constants.TypeEnum; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.adelbs.iso8583.util.Encoding; package org.adelbs.iso8583.payload; /** * Factory class to handle instances of {@link Transformator} */ public class PayloadTransformator { private final Encoding encoding; private static Map<String, PayloadTransformator> INSTANCES = new HashMap<String, PayloadTransformator>();
private static Map<TypeEnum, Transformator> TRANSFORMATORS = new HashMap<TypeEnum, Transformator>();
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/payload/PayloadTransformator.java
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // // Path: src/main/java/org/adelbs/iso8583/constants/TypeEnum.java // public enum TypeEnum { // // ALPHANUMERIC, TLV; // // public static TypeEnum getType(String value) { // if ("ALPHANUMERIC".equals(value)) // return TypeEnum.ALPHANUMERIC; // else if ("TLV".equals(value)) // return TypeEnum.TLV; // // return TypeEnum.ALPHANUMERIC; // } // } // // Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // // Path: src/main/java/org/adelbs/iso8583/util/Encoding.java // public interface Encoding { // // String convert(byte[] bytesToConvert); // // byte[] convert(String strToConvert); // // /** // * Some encoding algorithms need more the one byte to represent an ASCII character. // * So its original byte size, after the conversion, may change. // * This method receives the ascii length and returns what would be the ammount of bytes // * necessary to hold this value converted // * // * @param asciiLength length of the ascii value // * @return the length of the converted value // */ // int getEncondedByteLength(final int asciiLength); // // int getMinBitmapSize(); // // // String convertBitmap(byte[] binaryBitmap); // // byte[] convertBitmap(String binaryBitmap); // // }
import java.util.HashMap; import java.util.Map; import org.adelbs.iso8583.constants.EncodingEnum; import org.adelbs.iso8583.constants.TypeEnum; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.adelbs.iso8583.util.Encoding;
package org.adelbs.iso8583.payload; /** * Factory class to handle instances of {@link Transformator} */ public class PayloadTransformator { private final Encoding encoding; private static Map<String, PayloadTransformator> INSTANCES = new HashMap<String, PayloadTransformator>(); private static Map<TypeEnum, Transformator> TRANSFORMATORS = new HashMap<TypeEnum, Transformator>(); /** * Get a new instance of PayloadTransformator. Utilizes Lazy initialization and its not thread safe * @param encoding Which type of enconde this transformator will be specialized * @return a new instantiated PayloadTransformator */
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // // Path: src/main/java/org/adelbs/iso8583/constants/TypeEnum.java // public enum TypeEnum { // // ALPHANUMERIC, TLV; // // public static TypeEnum getType(String value) { // if ("ALPHANUMERIC".equals(value)) // return TypeEnum.ALPHANUMERIC; // else if ("TLV".equals(value)) // return TypeEnum.TLV; // // return TypeEnum.ALPHANUMERIC; // } // } // // Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // // Path: src/main/java/org/adelbs/iso8583/util/Encoding.java // public interface Encoding { // // String convert(byte[] bytesToConvert); // // byte[] convert(String strToConvert); // // /** // * Some encoding algorithms need more the one byte to represent an ASCII character. // * So its original byte size, after the conversion, may change. // * This method receives the ascii length and returns what would be the ammount of bytes // * necessary to hold this value converted // * // * @param asciiLength length of the ascii value // * @return the length of the converted value // */ // int getEncondedByteLength(final int asciiLength); // // int getMinBitmapSize(); // // // String convertBitmap(byte[] binaryBitmap); // // byte[] convertBitmap(String binaryBitmap); // // } // Path: src/main/java/org/adelbs/iso8583/payload/PayloadTransformator.java import java.util.HashMap; import java.util.Map; import org.adelbs.iso8583.constants.EncodingEnum; import org.adelbs.iso8583.constants.TypeEnum; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.adelbs.iso8583.util.Encoding; package org.adelbs.iso8583.payload; /** * Factory class to handle instances of {@link Transformator} */ public class PayloadTransformator { private final Encoding encoding; private static Map<String, PayloadTransformator> INSTANCES = new HashMap<String, PayloadTransformator>(); private static Map<TypeEnum, Transformator> TRANSFORMATORS = new HashMap<TypeEnum, Transformator>(); /** * Get a new instance of PayloadTransformator. Utilizes Lazy initialization and its not thread safe * @param encoding Which type of enconde this transformator will be specialized * @return a new instantiated PayloadTransformator */
public static PayloadTransformator getInstance(final EncodingEnum encoding){
adelbs/ISO8583
src/test/java/org/adelbs/iso8583/clientserver/MockISOServer.java
// Path: src/main/java/org/adelbs/iso8583/exception/ConnectionException.java // public class ConnectionException extends Exception { // // private static final long serialVersionUID = 2L; // // public ConnectionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/adelbs/iso8583/exception/ParseException.java // public class ParseException extends Exception { // // private static final long serialVersionUID = 2L; // // public ParseException(String message) { // super(message); // } // // }
import java.io.IOException; import org.adelbs.iso8583.exception.ConnectionException; import org.adelbs.iso8583.exception.ParseException;
package org.adelbs.iso8583.clientserver; class MockISOServer extends MockISOConnection{ public MockISOServer(final String host, final int port) throws IOException, ConnectionException{ this.conn = new ISOConnection(true, host, port, 1000); conn.setIsoConfig(ISOCONFIG); conn.putCallback(String.valueOf(Thread.currentThread().getId()), new MockServerCallback(conn,ISOCONFIG)); conn.connect(String.valueOf(Thread.currentThread().getId())); System.out.println("Server: Connected"); } public void process() throws MockISOException{ try { conn.processNextPayload(String.valueOf(Thread.currentThread().getId()), false, 0);
// Path: src/main/java/org/adelbs/iso8583/exception/ConnectionException.java // public class ConnectionException extends Exception { // // private static final long serialVersionUID = 2L; // // public ConnectionException(String message) { // super(message); // } // // } // // Path: src/main/java/org/adelbs/iso8583/exception/ParseException.java // public class ParseException extends Exception { // // private static final long serialVersionUID = 2L; // // public ParseException(String message) { // super(message); // } // // } // Path: src/test/java/org/adelbs/iso8583/clientserver/MockISOServer.java import java.io.IOException; import org.adelbs.iso8583.exception.ConnectionException; import org.adelbs.iso8583.exception.ParseException; package org.adelbs.iso8583.clientserver; class MockISOServer extends MockISOConnection{ public MockISOServer(final String host, final int port) throws IOException, ConnectionException{ this.conn = new ISOConnection(true, host, port, 1000); conn.setIsoConfig(ISOCONFIG); conn.putCallback(String.valueOf(Thread.currentThread().getId()), new MockServerCallback(conn,ISOCONFIG)); conn.connect(String.valueOf(Thread.currentThread().getId())); System.out.println("Server: Connected"); } public void process() throws MockISOException{ try { conn.processNextPayload(String.valueOf(Thread.currentThread().getId()), false, 0);
} catch (ParseException e) {
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java
// Path: src/main/java/org/adelbs/iso8583/constants/DelimiterEnum.java // public enum DelimiterEnum { // // LENGTH2_DELIMITER_BEG("LENGTH2_DELIMITER_BEG", new ISO8583Length2DelimiterBeginning()), // GENERIC_CONFIG_DELIMITER("GENERIC_CONFIG_DELIMITER", new ISO8583GenericConfigDelimiter()); // // private ISO8583Delimiter isoDelimiter; // private String value; // // DelimiterEnum(String value, ISO8583Delimiter isoDelimiter) { // this.value = value; // this.isoDelimiter = isoDelimiter; // } // // public static DelimiterEnum getDelimiter(String value) { // // if ("LENGTH2_DELIMITER_BEG".equals(value)) // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // else if ("GENERIC_CONFIG_DELIMITER".equals(value)) // return DelimiterEnum.GENERIC_CONFIG_DELIMITER; // // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // } // // public String toString() { // return isoDelimiter.getName(); // } // // public ISO8583Delimiter getDelimiter() { // return isoDelimiter; // } // // public String getValue() { // return value; // } // } // // Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.DelimiterEnum; import org.adelbs.iso8583.constants.EncodingEnum;
package org.adelbs.iso8583.vo; /** * Representation of a ISO8583 Config. */ @XmlRootElement(name="iso8583") //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) public class ISOConfigVO {
// Path: src/main/java/org/adelbs/iso8583/constants/DelimiterEnum.java // public enum DelimiterEnum { // // LENGTH2_DELIMITER_BEG("LENGTH2_DELIMITER_BEG", new ISO8583Length2DelimiterBeginning()), // GENERIC_CONFIG_DELIMITER("GENERIC_CONFIG_DELIMITER", new ISO8583GenericConfigDelimiter()); // // private ISO8583Delimiter isoDelimiter; // private String value; // // DelimiterEnum(String value, ISO8583Delimiter isoDelimiter) { // this.value = value; // this.isoDelimiter = isoDelimiter; // } // // public static DelimiterEnum getDelimiter(String value) { // // if ("LENGTH2_DELIMITER_BEG".equals(value)) // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // else if ("GENERIC_CONFIG_DELIMITER".equals(value)) // return DelimiterEnum.GENERIC_CONFIG_DELIMITER; // // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // } // // public String toString() { // return isoDelimiter.getName(); // } // // public ISO8583Delimiter getDelimiter() { // return isoDelimiter; // } // // public String getValue() { // return value; // } // } // // Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // Path: src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.DelimiterEnum; import org.adelbs.iso8583.constants.EncodingEnum; package org.adelbs.iso8583.vo; /** * Representation of a ISO8583 Config. */ @XmlRootElement(name="iso8583") //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) public class ISOConfigVO {
private DelimiterEnum delimiter;
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java
// Path: src/main/java/org/adelbs/iso8583/constants/DelimiterEnum.java // public enum DelimiterEnum { // // LENGTH2_DELIMITER_BEG("LENGTH2_DELIMITER_BEG", new ISO8583Length2DelimiterBeginning()), // GENERIC_CONFIG_DELIMITER("GENERIC_CONFIG_DELIMITER", new ISO8583GenericConfigDelimiter()); // // private ISO8583Delimiter isoDelimiter; // private String value; // // DelimiterEnum(String value, ISO8583Delimiter isoDelimiter) { // this.value = value; // this.isoDelimiter = isoDelimiter; // } // // public static DelimiterEnum getDelimiter(String value) { // // if ("LENGTH2_DELIMITER_BEG".equals(value)) // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // else if ("GENERIC_CONFIG_DELIMITER".equals(value)) // return DelimiterEnum.GENERIC_CONFIG_DELIMITER; // // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // } // // public String toString() { // return isoDelimiter.getName(); // } // // public ISO8583Delimiter getDelimiter() { // return isoDelimiter; // } // // public String getValue() { // return value; // } // } // // Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.DelimiterEnum; import org.adelbs.iso8583.constants.EncodingEnum;
package org.adelbs.iso8583.vo; /** * Representation of a ISO8583 Config. */ @XmlRootElement(name="iso8583") //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) public class ISOConfigVO { private DelimiterEnum delimiter;
// Path: src/main/java/org/adelbs/iso8583/constants/DelimiterEnum.java // public enum DelimiterEnum { // // LENGTH2_DELIMITER_BEG("LENGTH2_DELIMITER_BEG", new ISO8583Length2DelimiterBeginning()), // GENERIC_CONFIG_DELIMITER("GENERIC_CONFIG_DELIMITER", new ISO8583GenericConfigDelimiter()); // // private ISO8583Delimiter isoDelimiter; // private String value; // // DelimiterEnum(String value, ISO8583Delimiter isoDelimiter) { // this.value = value; // this.isoDelimiter = isoDelimiter; // } // // public static DelimiterEnum getDelimiter(String value) { // // if ("LENGTH2_DELIMITER_BEG".equals(value)) // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // else if ("GENERIC_CONFIG_DELIMITER".equals(value)) // return DelimiterEnum.GENERIC_CONFIG_DELIMITER; // // return DelimiterEnum.LENGTH2_DELIMITER_BEG; // } // // public String toString() { // return isoDelimiter.getName(); // } // // public ISO8583Delimiter getDelimiter() { // return isoDelimiter; // } // // public String getValue() { // return value; // } // } // // Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // Path: src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.DelimiterEnum; import org.adelbs.iso8583.constants.EncodingEnum; package org.adelbs.iso8583.vo; /** * Representation of a ISO8583 Config. */ @XmlRootElement(name="iso8583") //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) public class ISOConfigVO { private DelimiterEnum delimiter;
private EncodingEnum headerEncoding;
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/vo/MessageVO.java
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // }
import java.util.ArrayList; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.EncodingEnum;
package org.adelbs.iso8583.vo; @XmlRootElement(name="message") @XmlType(propOrder={"type", "bitmatEncoding", "fieldList"}) public class MessageVO extends GenericIsoVO { private ArrayList<FieldVO> fieldList = new ArrayList<FieldVO>(); private String type;
// Path: src/main/java/org/adelbs/iso8583/constants/EncodingEnum.java // public enum EncodingEnum implements Encoding { // // BCD("BCD", new EncodingBCD()), // EBCDIC("EBCDIC", new EncodingEBCDIC()), // ISO88591("ISO 8859-1", new EncodingUTF8()), // UTF8("UTF-8", new EncodingUTF8()), // HEXA("HEXA", new EncodingHEXA()), // BASE64("BASE64", new EncodingBASE64()), // BYTE("BYTE", new EncodingBYTE()); // // // private String value; // private Encoding encodingImpl; // // EncodingEnum (String value, Encoding encodingImpl) { // this.value = value; // this.encodingImpl = encodingImpl; // } // // public String toString() { // return value; // } // // public String toPlainString() { // return value.replaceAll(" ", "").replaceAll("-", ""); // } // // /** // * Returns an instance of Encoding, based on its name. The name must be a exact match // * of one of the Enumerators elements. // * // * @param value String name of the encoder. // * @return an instance of {@link Encoding}, depending on the type provided as, // * parameter. The default encoding is UTF8. // */ // public static EncodingEnum getEncoding(String value) { // EncodingEnum encoder = EncodingEnum.UTF8; // try{ // encoder = EncodingEnum.valueOf(value); // }catch (IllegalArgumentException e){ // encoder = EncodingEnum.UTF8; // } // if(value == null || value.isEmpty()){ // return EncodingEnum.UTF8; // } // return encoder; // } // // /** // * Populates a {@link JComboBox} with all elements of this Enumerator. // * @param combo previously created instance of a comboBox to be populated // */ // //TODO: This method should be on a separated UI class. UI must be separated from business classes // public static void addCmbItemList(JComboBox<EncodingEnum> combo) { // combo.addItem(UTF8); // combo.addItem(EBCDIC); // combo.addItem(ISO88591); // combo.addItem(HEXA); // combo.addItem(BCD); // combo.addItem(BASE64); // } // // @Override // public String convert(byte[] bytesToConvert) { // return encodingImpl.convert(bytesToConvert); // } // // @Override // public byte[] convert(String strToConvert) { // return encodingImpl.convert(strToConvert); // } // // @Override // public String convertBitmap(byte[] binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public byte[] convertBitmap(String binaryBitmap) { // return encodingImpl.convertBitmap(binaryBitmap); // } // // @Override // public int getMinBitmapSize() { // return encodingImpl.getMinBitmapSize(); // } // // @Override // public int getEncondedByteLength(final int asciiLength) { // return encodingImpl.getEncondedByteLength(asciiLength); // } // // } // Path: src/main/java/org/adelbs/iso8583/vo/MessageVO.java import java.util.ArrayList; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import org.adelbs.iso8583.constants.EncodingEnum; package org.adelbs.iso8583.vo; @XmlRootElement(name="message") @XmlType(propOrder={"type", "bitmatEncoding", "fieldList"}) public class MessageVO extends GenericIsoVO { private ArrayList<FieldVO> fieldList = new ArrayList<FieldVO>(); private String type;
private EncodingEnum bitmatEncoding;
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/util/ISOUtils.java
// Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // }
import java.util.List; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.w3c.dom.Node;
package org.adelbs.iso8583.util; public class ISOUtils { /* * TODO: * - implement check for TPDU * - implement subArray to extract TPDU * */ public static String hexToBin(String hex){ String bin = ""; String binFragment = ""; int iHex; hex = hex.trim(); hex = hex.replaceFirst("0x", ""); for(int i = 0; i < hex.length(); i++){ iHex = Integer.parseInt(""+hex.charAt(i),16); binFragment = Integer.toBinaryString(iHex); while(binFragment.length() < 4){ binFragment = "0" + binFragment; } bin += binFragment; } return bin; } public static String binToHex(String bin) { String result = ""; int decimal; for (int i = 4; (i <= 64 && i <= bin.length()); i = i + 4) { decimal = Integer.parseInt(bin.substring((i - 4), i), 2); result = result.concat(Integer.toString(decimal, 16)).toUpperCase(); } return result; }
// Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // Path: src/main/java/org/adelbs/iso8583/util/ISOUtils.java import java.util.List; import org.adelbs.iso8583.exception.OutOfBoundsException; import org.w3c.dom.Node; package org.adelbs.iso8583.util; public class ISOUtils { /* * TODO: * - implement check for TPDU * - implement subArray to extract TPDU * */ public static String hexToBin(String hex){ String bin = ""; String binFragment = ""; int iHex; hex = hex.trim(); hex = hex.replaceFirst("0x", ""); for(int i = 0; i < hex.length(); i++){ iHex = Integer.parseInt(""+hex.charAt(i),16); binFragment = Integer.toBinaryString(iHex); while(binFragment.length() < 4){ binFragment = "0" + binFragment; } bin += binFragment; } return bin; } public static String binToHex(String bin) { String result = ""; int decimal; for (int i = 4; (i <= 64 && i <= bin.length()); i = i + 4) { decimal = Integer.parseInt(bin.substring((i - 4), i), 2); result = result.concat(Integer.toString(decimal, 16)).toUpperCase(); } return result; }
public static byte[] subArray(byte[] data, int start, int end) throws OutOfBoundsException {
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/xml/ISOConfigMarshaller.java
// Path: src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java // @XmlRootElement(name="iso8583") // //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) // @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) // public class ISOConfigVO { // // private DelimiterEnum delimiter; // private EncodingEnum headerEncoding; // private Integer headerSize; // // private boolean TPDU; // private boolean StxEtx; // // private final List<MessageVO> messageList = new ArrayList<MessageVO>(); // // public ISOConfigVO() { // } // // // /** // * Create a new instance of a ISOConfig for a specific Delimiter // * // * @param delimiter // */ // public ISOConfigVO(DelimiterEnum delimiter) { // super(); // this.delimiter = delimiter; // } // // @XmlAttribute(name="delimiter") // public DelimiterEnum getDelimiter() { // return delimiter; // } // // public void setDelimiter(DelimiterEnum delimiter) { // this.delimiter = delimiter; // } // // /** // * @return the headerEncoding // */ // @XmlAttribute(name="headerEncoding") // public EncodingEnum getHeaderEncoding() { // return headerEncoding; // } // // /** // * @param headerEncoding the headerEncoding to set // */ // public void setHeaderEncoding(EncodingEnum headerEncoding) { // this.headerEncoding = headerEncoding; // } // // /** // * @return the headerSize // */ // @XmlAttribute(name="headerSize") // public Integer getHeaderSize() { // return headerSize; // } // // /** // * @param headerSize the headerSize to set // */ // public void setHeaderSize(Integer headerSize) { // this.headerSize = headerSize; // } // // /** // * @return the TPDU // */ // //@XmlAttribute(name="tpdu") // public boolean TPDU() { // return TPDU; // } // // /** // * @return the StxEtx // */ // //@XmlAttribute(name="stxetx") // public boolean StxEtx() { // return StxEtx; // } // // /** // * @param TPDU the TPDU to set // */ // public void setTPDU(boolean TPDU) { // this.TPDU=TPDU; // } // // /** // * @param StxEtx the StxEtx to set // */ // public void setStxEtx(boolean StxEtx) { // this.StxEtx=StxEtx; // } // // // @XmlElement(name="message") // public List<MessageVO> getMessageList() { // return Collections.unmodifiableList(messageList); // } // // /** // * Add a {@link MessageVO} to the list of messages of this ISOConfig // * @param message to be included as element of the ISO Config // */ // public void addMessage(final MessageVO message){ // messageList.add(message); // } // // /** // * Add a list of {@link MessageVO} to the messages of this ISOConfig // * @param messages List of messages to be included as elements of the ISO Config // */ // public void addAllMessages(final List<MessageVO> messages){ // messageList.addAll(messages); // } // // @Override // public String toString() { // return "iso8583 "+delimiter.toString(); // } // // // }
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.adelbs.iso8583.vo.ISOConfigVO;
package org.adelbs.iso8583.xml; /** * Specialized class to marshal {@link ISOConfigVO} objects into XML data. */ public class ISOConfigMarshaller { //singleton implementation private static ISOConfigMarshaller instance; private final Marshaller jaxbMarshaller; private final Unmarshaller jaxbUnmarshaller; private ISOConfigMarshaller() throws ISOConfigMarshallerException{ JAXBContext jaxbContext; try {
// Path: src/main/java/org/adelbs/iso8583/vo/ISOConfigVO.java // @XmlRootElement(name="iso8583") // //@XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "tpdu", "messageList"}) // @XmlType(propOrder={"delimiter", "headerEncoding", "headerSize", "messageList"}) // public class ISOConfigVO { // // private DelimiterEnum delimiter; // private EncodingEnum headerEncoding; // private Integer headerSize; // // private boolean TPDU; // private boolean StxEtx; // // private final List<MessageVO> messageList = new ArrayList<MessageVO>(); // // public ISOConfigVO() { // } // // // /** // * Create a new instance of a ISOConfig for a specific Delimiter // * // * @param delimiter // */ // public ISOConfigVO(DelimiterEnum delimiter) { // super(); // this.delimiter = delimiter; // } // // @XmlAttribute(name="delimiter") // public DelimiterEnum getDelimiter() { // return delimiter; // } // // public void setDelimiter(DelimiterEnum delimiter) { // this.delimiter = delimiter; // } // // /** // * @return the headerEncoding // */ // @XmlAttribute(name="headerEncoding") // public EncodingEnum getHeaderEncoding() { // return headerEncoding; // } // // /** // * @param headerEncoding the headerEncoding to set // */ // public void setHeaderEncoding(EncodingEnum headerEncoding) { // this.headerEncoding = headerEncoding; // } // // /** // * @return the headerSize // */ // @XmlAttribute(name="headerSize") // public Integer getHeaderSize() { // return headerSize; // } // // /** // * @param headerSize the headerSize to set // */ // public void setHeaderSize(Integer headerSize) { // this.headerSize = headerSize; // } // // /** // * @return the TPDU // */ // //@XmlAttribute(name="tpdu") // public boolean TPDU() { // return TPDU; // } // // /** // * @return the StxEtx // */ // //@XmlAttribute(name="stxetx") // public boolean StxEtx() { // return StxEtx; // } // // /** // * @param TPDU the TPDU to set // */ // public void setTPDU(boolean TPDU) { // this.TPDU=TPDU; // } // // /** // * @param StxEtx the StxEtx to set // */ // public void setStxEtx(boolean StxEtx) { // this.StxEtx=StxEtx; // } // // // @XmlElement(name="message") // public List<MessageVO> getMessageList() { // return Collections.unmodifiableList(messageList); // } // // /** // * Add a {@link MessageVO} to the list of messages of this ISOConfig // * @param message to be included as element of the ISO Config // */ // public void addMessage(final MessageVO message){ // messageList.add(message); // } // // /** // * Add a list of {@link MessageVO} to the messages of this ISOConfig // * @param messages List of messages to be included as elements of the ISO Config // */ // public void addAllMessages(final List<MessageVO> messages){ // messageList.addAll(messages); // } // // @Override // public String toString() { // return "iso8583 "+delimiter.toString(); // } // // // } // Path: src/main/java/org/adelbs/iso8583/xml/ISOConfigMarshaller.java import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.adelbs.iso8583.vo.ISOConfigVO; package org.adelbs.iso8583.xml; /** * Specialized class to marshal {@link ISOConfigVO} objects into XML data. */ public class ISOConfigMarshaller { //singleton implementation private static ISOConfigMarshaller instance; private final Marshaller jaxbMarshaller; private final Unmarshaller jaxbUnmarshaller; private ISOConfigMarshaller() throws ISOConfigMarshallerException{ JAXBContext jaxbContext; try {
jaxbContext = JAXBContext.newInstance(ISOConfigVO.class);
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/util/Out.java
// Path: src/main/java/org/adelbs/iso8583/clientserver/CallbackAction.java // public abstract class CallbackAction { // // public abstract void dataReceived(SocketPayload payload) throws ParseException; // // public abstract void log(String log); // // public abstract void end(); // // public void keepalive() { } // }
import java.text.SimpleDateFormat; import java.util.Calendar; import org.adelbs.iso8583.clientserver.CallbackAction;
package org.adelbs.iso8583.util; public class Out { public static void log(String title, String msg) { log(title, msg, null); }
// Path: src/main/java/org/adelbs/iso8583/clientserver/CallbackAction.java // public abstract class CallbackAction { // // public abstract void dataReceived(SocketPayload payload) throws ParseException; // // public abstract void log(String log); // // public abstract void end(); // // public void keepalive() { } // } // Path: src/main/java/org/adelbs/iso8583/util/Out.java import java.text.SimpleDateFormat; import java.util.Calendar; import org.adelbs.iso8583.clientserver.CallbackAction; package org.adelbs.iso8583.util; public class Out { public static void log(String title, String msg) { log(title, msg, null); }
public static void log(String title, String msg, CallbackAction callback) {
adelbs/ISO8583
src/main/java/org/adelbs/iso8583/payload/Transformator.java
// Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // }
import org.adelbs.iso8583.exception.OutOfBoundsException;
package org.adelbs.iso8583.payload; public interface Transformator { /** * Transform a Object into an array of bytes * @param value * @return */ public byte[] transform(final Object value); /** * Revert the array of bytes into an Object * @param payload payload array of bytes * @return * @throws OutOfBoundsException */
// Path: src/main/java/org/adelbs/iso8583/exception/OutOfBoundsException.java // public class OutOfBoundsException extends Exception { // // private static final long serialVersionUID = 2L; // // public OutOfBoundsException() { // super(); // } // // } // Path: src/main/java/org/adelbs/iso8583/payload/Transformator.java import org.adelbs.iso8583.exception.OutOfBoundsException; package org.adelbs.iso8583.payload; public interface Transformator { /** * Transform a Object into an array of bytes * @param value * @return */ public byte[] transform(final Object value); /** * Revert the array of bytes into an Object * @param payload payload array of bytes * @return * @throws OutOfBoundsException */
public RevertResult revert(final byte[] payload) throws OutOfBoundsException;
jVoid/jVoid
src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.configuration; /** * Specific loader for the {@code JVoidConfiguration} that builds the configuration up * in a hierarchical fashion from multiple properties files. * */ public class JVoidPropertiesBasedConfigurationLoader { private static final String CONFIG_FILE_NAME = "jvoid.config";
// Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.configuration; /** * Specific loader for the {@code JVoidConfiguration} that builds the configuration up * in a hierarchical fashion from multiple properties files. * */ public class JVoidPropertiesBasedConfigurationLoader { private static final String CONFIG_FILE_NAME = "jvoid.config";
public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException {
jVoid/jVoid
src/main/java/io/jvoid/metadata/repositories/AbstractRepository.java
// Path: src/main/java/io/jvoid/database/DbUtils.java // public class DbUtils { // // private static final QueryRunner queryRunner = new QueryRunner(); // // private DbUtils() { // super(); // } // // /** // * // * @param database // * @param sql // * @param parameters // */ // public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // QueryRunner query = new QueryRunner(); // query.update(conn, sql, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param parameters // * @return // */ // public static Long executeInsert(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // return queryRunner.insert(conn, sql, rsh, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sqlList // * @param parametersList // * @return // */ // public static List<Long> executeMultipleInserts(MetadataDatabase database, List<String> sqlList, List<Object[]> parametersList) { // try (Connection conn = database.getConnection()) { // List<Long> results = new ArrayList<>(); // for (int i = 0; i < sqlList.size(); i++) { // Object[] parameters = parametersList.get(i); // String sql = sqlList.get(i); // // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // Long id = queryRunner.insert(conn, sql, rsh, parameters); // results.add(id); // } // return results; // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param resultSetHandler // * @param parameters // * @return // */ // public static <T> T query(MetadataDatabase database, String sql, ResultSetHandler<T> resultSetHandler, Object... parameters) { // try (Connection conn = database.getConnection()) { // return queryRunner.query(conn, sql, resultSetHandler, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // }
import java.util.List; import org.apache.commons.dbutils.ResultSetHandler; import io.jvoid.database.DbUtils; import io.jvoid.database.MetadataDatabase;
package io.jvoid.metadata.repositories; /** * Generic repository class extended by all the concrete JVoid repositories. * */ public abstract class AbstractRepository<T, I> implements BaseRepository<T, I> { protected MetadataDatabase database; public AbstractRepository(MetadataDatabase database) { this.database = database; } protected void executeUpdate(String sql, Object... parameters) {
// Path: src/main/java/io/jvoid/database/DbUtils.java // public class DbUtils { // // private static final QueryRunner queryRunner = new QueryRunner(); // // private DbUtils() { // super(); // } // // /** // * // * @param database // * @param sql // * @param parameters // */ // public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // QueryRunner query = new QueryRunner(); // query.update(conn, sql, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param parameters // * @return // */ // public static Long executeInsert(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // return queryRunner.insert(conn, sql, rsh, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sqlList // * @param parametersList // * @return // */ // public static List<Long> executeMultipleInserts(MetadataDatabase database, List<String> sqlList, List<Object[]> parametersList) { // try (Connection conn = database.getConnection()) { // List<Long> results = new ArrayList<>(); // for (int i = 0; i < sqlList.size(); i++) { // Object[] parameters = parametersList.get(i); // String sql = sqlList.get(i); // // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // Long id = queryRunner.insert(conn, sql, rsh, parameters); // results.add(id); // } // return results; // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param resultSetHandler // * @param parameters // * @return // */ // public static <T> T query(MetadataDatabase database, String sql, ResultSetHandler<T> resultSetHandler, Object... parameters) { // try (Connection conn = database.getConnection()) { // return queryRunner.query(conn, sql, resultSetHandler, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // Path: src/main/java/io/jvoid/metadata/repositories/AbstractRepository.java import java.util.List; import org.apache.commons.dbutils.ResultSetHandler; import io.jvoid.database.DbUtils; import io.jvoid.database.MetadataDatabase; package io.jvoid.metadata.repositories; /** * Generic repository class extended by all the concrete JVoid repositories. * */ public abstract class AbstractRepository<T, I> implements BaseRepository<T, I> { protected MetadataDatabase database; public AbstractRepository(MetadataDatabase database) { this.database = database; } protected void executeUpdate(String sql, Object... parameters) {
DbUtils.executeUpdate(database, sql, parameters);
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/CtBehaviorChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // }
import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import javassist.CtBehavior;
package io.jvoid.metadata.checksum; /** * */ class CtBehaviorChecksummer extends AbstractCtBehaviorChecksummer<CtBehavior> { @Inject
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // Path: src/main/java/io/jvoid/metadata/checksum/CtBehaviorChecksummer.java import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import javassist.CtBehavior; package io.jvoid.metadata.checksum; /** * */ class CtBehaviorChecksummer extends AbstractCtBehaviorChecksummer<CtBehavior> { @Inject
public CtBehaviorChecksummer(JVoidConfiguration jVoidConfiguration) {
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
package io.jvoid.instrumentation; /** * The {@code JVoidClassFileTransformer} takes care of instrumenting the * classes. It instruments differently the test runner classes from the normal * classes and the filtered out classes. * */ @Slf4j public class JVoidClassFileTransformer implements ClassFileTransformer { private static final ClassPool classPool;
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; package io.jvoid.instrumentation; /** * The {@code JVoidClassFileTransformer} takes care of instrumenting the * classes. It instruments differently the test runner classes from the normal * classes and the filtered out classes. * */ @Slf4j public class JVoidClassFileTransformer implements ClassFileTransformer { private static final ClassPool classPool;
private final ProviderCatalog providerCatalog;
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
package io.jvoid.instrumentation; /** * The {@code JVoidClassFileTransformer} takes care of instrumenting the * classes. It instruments differently the test runner classes from the normal * classes and the filtered out classes. * */ @Slf4j public class JVoidClassFileTransformer implements ClassFileTransformer { private static final ClassPool classPool; private final ProviderCatalog providerCatalog; static { classPool = ClassPool.getDefault(); } /** * * @param providerCatalog */ @Inject public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { this.providerCatalog = providerCatalog; } /** * */ @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className == null) { return null; } try { String sanitizedClassName = className.replace('/', '.'); classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); CtClass ctClass = getCtClass(sanitizedClassName);
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; package io.jvoid.instrumentation; /** * The {@code JVoidClassFileTransformer} takes care of instrumenting the * classes. It instruments differently the test runner classes from the normal * classes and the filtered out classes. * */ @Slf4j public class JVoidClassFileTransformer implements ClassFileTransformer { private static final ClassPool classPool; private final ProviderCatalog providerCatalog; static { classPool = ClassPool.getDefault(); } /** * * @param providerCatalog */ @Inject public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { this.providerCatalog = providerCatalog; } /** * */ @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className == null) { return null; } try { String sanitizedClassName = className.replace('/', '.'); classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); CtClass ctClass = getCtClass(sanitizedClassName);
Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass);
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
} try { String sanitizedClassName = className.replace('/', '.'); classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); CtClass ctClass = getCtClass(sanitizedClassName); Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // This is important to avoid to modify classes part of the java.lang.* or // not related to the application under test. There might be otherwise some // error related to Javassist transformation. See: // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top if (providers.isEmpty()) { return null; } for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e);
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; } try { String sanitizedClassName = className.replace('/', '.'); classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); CtClass ctClass = getCtClass(sanitizedClassName); Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // This is important to avoid to modify classes part of the java.lang.* or // not related to the application under test. There might be otherwise some // error related to Javassist transformation. See: // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top if (providers.isEmpty()) { return null; } for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e);
throw new JVoidIntrumentationException("Failed to instrument class: " + className, e);
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
// error related to Javassist transformation. See: // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top if (providers.isEmpty()) { return null; } for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); } } /** * * @param ctClass * @param provider * @throws CannotCompileException */ private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException {
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; // error related to Javassist transformation. See: // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top if (providers.isEmpty()) { return null; } for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); } } /** * * @param ctClass * @param provider * @throws CannotCompileException */ private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException {
for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) {
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
} for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); } } /** * * @param ctClass * @param provider * @throws CannotCompileException */ private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { classHandler.handleClass(ctClass); } for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
// Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Set; import com.google.inject.Inject; import io.jvoid.exceptions.JVoidIntrumentationException; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.ByteArrayClassPath; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; } for (InstrumentationProvider provider : providers) { tranformWithProvider(ctClass, provider); } byte[] bytecode = ctClass.toBytecode(); ctClass.defrost(); ctClass.prune(); ctClass.detach(); return bytecode; } catch (Exception e) { log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); } } /** * * @param ctClass * @param provider * @throws CannotCompileException */ private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { classHandler.handleClass(ctClass); } for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
for (MethodInstrumenter instrumenter : provider.getMethodInstrumenters(ctMethod)) {
jVoid/jVoid
src/main/java/io/jvoid/metadata/repositories/TestsRepository.java
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JTest;
package io.jvoid.metadata.repositories; /** * */ @Singleton public class TestsRepository extends AbstractRepository<JTest, Long> { private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); @Inject
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JTest; package io.jvoid.metadata.repositories; /** * */ @Singleton public class TestsRepository extends AbstractRepository<JTest, Long> { private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); @Inject
public TestsRepository(MetadataDatabase database) {
jVoid/jVoid
src/test/java/io/jvoid/test/bytecode/JavassistUtilsTest.java
// Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java // public class JavassistUtils { // // private JavassistUtils() { // super(); // } // // /** // * This is basically the InstructionPrinter.getMethodBytecode but with a // * CtBehaviour parameter instead of a CtMethod // * // * @param behavior // * @return // */ // public static String getBehaviourBytecode(CtBehavior behavior) { // MethodInfo info = behavior.getMethodInfo2(); // CodeAttribute code = info.getCodeAttribute(); // if (code == null) { // return ""; // } // // ConstPool pool = info.getConstPool(); // StringBuilder sb = new StringBuilder(1024); // // CodeIterator iterator = code.iterator(); // while (iterator.hasNext()) { // int pos; // try { // pos = iterator.next(); // } catch (BadBytecode e) { // throw new JVoidIntrumentationException("BadBytecoode", e); // } // // sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n"); // } // return sb.toString(); // } // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.bytecode.JavassistUtils; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import javassist.bytecode.InstructionPrinter;
package io.jvoid.test.bytecode; public class JavassistUtilsTest extends AbstractJVoidTest { private CtClass ctClassTestClass; @Override @Before public void setUp() throws Exception { super.setUp(); ctClassTestClass = classPool.get(TestClass.class.getName()); } @Override @After public void tearDown() { ctClassTestClass.prune(); } @Test public void testGetBehaviourBytecodeCtMethod() throws NotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); InstructionPrinter instrPrinter = new InstructionPrinter(ps); CtMethod ctMethodCiao = ctClassTestClass.getDeclaredMethod("ciao"); instrPrinter.print(ctMethodCiao); String instrPrinterStr = baos.toString();
// Path: src/main/java/io/jvoid/bytecode/JavassistUtils.java // public class JavassistUtils { // // private JavassistUtils() { // super(); // } // // /** // * This is basically the InstructionPrinter.getMethodBytecode but with a // * CtBehaviour parameter instead of a CtMethod // * // * @param behavior // * @return // */ // public static String getBehaviourBytecode(CtBehavior behavior) { // MethodInfo info = behavior.getMethodInfo2(); // CodeAttribute code = info.getCodeAttribute(); // if (code == null) { // return ""; // } // // ConstPool pool = info.getConstPool(); // StringBuilder sb = new StringBuilder(1024); // // CodeIterator iterator = code.iterator(); // while (iterator.hasNext()) { // int pos; // try { // pos = iterator.next(); // } catch (BadBytecode e) { // throw new JVoidIntrumentationException("BadBytecoode", e); // } // // sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n"); // } // return sb.toString(); // } // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/bytecode/JavassistUtilsTest.java import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.bytecode.JavassistUtils; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import javassist.bytecode.InstructionPrinter; package io.jvoid.test.bytecode; public class JavassistUtilsTest extends AbstractJVoidTest { private CtClass ctClassTestClass; @Override @Before public void setUp() throws Exception { super.setUp(); ctClassTestClass = classPool.get(TestClass.class.getName()); } @Override @After public void tearDown() { ctClassTestClass.prune(); } @Test public void testGetBehaviourBytecodeCtMethod() throws NotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); InstructionPrinter instrPrinter = new InstructionPrinter(ps); CtMethod ctMethodCiao = ctClassTestClass.getDeclaredMethod("ciao"); instrPrinter.print(ctMethodCiao); String instrPrinterStr = baos.toString();
assertEquals(instrPrinterStr, JavassistUtils.getBehaviourBytecode(ctMethodCiao));
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelper.java
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java // @Singleton // public class JVoidExecutionContext { // // private ExecutionsRepository executionsRepository; // // private JExecution currentExecution; // // private ThreadLocal<JTest> runningTestHolder = new ThreadLocal<>(); // // @Inject // public JVoidExecutionContext(ExecutionsRepository executionsRepository) { // super(); // this.executionsRepository = executionsRepository; // this.runningTestHolder.set(null); // } // // public Long getCurrentExecutionId() { // return currentExecution == null ? null : currentExecution.getId(); // } // // public JExecution getCurrentExecution() { // return currentExecution; // } // // public void setCurrentExecution(JExecution currentExecution) { // this.currentExecution = currentExecution; // } // // public void startNewExecution() { // JExecution execution = new JExecution(); // execution.setTimestamp(System.currentTimeMillis()); // execution = executionsRepository.add(execution); // currentExecution = execution; // } // // public JTest getRunningTest() { // return runningTestHolder.get(); // } // // public synchronized void setRunningTest(JTest runningTest) { // runningTestHolder.set(runningTest); // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // }
import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.execution.JVoidExecutionContext; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestsRepository;
package io.jvoid.instrumentation; /** * All the injected code used to instrument runtime classes will refer to this * class to perform various tasks. * */ @Singleton public class JVoidInstrumentationHelper { private TestRelatedCodeModificationChecker testRelatedCodeModificationChecker;
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java // @Singleton // public class JVoidExecutionContext { // // private ExecutionsRepository executionsRepository; // // private JExecution currentExecution; // // private ThreadLocal<JTest> runningTestHolder = new ThreadLocal<>(); // // @Inject // public JVoidExecutionContext(ExecutionsRepository executionsRepository) { // super(); // this.executionsRepository = executionsRepository; // this.runningTestHolder.set(null); // } // // public Long getCurrentExecutionId() { // return currentExecution == null ? null : currentExecution.getId(); // } // // public JExecution getCurrentExecution() { // return currentExecution; // } // // public void setCurrentExecution(JExecution currentExecution) { // this.currentExecution = currentExecution; // } // // public void startNewExecution() { // JExecution execution = new JExecution(); // execution.setTimestamp(System.currentTimeMillis()); // execution = executionsRepository.add(execution); // currentExecution = execution; // } // // public JTest getRunningTest() { // return runningTestHolder.get(); // } // // public synchronized void setRunningTest(JTest runningTest) { // runningTestHolder.set(runningTest); // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelper.java import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.execution.JVoidExecutionContext; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestsRepository; package io.jvoid.instrumentation; /** * All the injected code used to instrument runtime classes will refer to this * class to perform various tasks. * */ @Singleton public class JVoidInstrumentationHelper { private TestRelatedCodeModificationChecker testRelatedCodeModificationChecker;
private TestsRepository testsRepository;
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelper.java
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java // @Singleton // public class JVoidExecutionContext { // // private ExecutionsRepository executionsRepository; // // private JExecution currentExecution; // // private ThreadLocal<JTest> runningTestHolder = new ThreadLocal<>(); // // @Inject // public JVoidExecutionContext(ExecutionsRepository executionsRepository) { // super(); // this.executionsRepository = executionsRepository; // this.runningTestHolder.set(null); // } // // public Long getCurrentExecutionId() { // return currentExecution == null ? null : currentExecution.getId(); // } // // public JExecution getCurrentExecution() { // return currentExecution; // } // // public void setCurrentExecution(JExecution currentExecution) { // this.currentExecution = currentExecution; // } // // public void startNewExecution() { // JExecution execution = new JExecution(); // execution.setTimestamp(System.currentTimeMillis()); // execution = executionsRepository.add(execution); // currentExecution = execution; // } // // public JTest getRunningTest() { // return runningTestHolder.get(); // } // // public synchronized void setRunningTest(JTest runningTest) { // runningTestHolder.set(runningTest); // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // }
import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.execution.JVoidExecutionContext; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestsRepository;
package io.jvoid.instrumentation; /** * All the injected code used to instrument runtime classes will refer to this * class to perform various tasks. * */ @Singleton public class JVoidInstrumentationHelper { private TestRelatedCodeModificationChecker testRelatedCodeModificationChecker; private TestsRepository testsRepository;
// Path: src/main/java/io/jvoid/execution/JVoidExecutionContext.java // @Singleton // public class JVoidExecutionContext { // // private ExecutionsRepository executionsRepository; // // private JExecution currentExecution; // // private ThreadLocal<JTest> runningTestHolder = new ThreadLocal<>(); // // @Inject // public JVoidExecutionContext(ExecutionsRepository executionsRepository) { // super(); // this.executionsRepository = executionsRepository; // this.runningTestHolder.set(null); // } // // public Long getCurrentExecutionId() { // return currentExecution == null ? null : currentExecution.getId(); // } // // public JExecution getCurrentExecution() { // return currentExecution; // } // // public void setCurrentExecution(JExecution currentExecution) { // this.currentExecution = currentExecution; // } // // public void startNewExecution() { // JExecution execution = new JExecution(); // execution.setTimestamp(System.currentTimeMillis()); // execution = executionsRepository.add(execution); // currentExecution = execution; // } // // public JTest getRunningTest() { // return runningTestHolder.get(); // } // // public synchronized void setRunningTest(JTest runningTest) { // runningTestHolder.set(runningTest); // } // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // } // Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelper.java import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.execution.JVoidExecutionContext; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestsRepository; package io.jvoid.instrumentation; /** * All the injected code used to instrument runtime classes will refer to this * class to perform various tasks. * */ @Singleton public class JVoidInstrumentationHelper { private TestRelatedCodeModificationChecker testRelatedCodeModificationChecker; private TestsRepository testsRepository;
private JVoidExecutionContext jvoidExecutionContext;
jVoid/jVoid
src/test/java/io/jvoid/test/JVoidAgentPremainTest.java
// Path: src/main/java/io/jvoid/JVoid.java // @Slf4j // public class JVoid { // // /** // * The JVoid agent tracks the classes and methods that are involved in unit-testing // * per execution. That allows to skip the tests that have not been affected by source // * code local modifications. // * // */ // public static void premain(String agentArguments, Instrumentation instrumentation) { // log.info("JVoid getting ready to jvoiding your code!"); // // Injector injector = Guice.createInjector(new JVoidModule()); // // JVoidConfigurationService jvoidConfigurationService = injector.getInstance(JVoidConfigurationService.class); // // try { // jvoidConfigurationService.loadConfiguration(agentArguments); // } catch (JVoidConfigurationException e) { // System.exit(-1); // } // // JVoidExecutionContext jvoidExecutionContext = injector.getInstance(JVoidExecutionContext.class); // jvoidExecutionContext.startNewExecution(); // // JVoidInstrumentationHelper helper = injector.getInstance(JVoidInstrumentationHelper.class); // JVoidInstrumentationHelperHolder.getInstance().set(helper); // // JVoidClassFileTransformer transformer = injector.getInstance(JVoidClassFileTransformer.class); // instrumentation.addTransformer(transformer); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java // @Slf4j // public class JVoidClassFileTransformer implements ClassFileTransformer { // // private static final ClassPool classPool; // // private final ProviderCatalog providerCatalog; // // static { // classPool = ClassPool.getDefault(); // } // // /** // * // * @param providerCatalog // */ // @Inject // public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { // this.providerCatalog = providerCatalog; // } // // /** // * // */ // @Override // public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, // ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // if (className == null) { // return null; // } // try { // String sanitizedClassName = className.replace('/', '.'); // // classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); // CtClass ctClass = getCtClass(sanitizedClassName); // // Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // // // This is important to avoid to modify classes part of the java.lang.* or // // not related to the application under test. There might be otherwise some // // error related to Javassist transformation. See: // // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top // if (providers.isEmpty()) { // return null; // } // // for (InstrumentationProvider provider : providers) { // tranformWithProvider(ctClass, provider); // } // // byte[] bytecode = ctClass.toBytecode(); // // ctClass.defrost(); // ctClass.prune(); // ctClass.detach(); // // return bytecode; // } catch (Exception e) { // log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); // throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); // } // } // // /** // * // * @param ctClass // * @param provider // * @throws CannotCompileException // */ // private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { // for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { // classHandler.handleClass(ctClass); // } // for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { // for (MethodInstrumenter instrumenter : provider.getMethodInstrumenters(ctMethod)) { // if (instrumenter.shouldInstrument(ctMethod)) { // instrumenter.instrument(ctMethod); // } // } // } // } // // /** // * // * @param sanitizedClassName // * @return // */ // private CtClass getCtClass(String sanitizedClassName) { // try { // return classPool.get(sanitizedClassName); // } catch (NotFoundException e) { // throw new JVoidIntrumentationException("Class not found:" + sanitizedClassName, e); // } catch (Exception e) { // throw new JVoidIntrumentationException(e.getLocalizedMessage(), e); // } // } // // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import io.jvoid.JVoid; import io.jvoid.instrumentation.JVoidClassFileTransformer;
package io.jvoid.test; public class JVoidAgentPremainTest extends AbstractJVoidTest { @Override @Before public void setUp() { // Make sure there is no context initialized } @Test public void premainTest() { // Prepare to verify the instrumentation added Instrumentation mockIntrumentation = mock(Instrumentation.class);
// Path: src/main/java/io/jvoid/JVoid.java // @Slf4j // public class JVoid { // // /** // * The JVoid agent tracks the classes and methods that are involved in unit-testing // * per execution. That allows to skip the tests that have not been affected by source // * code local modifications. // * // */ // public static void premain(String agentArguments, Instrumentation instrumentation) { // log.info("JVoid getting ready to jvoiding your code!"); // // Injector injector = Guice.createInjector(new JVoidModule()); // // JVoidConfigurationService jvoidConfigurationService = injector.getInstance(JVoidConfigurationService.class); // // try { // jvoidConfigurationService.loadConfiguration(agentArguments); // } catch (JVoidConfigurationException e) { // System.exit(-1); // } // // JVoidExecutionContext jvoidExecutionContext = injector.getInstance(JVoidExecutionContext.class); // jvoidExecutionContext.startNewExecution(); // // JVoidInstrumentationHelper helper = injector.getInstance(JVoidInstrumentationHelper.class); // JVoidInstrumentationHelperHolder.getInstance().set(helper); // // JVoidClassFileTransformer transformer = injector.getInstance(JVoidClassFileTransformer.class); // instrumentation.addTransformer(transformer); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java // @Slf4j // public class JVoidClassFileTransformer implements ClassFileTransformer { // // private static final ClassPool classPool; // // private final ProviderCatalog providerCatalog; // // static { // classPool = ClassPool.getDefault(); // } // // /** // * // * @param providerCatalog // */ // @Inject // public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { // this.providerCatalog = providerCatalog; // } // // /** // * // */ // @Override // public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, // ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // if (className == null) { // return null; // } // try { // String sanitizedClassName = className.replace('/', '.'); // // classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); // CtClass ctClass = getCtClass(sanitizedClassName); // // Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // // // This is important to avoid to modify classes part of the java.lang.* or // // not related to the application under test. There might be otherwise some // // error related to Javassist transformation. See: // // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top // if (providers.isEmpty()) { // return null; // } // // for (InstrumentationProvider provider : providers) { // tranformWithProvider(ctClass, provider); // } // // byte[] bytecode = ctClass.toBytecode(); // // ctClass.defrost(); // ctClass.prune(); // ctClass.detach(); // // return bytecode; // } catch (Exception e) { // log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); // throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); // } // } // // /** // * // * @param ctClass // * @param provider // * @throws CannotCompileException // */ // private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { // for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { // classHandler.handleClass(ctClass); // } // for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { // for (MethodInstrumenter instrumenter : provider.getMethodInstrumenters(ctMethod)) { // if (instrumenter.shouldInstrument(ctMethod)) { // instrumenter.instrument(ctMethod); // } // } // } // } // // /** // * // * @param sanitizedClassName // * @return // */ // private CtClass getCtClass(String sanitizedClassName) { // try { // return classPool.get(sanitizedClassName); // } catch (NotFoundException e) { // throw new JVoidIntrumentationException("Class not found:" + sanitizedClassName, e); // } catch (Exception e) { // throw new JVoidIntrumentationException(e.getLocalizedMessage(), e); // } // } // // } // Path: src/test/java/io/jvoid/test/JVoidAgentPremainTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import io.jvoid.JVoid; import io.jvoid.instrumentation.JVoidClassFileTransformer; package io.jvoid.test; public class JVoidAgentPremainTest extends AbstractJVoidTest { @Override @Before public void setUp() { // Make sure there is no context initialized } @Test public void premainTest() { // Prepare to verify the instrumentation added Instrumentation mockIntrumentation = mock(Instrumentation.class);
JVoid.premain(DEFAULT_TEST_CONFIGURATION_FILE, mockIntrumentation);
jVoid/jVoid
src/test/java/io/jvoid/test/JVoidAgentPremainTest.java
// Path: src/main/java/io/jvoid/JVoid.java // @Slf4j // public class JVoid { // // /** // * The JVoid agent tracks the classes and methods that are involved in unit-testing // * per execution. That allows to skip the tests that have not been affected by source // * code local modifications. // * // */ // public static void premain(String agentArguments, Instrumentation instrumentation) { // log.info("JVoid getting ready to jvoiding your code!"); // // Injector injector = Guice.createInjector(new JVoidModule()); // // JVoidConfigurationService jvoidConfigurationService = injector.getInstance(JVoidConfigurationService.class); // // try { // jvoidConfigurationService.loadConfiguration(agentArguments); // } catch (JVoidConfigurationException e) { // System.exit(-1); // } // // JVoidExecutionContext jvoidExecutionContext = injector.getInstance(JVoidExecutionContext.class); // jvoidExecutionContext.startNewExecution(); // // JVoidInstrumentationHelper helper = injector.getInstance(JVoidInstrumentationHelper.class); // JVoidInstrumentationHelperHolder.getInstance().set(helper); // // JVoidClassFileTransformer transformer = injector.getInstance(JVoidClassFileTransformer.class); // instrumentation.addTransformer(transformer); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java // @Slf4j // public class JVoidClassFileTransformer implements ClassFileTransformer { // // private static final ClassPool classPool; // // private final ProviderCatalog providerCatalog; // // static { // classPool = ClassPool.getDefault(); // } // // /** // * // * @param providerCatalog // */ // @Inject // public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { // this.providerCatalog = providerCatalog; // } // // /** // * // */ // @Override // public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, // ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // if (className == null) { // return null; // } // try { // String sanitizedClassName = className.replace('/', '.'); // // classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); // CtClass ctClass = getCtClass(sanitizedClassName); // // Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // // // This is important to avoid to modify classes part of the java.lang.* or // // not related to the application under test. There might be otherwise some // // error related to Javassist transformation. See: // // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top // if (providers.isEmpty()) { // return null; // } // // for (InstrumentationProvider provider : providers) { // tranformWithProvider(ctClass, provider); // } // // byte[] bytecode = ctClass.toBytecode(); // // ctClass.defrost(); // ctClass.prune(); // ctClass.detach(); // // return bytecode; // } catch (Exception e) { // log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); // throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); // } // } // // /** // * // * @param ctClass // * @param provider // * @throws CannotCompileException // */ // private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { // for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { // classHandler.handleClass(ctClass); // } // for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { // for (MethodInstrumenter instrumenter : provider.getMethodInstrumenters(ctMethod)) { // if (instrumenter.shouldInstrument(ctMethod)) { // instrumenter.instrument(ctMethod); // } // } // } // } // // /** // * // * @param sanitizedClassName // * @return // */ // private CtClass getCtClass(String sanitizedClassName) { // try { // return classPool.get(sanitizedClassName); // } catch (NotFoundException e) { // throw new JVoidIntrumentationException("Class not found:" + sanitizedClassName, e); // } catch (Exception e) { // throw new JVoidIntrumentationException(e.getLocalizedMessage(), e); // } // } // // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import io.jvoid.JVoid; import io.jvoid.instrumentation.JVoidClassFileTransformer;
package io.jvoid.test; public class JVoidAgentPremainTest extends AbstractJVoidTest { @Override @Before public void setUp() { // Make sure there is no context initialized } @Test public void premainTest() { // Prepare to verify the instrumentation added Instrumentation mockIntrumentation = mock(Instrumentation.class); JVoid.premain(DEFAULT_TEST_CONFIGURATION_FILE, mockIntrumentation); // The configuration is loaded // assertTrue(!JVoidContext.getConfiguration().dbLocation().isEmpty()); // JVoidExecutionContext jvoidExecutionContext; // // The execution is setup // JExecution execution = jvoidExecutionContext.getCurrentExecution(); // assertNotNull(execution); // assertEquals(JVoidContext.getCurrentExecution(), execution); // The transformer is added ArgumentCaptor<ClassFileTransformer> argument = ArgumentCaptor.forClass(ClassFileTransformer.class); verify(mockIntrumentation).addTransformer(argument.capture());
// Path: src/main/java/io/jvoid/JVoid.java // @Slf4j // public class JVoid { // // /** // * The JVoid agent tracks the classes and methods that are involved in unit-testing // * per execution. That allows to skip the tests that have not been affected by source // * code local modifications. // * // */ // public static void premain(String agentArguments, Instrumentation instrumentation) { // log.info("JVoid getting ready to jvoiding your code!"); // // Injector injector = Guice.createInjector(new JVoidModule()); // // JVoidConfigurationService jvoidConfigurationService = injector.getInstance(JVoidConfigurationService.class); // // try { // jvoidConfigurationService.loadConfiguration(agentArguments); // } catch (JVoidConfigurationException e) { // System.exit(-1); // } // // JVoidExecutionContext jvoidExecutionContext = injector.getInstance(JVoidExecutionContext.class); // jvoidExecutionContext.startNewExecution(); // // JVoidInstrumentationHelper helper = injector.getInstance(JVoidInstrumentationHelper.class); // JVoidInstrumentationHelperHolder.getInstance().set(helper); // // JVoidClassFileTransformer transformer = injector.getInstance(JVoidClassFileTransformer.class); // instrumentation.addTransformer(transformer); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/JVoidClassFileTransformer.java // @Slf4j // public class JVoidClassFileTransformer implements ClassFileTransformer { // // private static final ClassPool classPool; // // private final ProviderCatalog providerCatalog; // // static { // classPool = ClassPool.getDefault(); // } // // /** // * // * @param providerCatalog // */ // @Inject // public JVoidClassFileTransformer(ProviderCatalog providerCatalog) { // this.providerCatalog = providerCatalog; // } // // /** // * // */ // @Override // public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, // ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // if (className == null) { // return null; // } // try { // String sanitizedClassName = className.replace('/', '.'); // // classPool.insertClassPath(new ByteArrayClassPath(sanitizedClassName, classfileBuffer)); // CtClass ctClass = getCtClass(sanitizedClassName); // // Set<InstrumentationProvider> providers = providerCatalog.getProvidersForClass(ctClass); // // // This is important to avoid to modify classes part of the java.lang.* or // // not related to the application under test. There might be otherwise some // // error related to Javassist transformation. See: // // http://stackoverflow.com/questions/33038650/javassist-side-effects-of-classpool-makeclass?answertab=active#tab-top // if (providers.isEmpty()) { // return null; // } // // for (InstrumentationProvider provider : providers) { // tranformWithProvider(ctClass, provider); // } // // byte[] bytecode = ctClass.toBytecode(); // // ctClass.defrost(); // ctClass.prune(); // ctClass.detach(); // // return bytecode; // } catch (Exception e) { // log.error("Failed to transform class '" + className + "': " + e.getMessage(), e); // throw new JVoidIntrumentationException("Failed to instrument class: " + className, e); // } // } // // /** // * // * @param ctClass // * @param provider // * @throws CannotCompileException // */ // private void tranformWithProvider(CtClass ctClass, InstrumentationProvider provider) throws CannotCompileException { // for (ClassHandler classHandler : provider.getClassHandlers(ctClass)) { // classHandler.handleClass(ctClass); // } // for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { // for (MethodInstrumenter instrumenter : provider.getMethodInstrumenters(ctMethod)) { // if (instrumenter.shouldInstrument(ctMethod)) { // instrumenter.instrument(ctMethod); // } // } // } // } // // /** // * // * @param sanitizedClassName // * @return // */ // private CtClass getCtClass(String sanitizedClassName) { // try { // return classPool.get(sanitizedClassName); // } catch (NotFoundException e) { // throw new JVoidIntrumentationException("Class not found:" + sanitizedClassName, e); // } catch (Exception e) { // throw new JVoidIntrumentationException(e.getLocalizedMessage(), e); // } // } // // } // Path: src/test/java/io/jvoid/test/JVoidAgentPremainTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import io.jvoid.JVoid; import io.jvoid.instrumentation.JVoidClassFileTransformer; package io.jvoid.test; public class JVoidAgentPremainTest extends AbstractJVoidTest { @Override @Before public void setUp() { // Make sure there is no context initialized } @Test public void premainTest() { // Prepare to verify the instrumentation added Instrumentation mockIntrumentation = mock(Instrumentation.class); JVoid.premain(DEFAULT_TEST_CONFIGURATION_FILE, mockIntrumentation); // The configuration is loaded // assertTrue(!JVoidContext.getConfiguration().dbLocation().isEmpty()); // JVoidExecutionContext jvoidExecutionContext; // // The execution is setup // JExecution execution = jvoidExecutionContext.getCurrentExecution(); // assertNotNull(execution); // assertEquals(JVoidContext.getCurrentExecution(), execution); // The transformer is added ArgumentCaptor<ClassFileTransformer> argument = ArgumentCaptor.forClass(ClassFileTransformer.class); verify(mockIntrumentation).addTransformer(argument.capture());
assertTrue(argument.getValue() instanceof JVoidClassFileTransformer);
jVoid/jVoid
src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException;
package io.jvoid.test.instrumentation.provider; public class ProviderCatalogTest extends AbstractJVoidTest { private CtClass ctTestClass1, ctTestClass2;
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; package io.jvoid.test.instrumentation.provider; public class ProviderCatalogTest extends AbstractJVoidTest { private CtClass ctTestClass1, ctTestClass2;
private ProviderCatalog providerCatalog;
jVoid/jVoid
src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException;
package io.jvoid.test.instrumentation.provider; public class ProviderCatalogTest extends AbstractJVoidTest { private CtClass ctTestClass1, ctTestClass2; private ProviderCatalog providerCatalog; @Override @Before public void setUp() throws NotFoundException { ctTestClass1 = classPool.get(TestClass1.class.getName()); ctTestClass2 = classPool.get(TestClass2.class.getName()); providerCatalog = new ProviderCatalog(); providerCatalog.addProvider(new Provider1()); providerCatalog.addProvider(new Provider2()); providerCatalog.addProvider(new Provider3()); } @Override @After public void tearDown() { ctTestClass1.prune(); ctTestClass2.prune(); } @Test public void testGetProviderForClass() {
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; package io.jvoid.test.instrumentation.provider; public class ProviderCatalogTest extends AbstractJVoidTest { private CtClass ctTestClass1, ctTestClass2; private ProviderCatalog providerCatalog; @Override @Before public void setUp() throws NotFoundException { ctTestClass1 = classPool.get(TestClass1.class.getName()); ctTestClass2 = classPool.get(TestClass2.class.getName()); providerCatalog = new ProviderCatalog(); providerCatalog.addProvider(new Provider1()); providerCatalog.addProvider(new Provider2()); providerCatalog.addProvider(new Provider3()); } @Override @After public void tearDown() { ctTestClass1.prune(); ctTestClass2.prune(); } @Test public void testGetProviderForClass() {
List<InstrumentationProvider> providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass1));
jVoid/jVoid
src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException;
public void tearDown() { ctTestClass1.prune(); ctTestClass2.prune(); } @Test public void testGetProviderForClass() { List<InstrumentationProvider> providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass1)); assertEquals(2, providers.size()); assertTrue(providers.get(0) instanceof Provider1); assertTrue(providers.get(1) instanceof Provider2); providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass2)); assertEquals(1, providers.size()); assertTrue(providers.get(0) instanceof Provider3); } /* * ====================================== Helper mock classes * ====================================== */ // Mocked classes for getting ctClass private static class TestClass1 { } private static class TestClass2 { } private static abstract class AbstractMockProvider implements InstrumentationProvider { @Override
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; public void tearDown() { ctTestClass1.prune(); ctTestClass2.prune(); } @Test public void testGetProviderForClass() { List<InstrumentationProvider> providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass1)); assertEquals(2, providers.size()); assertTrue(providers.get(0) instanceof Provider1); assertTrue(providers.get(1) instanceof Provider2); providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass2)); assertEquals(1, providers.size()); assertTrue(providers.get(0) instanceof Provider3); } /* * ====================================== Helper mock classes * ====================================== */ // Mocked classes for getting ctClass private static class TestClass1 { } private static class TestClass2 { } private static abstract class AbstractMockProvider implements InstrumentationProvider { @Override
public List<ClassHandler> getClassHandlers(CtClass ctClass) {
jVoid/jVoid
src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException;
@Test public void testGetProviderForClass() { List<InstrumentationProvider> providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass1)); assertEquals(2, providers.size()); assertTrue(providers.get(0) instanceof Provider1); assertTrue(providers.get(1) instanceof Provider2); providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass2)); assertEquals(1, providers.size()); assertTrue(providers.get(0) instanceof Provider3); } /* * ====================================== Helper mock classes * ====================================== */ // Mocked classes for getting ctClass private static class TestClass1 { } private static class TestClass2 { } private static abstract class AbstractMockProvider implements InstrumentationProvider { @Override public List<ClassHandler> getClassHandlers(CtClass ctClass) { return Collections.emptyList(); } @Override
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java // @Singleton // public class ProviderCatalog { // // private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // // // This is still "hardcoded" providers. Make it discover the providers in // // the classpath automatically // @Inject // public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider, // SpockInstrumentationProvider spockInstrumentationProvider, // JUnitInstrumentationProvider junitInstrumentationProvider) { // registeredProviders.add(appInstrumentationProvider); // registeredProviders.add(spockInstrumentationProvider); // registeredProviders.add(junitInstrumentationProvider); // } // // public void addProvider(InstrumentationProvider provider) { // registeredProviders.add(provider); // } // // public Set<InstrumentationProvider> getProvidersForClass(CtClass ctClass) { // Set<InstrumentationProvider> providers = new LinkedHashSet<>(); // for (InstrumentationProvider provider : registeredProviders) { // if (provider.matches(ctClass)) { // providers.add(provider); // } // } // return providers; // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/instrumentation/provider/ProviderCatalogTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderCatalog; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; @Test public void testGetProviderForClass() { List<InstrumentationProvider> providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass1)); assertEquals(2, providers.size()); assertTrue(providers.get(0) instanceof Provider1); assertTrue(providers.get(1) instanceof Provider2); providers = new ArrayList<>(providerCatalog.getProvidersForClass(ctTestClass2)); assertEquals(1, providers.size()); assertTrue(providers.get(0) instanceof Provider3); } /* * ====================================== Helper mock classes * ====================================== */ // Mocked classes for getting ctClass private static class TestClass1 { } private static class TestClass2 { } private static abstract class AbstractMockProvider implements InstrumentationProvider { @Override public List<ClassHandler> getClassHandlers(CtClass ctClass) { return Collections.emptyList(); } @Override
public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) {
jVoid/jVoid
src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JExecution.java // @Data // public class JExecution implements JEntity<Long> { // // private Long id; // private Long timestamp; // // }
import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JExecution;
package io.jvoid.metadata.repositories; /** * */ @Singleton public class ExecutionsRepository extends AbstractRepository<JExecution, Long> { private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class); @Inject
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JExecution.java // @Data // public class JExecution implements JEntity<Long> { // // private Long id; // private Long timestamp; // // } // Path: src/main/java/io/jvoid/metadata/repositories/ExecutionsRepository.java import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JExecution; package io.jvoid.metadata.repositories; /** * */ @Singleton public class ExecutionsRepository extends AbstractRepository<JExecution, Long> { private ResultSetHandler<JExecution> objectHandler = new BeanHandler<>(JExecution.class); @Inject
public ExecutionsRepository(MetadataDatabase database) {
jVoid/jVoid
src/main/java/io/jvoid/metadata/repositories/ClassStaticBlocksRepository.java
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JClassStaticBlock.java // @Data // public class JClassStaticBlock implements JEntity<Long>, ChecksumAware { // // private Long id; // private String identifier; // private String checksum; // private Long classId; // // }
import java.util.Map; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanMapHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JClassStaticBlock;
package io.jvoid.metadata.repositories; /** * */ @Singleton public class ClassStaticBlocksRepository extends AbstractRepository<JClassStaticBlock, Long> implements TestRelatedEntityRepository<JClassStaticBlock, Long> { private ResultSetHandler<JClassStaticBlock> objectHandler = new BeanHandler<>( JClassStaticBlock.class); private ResultSetHandler<Map<String, JClassStaticBlock>> identifierMapHandler = new BeanMapHandler<>( JClassStaticBlock.class, "identifier"); @Inject
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JClassStaticBlock.java // @Data // public class JClassStaticBlock implements JEntity<Long>, ChecksumAware { // // private Long id; // private String identifier; // private String checksum; // private Long classId; // // } // Path: src/main/java/io/jvoid/metadata/repositories/ClassStaticBlocksRepository.java import java.util.Map; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanMapHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JClassStaticBlock; package io.jvoid.metadata.repositories; /** * */ @Singleton public class ClassStaticBlocksRepository extends AbstractRepository<JClassStaticBlock, Long> implements TestRelatedEntityRepository<JClassStaticBlock, Long> { private ResultSetHandler<JClassStaticBlock> objectHandler = new BeanHandler<>( JClassStaticBlock.class); private ResultSetHandler<Map<String, JClassStaticBlock>> identifierMapHandler = new BeanMapHandler<>( JClassStaticBlock.class, "identifier"); @Inject
public ClassStaticBlocksRepository(MetadataDatabase database) {
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod;
package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler;
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod; package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler;
private MethodInstrumenter trackerMethodInstrumenter;
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod;
package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler; private MethodInstrumenter trackerMethodInstrumenter;
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod; package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler; private MethodInstrumenter trackerMethodInstrumenter;
private JVoidConfiguration jvoidConfiguration;
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod;
package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler; private MethodInstrumenter trackerMethodInstrumenter; private JVoidConfiguration jvoidConfiguration; @Inject public AppInstrumentationProvider(AppClassHandler appClassHandler, TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { super(); this.appClassHandler = appClassHandler; this.trackerMethodInstrumenter = trackerMethodInstrumenter; this.jvoidConfiguration = jvoidConfiguration; } @Override public boolean matches(CtClass ctClass) { JVoidConfiguration config = jvoidConfiguration; boolean matches = ctClass.getName().startsWith(config.basePackage()); if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); } return matches; } @Override
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/ClassHandler.java // public interface ClassHandler { // // void handleClass(CtClass ctClass) throws CannotCompileException; // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java import java.util.Collections; import java.util.List; import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.api.ClassHandler; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CtClass; import javassist.CtMethod; package io.jvoid.instrumentation.provider.app; /** * JVoid instrumentation provider for the application classes. * */ public class AppInstrumentationProvider implements InstrumentationProvider { private AppClassHandler appClassHandler; private MethodInstrumenter trackerMethodInstrumenter; private JVoidConfiguration jvoidConfiguration; @Inject public AppInstrumentationProvider(AppClassHandler appClassHandler, TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { super(); this.appClassHandler = appClassHandler; this.trackerMethodInstrumenter = trackerMethodInstrumenter; this.jvoidConfiguration = jvoidConfiguration; } @Override public boolean matches(CtClass ctClass) { JVoidConfiguration config = jvoidConfiguration; boolean matches = ctClass.getName().startsWith(config.basePackage()); if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); } return matches; } @Override
public List<ClassHandler> getClassHandlers(CtClass ctClass) {
jVoid/jVoid
src/test/java/io/jvoid/test/metadata/repositories/AbstractTestRelatedEntityRepositoryTest.java
// Path: src/main/java/io/jvoid/metadata/model/JEntity.java // public interface JEntity<I> { // // I getId(); // // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestRelatedEntityRepository.java // public interface TestRelatedEntityRepository<T, I> extends BaseRepository<T, I> { // // Map<String, T> findByTestId(Long testId); // // Map<String, T> findByExecutionIdAndRelatedToTestId(Long executionId, Long testId); // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.inject.Inject; import io.jvoid.metadata.model.JEntity; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestRelatedEntityRepository; import io.jvoid.metadata.repositories.TestsRepository;
package io.jvoid.test.metadata.repositories; public abstract class AbstractTestRelatedEntityRepositoryTest<T extends JEntity<ID>, ID, R extends TestRelatedEntityRepository<T, ID>> extends AbstractBaseRepositoryTest<T, ID, R> {
// Path: src/main/java/io/jvoid/metadata/model/JEntity.java // public interface JEntity<I> { // // I getId(); // // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestRelatedEntityRepository.java // public interface TestRelatedEntityRepository<T, I> extends BaseRepository<T, I> { // // Map<String, T> findByTestId(Long testId); // // Map<String, T> findByExecutionIdAndRelatedToTestId(Long executionId, Long testId); // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // } // Path: src/test/java/io/jvoid/test/metadata/repositories/AbstractTestRelatedEntityRepositoryTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.inject.Inject; import io.jvoid.metadata.model.JEntity; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestRelatedEntityRepository; import io.jvoid.metadata.repositories.TestsRepository; package io.jvoid.test.metadata.repositories; public abstract class AbstractTestRelatedEntityRepositoryTest<T extends JEntity<ID>, ID, R extends TestRelatedEntityRepository<T, ID>> extends AbstractBaseRepositoryTest<T, ID, R> {
protected abstract void linkToTest(T entity, JTest jtest);
jVoid/jVoid
src/test/java/io/jvoid/test/metadata/repositories/AbstractTestRelatedEntityRepositoryTest.java
// Path: src/main/java/io/jvoid/metadata/model/JEntity.java // public interface JEntity<I> { // // I getId(); // // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestRelatedEntityRepository.java // public interface TestRelatedEntityRepository<T, I> extends BaseRepository<T, I> { // // Map<String, T> findByTestId(Long testId); // // Map<String, T> findByExecutionIdAndRelatedToTestId(Long executionId, Long testId); // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.inject.Inject; import io.jvoid.metadata.model.JEntity; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestRelatedEntityRepository; import io.jvoid.metadata.repositories.TestsRepository;
package io.jvoid.test.metadata.repositories; public abstract class AbstractTestRelatedEntityRepositoryTest<T extends JEntity<ID>, ID, R extends TestRelatedEntityRepository<T, ID>> extends AbstractBaseRepositoryTest<T, ID, R> { protected abstract void linkToTest(T entity, JTest jtest); @Inject
// Path: src/main/java/io/jvoid/metadata/model/JEntity.java // public interface JEntity<I> { // // I getId(); // // } // // Path: src/main/java/io/jvoid/metadata/model/JTest.java // @Data // public class JTest implements JEntity<Long> { // // public static final String RUN_STATUS_RUN = "RUN"; // public static final String RUN_STATUS_RUNNING = "RUNNING"; // public static final String RUN_STATUS_SKIPPED = "SKIPPED"; // public static final String RUN_STATUS_FAILED = "FAILED"; // // private Long id; // private Long executionId; // private String identifier; // private String runStatus = RUN_STATUS_RUNNING; // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestRelatedEntityRepository.java // public interface TestRelatedEntityRepository<T, I> extends BaseRepository<T, I> { // // Map<String, T> findByTestId(Long testId); // // Map<String, T> findByExecutionIdAndRelatedToTestId(Long executionId, Long testId); // // } // // Path: src/main/java/io/jvoid/metadata/repositories/TestsRepository.java // @Singleton // public class TestsRepository extends AbstractRepository<JTest, Long> { // // private ResultSetHandler<JTest> objectHandler = new BeanHandler<>(JTest.class); // // @Inject // public TestsRepository(MetadataDatabase database) { // super(database); // } // // @Override // public JTest findById(Long id) { // return query("SELECT * FROM tests WHERE id = ?", objectHandler, id); // } // // @Override // public JTest add(JTest jtest) { // assertNull(jtest.getId()); // String sql = "INSERT INTO tests (executionId, identifier, runStatus) VALUES (?, ?, ?)"; // long id = executeInsert(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus()); // jtest.setId(id); // return jtest; // } // // public JTest update(JTest jtest) { // String sql = "UPDATE tests SET executionId = ?, identifier = ?, runStatus = ? WHERE id = ?"; // executeUpdate(sql, jtest.getExecutionId(), jtest.getIdentifier(), jtest.getRunStatus(), jtest.getId()); // return jtest; // } // // public void linkMethodAndClass(JTest test, long jmethodId, long classId) { // List<String> sqlStms = new ArrayList<>(); // List<Object[]> parametersList = new ArrayList<>(); // sqlStms.add("INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"); // parametersList.add( new Object[]{test.getId(), jmethodId}); // sqlStms.add("INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"); // parametersList.add( new Object[]{test.getId(), classId}); // // executeMultipleInserts(sqlStms, parametersList); // } // // public void linkMethod(JTest test, Long jmethodId) { // String sql = "INSERT INTO test_methods (testId, methodId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), methodId=VALUES(methodId)"; // executeInsert(sql, test.getId(), jmethodId); // } // // public void linkClass(JTest test, Long jclassId) { // String sql = "INSERT INTO test_classes (testId, classId) VALUES (?, ?) ON DUPLICATE KEY UPDATE testId=VALUES(testId), classId=VALUES(classId)"; // executeInsert(sql, test.getId(), jclassId); // } // // public JTest findByIdenfifierAndExecutionId(String identifier, long executionId) { // return query("SELECT t.* FROM tests t WHERE t.identifier = ? AND t.executionId = ?", objectHandler, identifier, executionId); // } // // public JTest findLatestExecutedByIdenfifier(String identifier) { // // @formatter:off // String sql = "SELECT t.* " + // "FROM tests t " + // "WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " AND t.executionId = (" + // " SELECT MAX(t.executionId) FROM tests t " + // " WHERE t.identifier = ? " + // " AND (t.runStatus = 'FAILED' OR t.runStatus = 'RUN') " + // " )"; // // @formatter:on // return query(sql, objectHandler, identifier, identifier); // } // // } // Path: src/test/java/io/jvoid/test/metadata/repositories/AbstractTestRelatedEntityRepositoryTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.inject.Inject; import io.jvoid.metadata.model.JEntity; import io.jvoid.metadata.model.JTest; import io.jvoid.metadata.repositories.TestRelatedEntityRepository; import io.jvoid.metadata.repositories.TestsRepository; package io.jvoid.test.metadata.repositories; public abstract class AbstractTestRelatedEntityRepositoryTest<T extends JEntity<ID>, ID, R extends TestRelatedEntityRepository<T, ID>> extends AbstractBaseRepositoryTest<T, ID, R> { protected abstract void linkToTest(T entity, JTest jtest); @Inject
private TestsRepository testsRepository;
jVoid/jVoid
src/main/java/io/jvoid/guice/JVoidModule.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // }
import com.google.inject.AbstractModule; import com.google.inject.Singleton; import io.jvoid.configuration.JVoidConfiguration;
package io.jvoid.guice; /** * Guice module for JVoid */ public class JVoidModule extends AbstractModule { @Override protected void configure() {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // Path: src/main/java/io/jvoid/guice/JVoidModule.java import com.google.inject.AbstractModule; import com.google.inject.Singleton; import io.jvoid.configuration.JVoidConfiguration; package io.jvoid.guice; /** * Guice module for JVoid */ public class JVoidModule extends AbstractModule { @Override protected void configure() {
bind(JVoidConfiguration.class).toProvider(JVoidConfigurationProvider.class).in(Singleton.class);
jVoid/jVoid
src/test/java/io/jvoid/test/database/DbUtilsTest.java
// Path: src/main/java/io/jvoid/database/DbUtils.java // public class DbUtils { // // private static final QueryRunner queryRunner = new QueryRunner(); // // private DbUtils() { // super(); // } // // /** // * // * @param database // * @param sql // * @param parameters // */ // public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // QueryRunner query = new QueryRunner(); // query.update(conn, sql, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param parameters // * @return // */ // public static Long executeInsert(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // return queryRunner.insert(conn, sql, rsh, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sqlList // * @param parametersList // * @return // */ // public static List<Long> executeMultipleInserts(MetadataDatabase database, List<String> sqlList, List<Object[]> parametersList) { // try (Connection conn = database.getConnection()) { // List<Long> results = new ArrayList<>(); // for (int i = 0; i < sqlList.size(); i++) { // Object[] parameters = parametersList.get(i); // String sql = sqlList.get(i); // // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // Long id = queryRunner.insert(conn, sql, rsh, parameters); // results.add(id); // } // return results; // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param resultSetHandler // * @param parameters // * @return // */ // public static <T> T query(MetadataDatabase database, String sql, ResultSetHandler<T> resultSetHandler, Object... parameters) { // try (Connection conn = database.getConnection()) { // return queryRunner.query(conn, sql, resultSetHandler, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java // public class JVoidDataAccessException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public JVoidDataAccessException(String msg, Throwable cause) { // super(msg, cause); // } // // public JVoidDataAccessException(Throwable cause) { // super(cause); // } // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import java.util.Arrays; import java.util.Collections; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.junit.Test; import io.jvoid.database.DbUtils; import io.jvoid.exceptions.JVoidDataAccessException; import io.jvoid.test.AbstractJVoidTest;
package io.jvoid.test.database; public class DbUtilsTest extends AbstractJVoidTest { @Test(expected = JVoidDataAccessException.class) public void testInvalidUpdateStatement() {
// Path: src/main/java/io/jvoid/database/DbUtils.java // public class DbUtils { // // private static final QueryRunner queryRunner = new QueryRunner(); // // private DbUtils() { // super(); // } // // /** // * // * @param database // * @param sql // * @param parameters // */ // public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // QueryRunner query = new QueryRunner(); // query.update(conn, sql, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param parameters // * @return // */ // public static Long executeInsert(MetadataDatabase database, String sql, Object... parameters) { // try (Connection conn = database.getConnection()) { // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // return queryRunner.insert(conn, sql, rsh, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sqlList // * @param parametersList // * @return // */ // public static List<Long> executeMultipleInserts(MetadataDatabase database, List<String> sqlList, List<Object[]> parametersList) { // try (Connection conn = database.getConnection()) { // List<Long> results = new ArrayList<>(); // for (int i = 0; i < sqlList.size(); i++) { // Object[] parameters = parametersList.get(i); // String sql = sqlList.get(i); // // ResultSetHandler<Long> rsh = new ScalarHandler<>(); // Long id = queryRunner.insert(conn, sql, rsh, parameters); // results.add(id); // } // return results; // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // // /** // * // * @param database // * @param sql // * @param resultSetHandler // * @param parameters // * @return // */ // public static <T> T query(MetadataDatabase database, String sql, ResultSetHandler<T> resultSetHandler, Object... parameters) { // try (Connection conn = database.getConnection()) { // return queryRunner.query(conn, sql, resultSetHandler, parameters); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java // public class JVoidDataAccessException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public JVoidDataAccessException(String msg, Throwable cause) { // super(msg, cause); // } // // public JVoidDataAccessException(Throwable cause) { // super(cause); // } // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/database/DbUtilsTest.java import java.util.Arrays; import java.util.Collections; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.junit.Test; import io.jvoid.database.DbUtils; import io.jvoid.exceptions.JVoidDataAccessException; import io.jvoid.test.AbstractJVoidTest; package io.jvoid.test.database; public class DbUtilsTest extends AbstractJVoidTest { @Test(expected = JVoidDataAccessException.class) public void testInvalidUpdateStatement() {
DbUtils.executeUpdate(metadataDatabase, "UPDATE no_table(id) SET id=1");
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java
// Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java // @Singleton // public class JVoidInstrumentationHelperHolder { // // private JVoidInstrumentationHelper helper; // // private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder(); // // public static JVoidInstrumentationHelperHolder getInstance() { // return instance; // } // // public JVoidInstrumentationHelper get() { // return helper; // } // // public void set(JVoidInstrumentationHelper helper) { // this.helper = helper; // } // // public static String helperGetterRef() { // return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()"; // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // }
import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CannotCompileException; import javassist.CtMethod;
package io.jvoid.instrumentation.provider.spock; /** * Tracker method for Spock tests. It notifies JVoid that a test is going * to be executed. * */ public class RunFeatureMethodInstrumenter implements MethodInstrumenter { @Override public void instrument(CtMethod method) throws CannotCompileException { // Right now is only called for the runFeature method StringBuilder sb = new StringBuilder(1024); // Get the String identifier of the spec sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
// Path: src/main/java/io/jvoid/instrumentation/JVoidInstrumentationHelperHolder.java // @Singleton // public class JVoidInstrumentationHelperHolder { // // private JVoidInstrumentationHelper helper; // // private static final JVoidInstrumentationHelperHolder instance = new JVoidInstrumentationHelperHolder(); // // public static JVoidInstrumentationHelperHolder getInstance() { // return instance; // } // // public JVoidInstrumentationHelper get() { // return helper; // } // // public void set(JVoidInstrumentationHelper helper) { // this.helper = helper; // } // // public static String helperGetterRef() { // return JVoidInstrumentationHelperHolder.class.getName() + ".getInstance().get()"; // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/api/MethodInstrumenter.java // public interface MethodInstrumenter { // // void instrument(CtMethod ctMethod) throws CannotCompileException; // // boolean shouldInstrument(CtMethod ctMethod); // // } // Path: src/main/java/io/jvoid/instrumentation/provider/spock/RunFeatureMethodInstrumenter.java import io.jvoid.instrumentation.JVoidInstrumentationHelperHolder; import io.jvoid.instrumentation.provider.api.MethodInstrumenter; import javassist.CannotCompileException; import javassist.CtMethod; package io.jvoid.instrumentation.provider.spock; /** * Tracker method for Spock tests. It notifies JVoid that a test is going * to be executed. * */ public class RunFeatureMethodInstrumenter implements MethodInstrumenter { @Override public void instrument(CtMethod method) throws CannotCompileException { // Right now is only called for the runFeature method StringBuilder sb = new StringBuilder(1024); // Get the String identifier of the spec sb.append("String featureId = currentFeature.getFeatureMethod().getDescription().toString();\n");
sb.append(JVoidInstrumentationHelperHolder.helperGetterRef() + ".beginTest(featureId);\n");
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties();
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties();
JVoidConfiguration config = new PropertyBasedConfiguration(properties);
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties();
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties();
JVoidConfiguration config = new PropertyBasedConfiguration(properties);
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try {
new JVoidConfigurationValidator().validate(config);
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try { new JVoidConfigurationValidator().validate(config); Assert.fail();
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try { new JVoidConfigurationValidator().validate(config); Assert.fail();
} catch (JVoidConfigurationException e) {
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // }
import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException;
package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try { new JVoidConfigurationValidator().validate(config); Assert.fail(); } catch (JVoidConfigurationException e) { } } @Test public void testValidateClasspathConfig() { try {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/configuration/JVoidConfigurationValidator.java // public class JVoidConfigurationValidator { // // public void validate(JVoidConfiguration config) throws JVoidConfigurationException { // if (config.basePackage() == null || config.basePackage().isEmpty()) { // throw new JVoidConfigurationException("Configuration needs a 'app.package' property."); // } // } // } // // Path: src/main/java/io/jvoid/configuration/JVoidPropertiesBasedConfigurationLoader.java // public class JVoidPropertiesBasedConfigurationLoader { // // private static final String CONFIG_FILE_NAME = "jvoid.config"; // // public synchronized PropertyBasedConfiguration load(String parameterConfigPath) throws JVoidConfigurationException { // Properties properties = new Properties(); // properties.putAll(loadFromClasspath()); // properties.putAll(loadFromHomeDir()); // properties.putAll(loadFromWorkingDir()); // if (parameterConfigPath != null && !parameterConfigPath.isEmpty()) { // properties.putAll(loadFromParameterValue(parameterConfigPath)); // } // // return new PropertyBasedConfiguration(properties); // } // // private Map<? extends Object, ? extends Object> loadFromParameterValue(String parameterConfigPath) throws JVoidConfigurationException { // return loadFromDir(parameterConfigPath); // } // // private Map<? extends Object, ? extends Object> loadFromWorkingDir() throws JVoidConfigurationException { // String path = System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromHomeDir() throws JVoidConfigurationException { // String path = System.getProperty("user.home") + File.separator + CONFIG_FILE_NAME; // return loadFromDir(path); // } // // private Map<? extends Object, ? extends Object> loadFromClasspath() throws JVoidConfigurationException { // Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // InputStream classPathConfiguration = classLoader.getResourceAsStream(CONFIG_FILE_NAME); // if (classPathConfiguration != null) { // try { // properties.load(classPathConfiguration); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read builtin configuration", e); // } // } // // return properties; // } // // private Map<? extends Object, ? extends Object> loadFromDir(String path) throws JVoidConfigurationException { // Properties properties = new Properties(); // File file = new File(path); // if (file.exists()) { // FileInputStream fis; // try { // fis = new FileInputStream(file); // properties.load(fis); // } catch (IOException e) { // throw new JVoidConfigurationException("Unable to read configuration from " + path, e); // } // } // return properties; // } // } // // Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidConfigurationException.java // public class JVoidConfigurationException extends Exception { // // private static final long serialVersionUID = 1L; // // public JVoidConfigurationException(String message) { // super(message); // } // public JVoidConfigurationException(String message, Throwable e) { // super(message, e); // } // // } // Path: src/test/java/io/jvoid/test/configuration/JVoidConfigurationValidatorTest.java import java.util.Properties; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.configuration.JVoidConfigurationValidator; import io.jvoid.configuration.JVoidPropertiesBasedConfigurationLoader; import io.jvoid.configuration.PropertyBasedConfiguration; import io.jvoid.exceptions.JVoidConfigurationException; package io.jvoid.test.configuration; public class JVoidConfigurationValidatorTest { @Before public void setUp() { } @After public void tearDown() { } @Test public void testValidateEmptyConfig() { Properties properties = new Properties(); JVoidConfiguration config = new PropertyBasedConfiguration(properties); try { new JVoidConfigurationValidator().validate(config); Assert.fail(); } catch (JVoidConfigurationException e) { } } @Test public void testValidateClasspathConfig() { try {
JVoidConfiguration config = new JVoidPropertiesBasedConfigurationLoader().load("./src/test/resources/invalid-jvoid.config");
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/CtMethodChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // }
import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtMethodChecksummer extends AbstractCtBehaviorChecksummer<CtMethod> { @Inject
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // Path: src/main/java/io/jvoid/metadata/checksum/CtMethodChecksummer.java import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import javassist.CtMethod; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtMethodChecksummer extends AbstractCtBehaviorChecksummer<CtMethod> { @Inject
public CtMethodChecksummer(JVoidConfiguration jVoidConfiguration) {
jVoid/jVoid
src/test/java/io/jvoid/test/instrumentation/provider/ProviderUtilTest.java
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderUtil.java // @Singleton // public class ProviderUtil { // // public String getClassIdentifier(CtClass clazz) { // return clazz.getName(); // } // // public String getConstructorIdentifier(CtConstructor constructor) { // return constructor.getLongName(); // } // // public String getMethodIdentifier(CtMethod method) { // return method.getLongName(); // } // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // }
import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderUtil; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException;
package io.jvoid.test.instrumentation.provider; /* * It would be really nice to test the ProviderUtil methods mocking * CtMethod and CtConstructor. Unfortunately, those are final classes * and even PowerMock has errors when trying to mock them. So for these * reasons we test the ProviderUtil in an alternative way. */ public class ProviderUtilTest extends AbstractJVoidTest { private CtClass ctClassTestClass;
// Path: src/main/java/io/jvoid/instrumentation/provider/ProviderUtil.java // @Singleton // public class ProviderUtil { // // public String getClassIdentifier(CtClass clazz) { // return clazz.getName(); // } // // public String getConstructorIdentifier(CtConstructor constructor) { // return constructor.getLongName(); // } // // public String getMethodIdentifier(CtMethod method) { // return method.getLongName(); // } // // } // // Path: src/test/java/io/jvoid/test/AbstractJVoidTest.java // @UseModules({ JVoidModule.class }) // @RunWith(JVoidTestRunner.class) // public abstract class AbstractJVoidTest { // // protected static final String DEFAULT_TEST_CONFIGURATION_FILE = "./src/test/resources/test-jvoid.config"; // // private static ThreadLocal<Long> currentExecutionId = new ThreadLocal<>(); // Parallel tests? // // protected static final ClassPool classPool; // // @Inject // protected MetadataDatabase metadataDatabase; // // @Inject // protected JVoidInstrumentationHelper instrumentationHelper; // // @Inject // protected ExecutionsRepository executionsRepository; // // @Inject // protected JVoidExecutionContext jvoidExecutionContext; // // static { // // See ClassPool JavaDoc for memory consumption issues // ClassPool.doPruning = true; // classPool = ClassPool.getDefault(); // } // // @Before // public void setUp() throws Exception { // // Make sure the database is initialized // metadataDatabase.startup(); // // // Makes sure that the database is clean, then restarts it to apply the migrations. // // To be sure that each test runs in its own clean db environment. // // TODO: Can this be more elegant? // DbUtils.executeUpdate(metadataDatabase, "DROP ALL OBJECTS"); // metadataDatabase.shutdown(); // metadataDatabase.startup(); // // currentExecutionId.set(0L); // } // // @After // public void tearDown() { // metadataDatabase.shutdown(); // JVoidInstrumentationHelperHolder.getInstance().set(instrumentationHelper); // } // // /* // * Utility methods for current JExecution // */ // protected Long getCurrentExecutionId() { // return currentExecutionId.get(); // } // // protected synchronized JExecution setupCurrentExecution() { // return setupCurrentExecution(null); // } // // protected synchronized JExecution setupCurrentExecution(Long timestamp) { // JExecution currentExecution = new JExecution(); // currentExecution.setTimestamp(timestamp == null ? System.currentTimeMillis() : timestamp); // currentExecution = executionsRepository.add(currentExecution); // currentExecutionId.set(currentExecution.getId()); // jvoidExecutionContext.setCurrentExecution(currentExecution); // return currentExecution; // } // } // Path: src/test/java/io/jvoid/test/instrumentation/provider/ProviderUtilTest.java import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jvoid.instrumentation.provider.ProviderUtil; import io.jvoid.test.AbstractJVoidTest; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; package io.jvoid.test.instrumentation.provider; /* * It would be really nice to test the ProviderUtil methods mocking * CtMethod and CtConstructor. Unfortunately, those are final classes * and even PowerMock has errors when trying to mock them. So for these * reasons we test the ProviderUtil in an alternative way. */ public class ProviderUtilTest extends AbstractJVoidTest { private CtClass ctClassTestClass;
private ProviderUtil providerUtils;
jVoid/jVoid
src/main/java/io/jvoid/metadata/repositories/ClassConstructorsRepository.java
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JClassConstructor.java // @Data // public class JClassConstructor implements JEntity<Long>, ChecksumAware { // // private Long id; // private String identifier; // private String checksum; // private Long classId; // // }
import java.util.Map; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanMapHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JClassConstructor;
package io.jvoid.metadata.repositories; /** * */ @Singleton public class ClassConstructorsRepository extends AbstractRepository<JClassConstructor, Long> implements TestRelatedEntityRepository<JClassConstructor, Long> { private ResultSetHandler<JClassConstructor> objectHandler = new BeanHandler<>( JClassConstructor.class); private ResultSetHandler<Map<String, JClassConstructor>> identifierMapHandler = new BeanMapHandler<>( JClassConstructor.class, "identifier"); @Inject
// Path: src/main/java/io/jvoid/database/MetadataDatabase.java // @Singleton // public class MetadataDatabase { // // private JVoidConfiguration configuration; // // private HikariDataSource ds; // // /** // * // * @param configuration // */ // @Inject // public MetadataDatabase(JVoidConfiguration configuration) { // this.configuration = configuration; // } // // /** // * // */ // @Inject // public void startup() { // if (ds != null && !ds.isClosed()) { // return; // } // // HikariConfig config = new HikariConfig(); // config.setJdbcUrl(configuration.dbUrl()); // config.setUsername(configuration.dbUsername()); // config.setPassword(configuration.dbPassword()); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // ds = new HikariDataSource(config); // // initializeDatabase(); // } // // /** // * // */ // public void shutdown() { // if (ds != null) { // ds.close(); // ds = null; // } // } // // /** // * // */ // private void initializeDatabase() { // Flyway flyway = new Flyway(); // flyway.setDataSource(ds); // flyway.migrate(); // } // // /** // * // * @return A connection from the pool // */ // public Connection getConnection() { // try { // return ds.getConnection(); // } catch (SQLException e) { // throw new JVoidDataAccessException(e); // } // } // } // // Path: src/main/java/io/jvoid/metadata/model/JClassConstructor.java // @Data // public class JClassConstructor implements JEntity<Long>, ChecksumAware { // // private Long id; // private String identifier; // private String checksum; // private Long classId; // // } // Path: src/main/java/io/jvoid/metadata/repositories/ClassConstructorsRepository.java import java.util.Map; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanMapHandler; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.database.MetadataDatabase; import io.jvoid.metadata.model.JClassConstructor; package io.jvoid.metadata.repositories; /** * */ @Singleton public class ClassConstructorsRepository extends AbstractRepository<JClassConstructor, Long> implements TestRelatedEntityRepository<JClassConstructor, Long> { private ResultSetHandler<JClassConstructor> objectHandler = new BeanHandler<>( JClassConstructor.class); private ResultSetHandler<Map<String, JClassConstructor>> identifierMapHandler = new BeanMapHandler<>( JClassConstructor.class, "identifier"); @Inject
public ClassConstructorsRepository(MetadataDatabase database) {
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationJClassHolder.java
// Path: src/main/java/io/jvoid/metadata/model/JClass.java // @Data // public class JClass implements JEntity<Long>, ChecksumAware { // // private Long id; // private Long executionId; // private String identifier; // private String checksum; // private String superClassIdentifier; // // }
import com.google.inject.Singleton; import io.jvoid.metadata.model.JClass;
package io.jvoid.instrumentation.provider.app; /** * This class is used to keep track of the current JClass object * created by the {@code AppClassHandler} and useful in the * {@code TrackerMethodInstrumenter} in order to avoid multiple * queries to the DB. * */ @Singleton public class AppInstrumentationJClassHolder {
// Path: src/main/java/io/jvoid/metadata/model/JClass.java // @Data // public class JClass implements JEntity<Long>, ChecksumAware { // // private Long id; // private Long executionId; // private String identifier; // private String checksum; // private String superClassIdentifier; // // } // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationJClassHolder.java import com.google.inject.Singleton; import io.jvoid.metadata.model.JClass; package io.jvoid.instrumentation.provider.app; /** * This class is used to keep track of the current JClass object * created by the {@code AppClassHandler} and useful in the * {@code TrackerMethodInstrumenter} in order to avoid multiple * queries to the DB. * */ @Singleton public class AppInstrumentationJClassHolder {
private ThreadLocal<JClass> jClassUnderInstrumentation = new ThreadLocal<>();
jVoid/jVoid
src/test/java/io/jvoid/test/configuration/PropertyBasedConfigurationTest.java
// Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // }
import java.util.Properties; import org.junit.Assert; import org.junit.Test; import io.jvoid.configuration.PropertyBasedConfiguration;
package io.jvoid.test.configuration; public class PropertyBasedConfigurationTest { private static final String TEST_VALUE = "test_value"; @Test public void testInvalidProperties() { Properties properties = new Properties(); properties.setProperty("db.location", TEST_VALUE); try {
// Path: src/main/java/io/jvoid/configuration/PropertyBasedConfiguration.java // public class PropertyBasedConfiguration implements JVoidConfiguration { // // private Properties properties; // // public PropertyBasedConfiguration(Properties properties) { // if (properties == null) { // throw new IllegalArgumentException("Backing properties needed for the configuration"); // } // // this.properties = properties; // } // // @Override // public String dbUrl() { // return properties.getProperty("db.url"); // } // // @Override // public String dbUsername() { // return properties.getProperty("db.username"); // } // // @Override // public String dbPassword() { // return properties.getProperty("db.password"); // } // // @Override // public String basePackage() { // return properties.getProperty("app.package"); // } // // @Override // public String excludes() { // return properties.getProperty("app.excludes"); // } // // @Override // public String includes() { // return properties.getProperty("app.includes"); // } // // @Override // public Boolean heuristicExcludeCglib() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeCglib")); // } // // @Override // public Boolean heuristicExcludeJacoco() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeJacoco")); // } // // @Override // public Boolean heuristicExcludeGroovyCallSite() { // return Boolean.valueOf(properties.getProperty("app.heuristic.excludeGroovyCallSite")); // } // // } // Path: src/test/java/io/jvoid/test/configuration/PropertyBasedConfigurationTest.java import java.util.Properties; import org.junit.Assert; import org.junit.Test; import io.jvoid.configuration.PropertyBasedConfiguration; package io.jvoid.test.configuration; public class PropertyBasedConfigurationTest { private static final String TEST_VALUE = "test_value"; @Test public void testInvalidProperties() { Properties properties = new Properties(); properties.setProperty("db.location", TEST_VALUE); try {
new PropertyBasedConfiguration(null);
jVoid/jVoid
src/main/java/io/jvoid/database/DbUtils.java
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java // public class JVoidDataAccessException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public JVoidDataAccessException(String msg, Throwable cause) { // super(msg, cause); // } // // public JVoidDataAccessException(Throwable cause) { // super(cause); // } // // }
import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import io.jvoid.exceptions.JVoidDataAccessException;
package io.jvoid.database; /** * Simple utility class that makes it easy to interact with a relational DB using * apache dbutils API. * */ public class DbUtils { private static final QueryRunner queryRunner = new QueryRunner(); private DbUtils() { super(); } /** * * @param database * @param sql * @param parameters */ public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { try (Connection conn = database.getConnection()) { QueryRunner query = new QueryRunner(); query.update(conn, sql, parameters); } catch (SQLException e) {
// Path: src/main/java/io/jvoid/exceptions/JVoidDataAccessException.java // public class JVoidDataAccessException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public JVoidDataAccessException(String msg, Throwable cause) { // super(msg, cause); // } // // public JVoidDataAccessException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/io/jvoid/database/DbUtils.java import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import io.jvoid.exceptions.JVoidDataAccessException; package io.jvoid.database; /** * Simple utility class that makes it easy to interact with a relational DB using * apache dbutils API. * */ public class DbUtils { private static final QueryRunner queryRunner = new QueryRunner(); private DbUtils() { super(); } /** * * @param database * @param sql * @param parameters */ public static void executeUpdate(MetadataDatabase database, String sql, Object... parameters) { try (Connection conn = database.getConnection()) { QueryRunner query = new QueryRunner(); query.update(conn, sql, parameters); } catch (SQLException e) {
throw new JVoidDataAccessException(e);
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/AbstractChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // }
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.exceptions.JVoidIntrumentationException; import lombok.AllArgsConstructor;
package io.jvoid.metadata.checksum; /** * Generic class that generates a checksum for the entities tracked in JVoid. * (Those entities are typically classes, methods, constructors, static blocks, etc.) */ @AllArgsConstructor public abstract class AbstractChecksummer<T> implements Checksummer<T> {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // Path: src/main/java/io/jvoid/metadata/checksum/AbstractChecksummer.java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.exceptions.JVoidIntrumentationException; import lombok.AllArgsConstructor; package io.jvoid.metadata.checksum; /** * Generic class that generates a checksum for the entities tracked in JVoid. * (Those entities are typically classes, methods, constructors, static blocks, etc.) */ @AllArgsConstructor public abstract class AbstractChecksummer<T> implements Checksummer<T> {
protected JVoidConfiguration jVoidConfiguration;
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/AbstractChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // }
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.exceptions.JVoidIntrumentationException; import lombok.AllArgsConstructor;
package io.jvoid.metadata.checksum; /** * Generic class that generates a checksum for the entities tracked in JVoid. * (Those entities are typically classes, methods, constructors, static blocks, etc.) */ @AllArgsConstructor public abstract class AbstractChecksummer<T> implements Checksummer<T> { protected JVoidConfiguration jVoidConfiguration; protected String computeChecksum(byte[] input) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(input); return String.format("%064x", new java.math.BigInteger(1, md.digest())); } catch (NoSuchAlgorithmException e) {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/exceptions/JVoidIntrumentationException.java // public class JVoidIntrumentationException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public JVoidIntrumentationException(String message, Throwable cause) { // super(message, cause); // } // // public JVoidIntrumentationException(String cause) { // super(cause); // } // // } // Path: src/main/java/io/jvoid/metadata/checksum/AbstractChecksummer.java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.exceptions.JVoidIntrumentationException; import lombok.AllArgsConstructor; package io.jvoid.metadata.checksum; /** * Generic class that generates a checksum for the entities tracked in JVoid. * (Those entities are typically classes, methods, constructors, static blocks, etc.) */ @AllArgsConstructor public abstract class AbstractChecksummer<T> implements Checksummer<T> { protected JVoidConfiguration jVoidConfiguration; protected String computeChecksum(byte[] input) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(input); return String.format("%064x", new java.math.BigInteger(1, md.digest())); } catch (NoSuchAlgorithmException e) {
throw new JVoidIntrumentationException(e.getLocalizedMessage(), e);
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/CtClassChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java // public class AppHeuristicHelper { // // public static boolean isCGLIBProxy(CtClass ctClass) { // String name = ctClass.getName(); // return name.contains("$$") || name.contains("CGLIB"); // // } // public static boolean isCGLIBProxy(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$$") || methodName.contains("CGLIB"); // } // // public static boolean isGroovyCallSite(CtClass ctClass) { // try { // CtClass superclass = ctClass.getSuperclass(); // return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite"); // } catch (Exception e) { // return false; // Being conservative here... // } // } // // public static boolean isJacocoField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$jacoco"); // } // // public static boolean isGeneratedField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$$"); // } // // public static boolean isJacocoMethod(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$jacoco"); // } // // }
import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.app.AppHeuristicHelper; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtClassChecksummer extends AbstractChecksummer<CtClass> { @Inject
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java // public class AppHeuristicHelper { // // public static boolean isCGLIBProxy(CtClass ctClass) { // String name = ctClass.getName(); // return name.contains("$$") || name.contains("CGLIB"); // // } // public static boolean isCGLIBProxy(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$$") || methodName.contains("CGLIB"); // } // // public static boolean isGroovyCallSite(CtClass ctClass) { // try { // CtClass superclass = ctClass.getSuperclass(); // return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite"); // } catch (Exception e) { // return false; // Being conservative here... // } // } // // public static boolean isJacocoField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$jacoco"); // } // // public static boolean isGeneratedField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$$"); // } // // public static boolean isJacocoMethod(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$jacoco"); // } // // } // Path: src/main/java/io/jvoid/metadata/checksum/CtClassChecksummer.java import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.app.AppHeuristicHelper; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtClassChecksummer extends AbstractChecksummer<CtClass> { @Inject
public CtClassChecksummer(JVoidConfiguration jVoidConfiguration) {
jVoid/jVoid
src/main/java/io/jvoid/metadata/checksum/CtClassChecksummer.java
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java // public class AppHeuristicHelper { // // public static boolean isCGLIBProxy(CtClass ctClass) { // String name = ctClass.getName(); // return name.contains("$$") || name.contains("CGLIB"); // // } // public static boolean isCGLIBProxy(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$$") || methodName.contains("CGLIB"); // } // // public static boolean isGroovyCallSite(CtClass ctClass) { // try { // CtClass superclass = ctClass.getSuperclass(); // return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite"); // } catch (Exception e) { // return false; // Being conservative here... // } // } // // public static boolean isJacocoField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$jacoco"); // } // // public static boolean isGeneratedField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$$"); // } // // public static boolean isJacocoMethod(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$jacoco"); // } // // }
import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.app.AppHeuristicHelper; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j;
package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtClassChecksummer extends AbstractChecksummer<CtClass> { @Inject public CtClassChecksummer(JVoidConfiguration jVoidConfiguration) { super(jVoidConfiguration); } @Override public String checksum(CtClass clazz) { StringBuilder data = new StringBuilder(1024); handleInterfaces(clazz, data); handleSuperClass(clazz, data); handleAnnotations(clazz, data); handleFields(clazz, data); return computeChecksum(data.toString().getBytes()); } private void handleFields(CtClass clazz, StringBuilder data) { // This is not ideal, this should be in the actual method checksum to prevent a change to a class to invalidade all the tests that use it // However we can hope on our users design skills so that the target classes state will be relevant to *all* methods :) for (CtField field : clazz.getDeclaredFields()) {
// Path: src/main/java/io/jvoid/configuration/JVoidConfiguration.java // public interface JVoidConfiguration { // // String dbUrl(); // // String dbUsername(); // // String dbPassword(); // // String basePackage(); // // String excludes(); // // String includes(); // // Boolean heuristicExcludeCglib(); // // Boolean heuristicExcludeJacoco(); // // Boolean heuristicExcludeGroovyCallSite(); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppHeuristicHelper.java // public class AppHeuristicHelper { // // public static boolean isCGLIBProxy(CtClass ctClass) { // String name = ctClass.getName(); // return name.contains("$$") || name.contains("CGLIB"); // // } // public static boolean isCGLIBProxy(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$$") || methodName.contains("CGLIB"); // } // // public static boolean isGroovyCallSite(CtClass ctClass) { // try { // CtClass superclass = ctClass.getSuperclass(); // return superclass != null && superclass.getName().startsWith("org.codehaus.groovy.runtime.callsite"); // } catch (Exception e) { // return false; // Being conservative here... // } // } // // public static boolean isJacocoField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$jacoco"); // } // // public static boolean isGeneratedField(CtField ctField) { // String methodName = ctField.getName(); // return methodName.startsWith("$$"); // } // // public static boolean isJacocoMethod(CtMethod ctMethod) { // String methodName = ctMethod.getLongName(); // return methodName.contains("$jacoco"); // } // // } // Path: src/main/java/io/jvoid/metadata/checksum/CtClassChecksummer.java import com.google.inject.Inject; import io.jvoid.configuration.JVoidConfiguration; import io.jvoid.instrumentation.provider.app.AppHeuristicHelper; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import lombok.extern.slf4j.Slf4j; package io.jvoid.metadata.checksum; /** * */ @Slf4j class CtClassChecksummer extends AbstractChecksummer<CtClass> { @Inject public CtClassChecksummer(JVoidConfiguration jVoidConfiguration) { super(jVoidConfiguration); } @Override public String checksum(CtClass clazz) { StringBuilder data = new StringBuilder(1024); handleInterfaces(clazz, data); handleSuperClass(clazz, data); handleAnnotations(clazz, data); handleFields(clazz, data); return computeChecksum(data.toString().getBytes()); } private void handleFields(CtClass clazz, StringBuilder data) { // This is not ideal, this should be in the actual method checksum to prevent a change to a class to invalidade all the tests that use it // However we can hope on our users design skills so that the target classes state will be relevant to *all* methods :) for (CtField field : clazz.getDeclaredFields()) {
if ( (jVoidConfiguration.heuristicExcludeJacoco() && AppHeuristicHelper.isJacocoField(field)) ||
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass;
package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog {
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // } // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass; package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog {
private List<InstrumentationProvider> registeredProviders = new ArrayList<>();
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass;
package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog { private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // This is still "hardcoded" providers. Make it discover the providers in // the classpath automatically @Inject
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // } // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass; package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog { private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // This is still "hardcoded" providers. Make it discover the providers in // the classpath automatically @Inject
public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider,
jVoid/jVoid
src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass;
package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog { private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // This is still "hardcoded" providers. Make it discover the providers in // the classpath automatically @Inject public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider,
// Path: src/main/java/io/jvoid/instrumentation/provider/api/InstrumentationProvider.java // public interface InstrumentationProvider { // // boolean matches(CtClass ctClass); // // List<ClassHandler> getClassHandlers(CtClass ctClass); // // List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod); // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/app/AppInstrumentationProvider.java // public class AppInstrumentationProvider implements InstrumentationProvider { // // private AppClassHandler appClassHandler; // private MethodInstrumenter trackerMethodInstrumenter; // private JVoidConfiguration jvoidConfiguration; // // @Inject // public AppInstrumentationProvider(AppClassHandler appClassHandler, // TrackerMethodInstrumenter trackerMethodInstrumenter, JVoidConfiguration jvoidConfiguration) { // super(); // this.appClassHandler = appClassHandler; // this.trackerMethodInstrumenter = trackerMethodInstrumenter; // this.jvoidConfiguration = jvoidConfiguration; // } // // @Override // public boolean matches(CtClass ctClass) { // JVoidConfiguration config = jvoidConfiguration; // boolean matches = ctClass.getName().startsWith(config.basePackage()); // if (jvoidConfiguration.heuristicExcludeGroovyCallSite()) { // matches = matches && !AppHeuristicHelper.isGroovyCallSite(ctClass); // } // return matches; // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.<ClassHandler> singletonList(appClassHandler); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(trackerMethodInstrumenter); // } // } // // Path: src/main/java/io/jvoid/instrumentation/provider/junit4/JUnitInstrumentationProvider.java // public class JUnitInstrumentationProvider implements InstrumentationProvider { // // private Map<String, MethodInstrumenter> instrumenterMap; // // @Inject // public JUnitInstrumentationProvider(JUnitRunNotifierMethodInstrumenter junitRunNotifierMethodInstrumenter, // RunChildMethodInstrumenter runChildMethodInstrumenter) { // this.instrumenterMap = new HashMap<>(); // this.instrumenterMap.put("org.junit.runner.notification.RunNotifier", junitRunNotifierMethodInstrumenter); // this.instrumenterMap.put("org.junit.runners.BlockJUnit4ClassRunner", runChildMethodInstrumenter); // // Let's be friends with Spring ;) // this.instrumenterMap.put("org.springframework.test.context.junit4.SpringJUnit4ClassRunner", runChildMethodInstrumenter); // } // // @Override // public boolean matches(CtClass ctClass) { // return instrumenterMap.containsKey(ctClass.getName()); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // return Collections.singletonList(instrumenterMap.get(ctMethod.getDeclaringClass().getName())); // } // // } // // Path: src/main/java/io/jvoid/instrumentation/provider/spock/SpockInstrumentationProvider.java // public class SpockInstrumentationProvider implements InstrumentationProvider { // // private MethodInstrumenter runFeatureMethodInstrumenter; // // @Inject // public SpockInstrumentationProvider(RunFeatureMethodInstrumenter runFeatureMethodInstrumenter) { // this.runFeatureMethodInstrumenter = runFeatureMethodInstrumenter; // } // // @Override // public boolean matches(CtClass ctClass) { // return ctClass.getName().contains("org.spockframework.runtime.BaseSpecRunner"); // } // // @Override // public List<ClassHandler> getClassHandlers(CtClass ctClass) { // return Collections.emptyList(); // } // // @Override // public List<MethodInstrumenter> getMethodInstrumenters(CtMethod ctMethod) { // if (ctMethod.getName().equals("runFeature")) { // return Collections.singletonList(runFeatureMethodInstrumenter); // } // return Collections.emptyList(); // } // // } // Path: src/main/java/io/jvoid/instrumentation/provider/ProviderCatalog.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.inject.Inject; import com.google.inject.Singleton; import io.jvoid.instrumentation.provider.api.InstrumentationProvider; import io.jvoid.instrumentation.provider.app.AppInstrumentationProvider; import io.jvoid.instrumentation.provider.junit4.JUnitInstrumentationProvider; import io.jvoid.instrumentation.provider.spock.SpockInstrumentationProvider; import javassist.CtClass; package io.jvoid.instrumentation.provider; /** * Catalog of all the instrumentation providers that the JVoid agent will apply * at runtime for classes instrumentation. * */ @Singleton public class ProviderCatalog { private List<InstrumentationProvider> registeredProviders = new ArrayList<>(); // This is still "hardcoded" providers. Make it discover the providers in // the classpath automatically @Inject public void initializeProviders(AppInstrumentationProvider appInstrumentationProvider,
SpockInstrumentationProvider spockInstrumentationProvider,