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
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired
private JobService jobService;
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every fifteen minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 15 * 60 * 1000L) public void scheduleRetryJobsForExecution() { LOG.info("Fetching failed jobs as per category and submit time priority...");
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every fifteen minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 15 * 60 * 1000L) public void scheduleRetryJobsForExecution() { LOG.info("Fetching failed jobs as per category and submit time priority...");
List<Job> retryableJobs = jobService.fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(10);
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every fifteen minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 15 * 60 * 1000L) public void scheduleRetryJobsForExecution() { LOG.info("Fetching failed jobs as per category and submit time priority..."); List<Job> retryableJobs = jobService.fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); LOG.info("Fetched Jobs Count: "+retryableJobs.size());
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/RetryJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class RetryJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(RetryJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every fifteen minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 15 * 60 * 1000L) public void scheduleRetryJobsForExecution() { LOG.info("Fetching failed jobs as per category and submit time priority..."); List<Job> retryableJobs = jobService.fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); LOG.info("Fetched Jobs Count: "+retryableJobs.size());
Collections.sort(retryableJobs, new CategoryPriorityComparator());
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/framework/controller/BaseController.java
// Path: src/main/java/yourwebproject2/model/dto/UserDTO.java // public class UserDTO { // String email; // String password; // String displayName; // String encryptedPassword; // String iv; // String salt; // int keySize; // int iterations; // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public String getEncryptedPassword() { // return encryptedPassword; // } // // public void setEncryptedPassword(String encryptedPassword) { // this.encryptedPassword = encryptedPassword; // } // // public String getIv() { // return iv; // } // // public void setIv(String iv) { // this.iv = iv; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public int getKeySize() { // return keySize; // } // // public void setKeySize(int keySize) { // this.keySize = keySize; // } // // public int getIterations() { // return iterations; // } // // public void setIterations(int iterations) { // this.iterations = iterations; // } // }
import yourwebproject2.model.dto.UserDTO; import org.apache.commons.lang.Validate; import org.json.JSONObject; import org.springframework.security.crypto.codec.Base64; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Scanner;
package yourwebproject2.framework.controller; /** * All controllers in spring should extend this controller so as to have * centralize control for doing any sort of common functionality. * e.g. extracting data from post request body * * @author : Y Kamesh Rao */ public abstract class BaseController { protected static final String JSON_API_CONTENT_HEADER = "Content-type=application/json"; public String extractPostRequestBody(HttpServletRequest request) throws IOException { if ("POST".equalsIgnoreCase(request.getMethod())) { Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } return ""; } public JSONObject parseJSON(String object) { return new JSONObject(object); }
// Path: src/main/java/yourwebproject2/model/dto/UserDTO.java // public class UserDTO { // String email; // String password; // String displayName; // String encryptedPassword; // String iv; // String salt; // int keySize; // int iterations; // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // public String getEncryptedPassword() { // return encryptedPassword; // } // // public void setEncryptedPassword(String encryptedPassword) { // this.encryptedPassword = encryptedPassword; // } // // public String getIv() { // return iv; // } // // public void setIv(String iv) { // this.iv = iv; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public int getKeySize() { // return keySize; // } // // public void setKeySize(int keySize) { // this.keySize = keySize; // } // // public int getIterations() { // return iterations; // } // // public void setIterations(int iterations) { // this.iterations = iterations; // } // } // Path: src/main/java/yourwebproject2/framework/controller/BaseController.java import yourwebproject2.model.dto.UserDTO; import org.apache.commons.lang.Validate; import org.json.JSONObject; import org.springframework.security.crypto.codec.Base64; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Scanner; package yourwebproject2.framework.controller; /** * All controllers in spring should extend this controller so as to have * centralize control for doing any sort of common functionality. * e.g. extracting data from post request body * * @author : Y Kamesh Rao */ public abstract class BaseController { protected static final String JSON_API_CONTENT_HEADER = "Content-type=application/json"; public String extractPostRequestBody(HttpServletRequest request) throws IOException { if ("POST".equalsIgnoreCase(request.getMethod())) { Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } return ""; } public JSONObject parseJSON(String object) { return new JSONObject(object); }
public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/model/entity/Category.java
// Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java // @MappedSuperclass // public abstract class JPAEntity<T extends Serializable> implements Entity { // protected T id; // protected Date createdAt; // protected Date updatedAt; // // // public JPAEntity() { // createdAt = new Date(); // updatedAt = new Date(); // } // // // /** // * To make XStream deserialization assign values to // * base class fields of createdAt and updatedAt // * // * @return // */ // public Object readResolve() { // if (this.createdAt == null) { // this.createdAt = new Date(); // this.updatedAt = createdAt; // } // // return this; // } // // // @XmlElement(type = Object.class) @Id @GeneratedValue // public T getId() { // return id; // } // // // public void setId(T id) { // this.id = id; // } // // // @JsonIgnore @Temporal(TemporalType.DATE) @Column // public Date getCreatedAt() { // return createdAt; // } // // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // // @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column // public Date getUpdatedAt() { // return updatedAt; // } // // // public void setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // } // }
import yourwebproject2.framework.data.JPAEntity; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull;
package yourwebproject2.model.entity; /** * Category Entity * * Created by Y.Kamesh on 8/2/2015. */ @Entity @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), @Index(name="priority_idx", columnList = "priority"), @Index(name="parentCategory_idx", columnList = "parent_category")})
// Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java // @MappedSuperclass // public abstract class JPAEntity<T extends Serializable> implements Entity { // protected T id; // protected Date createdAt; // protected Date updatedAt; // // // public JPAEntity() { // createdAt = new Date(); // updatedAt = new Date(); // } // // // /** // * To make XStream deserialization assign values to // * base class fields of createdAt and updatedAt // * // * @return // */ // public Object readResolve() { // if (this.createdAt == null) { // this.createdAt = new Date(); // this.updatedAt = createdAt; // } // // return this; // } // // // @XmlElement(type = Object.class) @Id @GeneratedValue // public T getId() { // return id; // } // // // public void setId(T id) { // this.id = id; // } // // // @JsonIgnore @Temporal(TemporalType.DATE) @Column // public Date getCreatedAt() { // return createdAt; // } // // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // // @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column // public Date getUpdatedAt() { // return updatedAt; // } // // // public void setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // } // } // Path: src/main/java/yourwebproject2/model/entity/Category.java import yourwebproject2.framework.data.JPAEntity; import org.hibernate.validator.constraints.NotBlank; import javax.persistence.*; import javax.validation.constraints.NotNull; package yourwebproject2.model.entity; /** * Category Entity * * Created by Y.Kamesh on 8/2/2015. */ @Entity @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), @Index(name="priority_idx", columnList = "priority"), @Index(name="parentCategory_idx", columnList = "parent_category")})
public class Category extends JPAEntity<Long> {
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/tool/CategoryTool.java
// Path: src/main/java/yourwebproject2/model/entity/Category.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="priority_idx", columnList = "priority"), // @Index(name="parentCategory_idx", columnList = "parent_category")}) // public class Category extends JPAEntity<Long> { // private String name; // private Integer priority; // private Category parentCategory; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @NotNull // @Column // public Integer getPriority() { // return priority; // } // // public void setPriority(Integer priority) { // this.priority = priority; // } // // @ManyToOne(fetch = FetchType.EAGER) // public Category getParentCategory() { // return parentCategory; // } // // public void setParentCategory(Category parentCategory) { // this.parentCategory = parentCategory; // } // // @Override // public String toString() { // return "Category{" + // "name='" + name + '\'' + // ", priority=" + priority + // ", parentCategory=" + parentCategory + // '}'; // } // } // // Path: src/main/java/yourwebproject2/service/CategoryService.java // public interface CategoryService extends BaseService<Category, Long> { // /** // * Validates whether the given category already // * exists in the system. // * // * @param categoryName // * // * @return // */ // public boolean isCategoryPresent(String categoryName); // // /** // * Validates whether the given category priority already // * exists in the system. // * // * @param priorityId // * // * @return // */ // public boolean isPriorityPresent(Integer priorityId); // // /** // * Find category by name // * // * @param categoryName // * @return // */ // public Category findByCategoryName(String categoryName) throws NotFoundException; // // /** // * Find sub categories by parent category // * // * @param parentCategory // * @return // */ // public List<Category> findSubCategories(Category parentCategory) throws NotFoundException; // }
import yourwebproject2.model.entity.Category; import yourwebproject2.service.CategoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashMap;
break; case "parent": params.put("parent", p[1]); break; } } Integer priority = null; if(params.containsKey("name") && (params.containsKey("priority") || params.containsKey("parent"))) { if(params.containsKey("priority")) { try { priority = Integer.parseInt(params.get("priority")); } catch (NumberFormatException nfe) { System.out.println("Priority not a number"); System.exit(1); } } } else { printUsage(); } LOG.info("Params: "+params); System.out.println("Params: "+params); ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", "classpath:/config/spring/appContext-repository.xml", "classpath:/config/spring/appContext-service.xml", "classpath:/config/spring/appContext-interceptor.xml"}, true); LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames());
// Path: src/main/java/yourwebproject2/model/entity/Category.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="priority_idx", columnList = "priority"), // @Index(name="parentCategory_idx", columnList = "parent_category")}) // public class Category extends JPAEntity<Long> { // private String name; // private Integer priority; // private Category parentCategory; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @NotNull // @Column // public Integer getPriority() { // return priority; // } // // public void setPriority(Integer priority) { // this.priority = priority; // } // // @ManyToOne(fetch = FetchType.EAGER) // public Category getParentCategory() { // return parentCategory; // } // // public void setParentCategory(Category parentCategory) { // this.parentCategory = parentCategory; // } // // @Override // public String toString() { // return "Category{" + // "name='" + name + '\'' + // ", priority=" + priority + // ", parentCategory=" + parentCategory + // '}'; // } // } // // Path: src/main/java/yourwebproject2/service/CategoryService.java // public interface CategoryService extends BaseService<Category, Long> { // /** // * Validates whether the given category already // * exists in the system. // * // * @param categoryName // * // * @return // */ // public boolean isCategoryPresent(String categoryName); // // /** // * Validates whether the given category priority already // * exists in the system. // * // * @param priorityId // * // * @return // */ // public boolean isPriorityPresent(Integer priorityId); // // /** // * Find category by name // * // * @param categoryName // * @return // */ // public Category findByCategoryName(String categoryName) throws NotFoundException; // // /** // * Find sub categories by parent category // * // * @param parentCategory // * @return // */ // public List<Category> findSubCategories(Category parentCategory) throws NotFoundException; // } // Path: src/main/java/yourwebproject2/core/tool/CategoryTool.java import yourwebproject2.model.entity.Category; import yourwebproject2.service.CategoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashMap; break; case "parent": params.put("parent", p[1]); break; } } Integer priority = null; if(params.containsKey("name") && (params.containsKey("priority") || params.containsKey("parent"))) { if(params.containsKey("priority")) { try { priority = Integer.parseInt(params.get("priority")); } catch (NumberFormatException nfe) { System.out.println("Priority not a number"); System.exit(1); } } } else { printUsage(); } LOG.info("Params: "+params); System.out.println("Params: "+params); ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", "classpath:/config/spring/appContext-repository.xml", "classpath:/config/spring/appContext-service.xml", "classpath:/config/spring/appContext-interceptor.xml"}, true); LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames());
CategoryService categoryService = (CategoryService) ctx.getBean("categoryServiceImpl");
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/tool/CategoryTool.java
// Path: src/main/java/yourwebproject2/model/entity/Category.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="priority_idx", columnList = "priority"), // @Index(name="parentCategory_idx", columnList = "parent_category")}) // public class Category extends JPAEntity<Long> { // private String name; // private Integer priority; // private Category parentCategory; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @NotNull // @Column // public Integer getPriority() { // return priority; // } // // public void setPriority(Integer priority) { // this.priority = priority; // } // // @ManyToOne(fetch = FetchType.EAGER) // public Category getParentCategory() { // return parentCategory; // } // // public void setParentCategory(Category parentCategory) { // this.parentCategory = parentCategory; // } // // @Override // public String toString() { // return "Category{" + // "name='" + name + '\'' + // ", priority=" + priority + // ", parentCategory=" + parentCategory + // '}'; // } // } // // Path: src/main/java/yourwebproject2/service/CategoryService.java // public interface CategoryService extends BaseService<Category, Long> { // /** // * Validates whether the given category already // * exists in the system. // * // * @param categoryName // * // * @return // */ // public boolean isCategoryPresent(String categoryName); // // /** // * Validates whether the given category priority already // * exists in the system. // * // * @param priorityId // * // * @return // */ // public boolean isPriorityPresent(Integer priorityId); // // /** // * Find category by name // * // * @param categoryName // * @return // */ // public Category findByCategoryName(String categoryName) throws NotFoundException; // // /** // * Find sub categories by parent category // * // * @param parentCategory // * @return // */ // public List<Category> findSubCategories(Category parentCategory) throws NotFoundException; // }
import yourwebproject2.model.entity.Category; import yourwebproject2.service.CategoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashMap;
Integer priority = null; if(params.containsKey("name") && (params.containsKey("priority") || params.containsKey("parent"))) { if(params.containsKey("priority")) { try { priority = Integer.parseInt(params.get("priority")); } catch (NumberFormatException nfe) { System.out.println("Priority not a number"); System.exit(1); } } } else { printUsage(); } LOG.info("Params: "+params); System.out.println("Params: "+params); ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", "classpath:/config/spring/appContext-repository.xml", "classpath:/config/spring/appContext-service.xml", "classpath:/config/spring/appContext-interceptor.xml"}, true); LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames()); CategoryService categoryService = (CategoryService) ctx.getBean("categoryServiceImpl"); if(categoryService.isCategoryPresent(params.get("name"))) { System.out.println("Category taken"); System.exit(1); }
// Path: src/main/java/yourwebproject2/model/entity/Category.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="priority_idx", columnList = "priority"), // @Index(name="parentCategory_idx", columnList = "parent_category")}) // public class Category extends JPAEntity<Long> { // private String name; // private Integer priority; // private Category parentCategory; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @NotNull // @Column // public Integer getPriority() { // return priority; // } // // public void setPriority(Integer priority) { // this.priority = priority; // } // // @ManyToOne(fetch = FetchType.EAGER) // public Category getParentCategory() { // return parentCategory; // } // // public void setParentCategory(Category parentCategory) { // this.parentCategory = parentCategory; // } // // @Override // public String toString() { // return "Category{" + // "name='" + name + '\'' + // ", priority=" + priority + // ", parentCategory=" + parentCategory + // '}'; // } // } // // Path: src/main/java/yourwebproject2/service/CategoryService.java // public interface CategoryService extends BaseService<Category, Long> { // /** // * Validates whether the given category already // * exists in the system. // * // * @param categoryName // * // * @return // */ // public boolean isCategoryPresent(String categoryName); // // /** // * Validates whether the given category priority already // * exists in the system. // * // * @param priorityId // * // * @return // */ // public boolean isPriorityPresent(Integer priorityId); // // /** // * Find category by name // * // * @param categoryName // * @return // */ // public Category findByCategoryName(String categoryName) throws NotFoundException; // // /** // * Find sub categories by parent category // * // * @param parentCategory // * @return // */ // public List<Category> findSubCategories(Category parentCategory) throws NotFoundException; // } // Path: src/main/java/yourwebproject2/core/tool/CategoryTool.java import yourwebproject2.model.entity.Category; import yourwebproject2.service.CategoryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashMap; Integer priority = null; if(params.containsKey("name") && (params.containsKey("priority") || params.containsKey("parent"))) { if(params.containsKey("priority")) { try { priority = Integer.parseInt(params.get("priority")); } catch (NumberFormatException nfe) { System.out.println("Priority not a number"); System.exit(1); } } } else { printUsage(); } LOG.info("Params: "+params); System.out.println("Params: "+params); ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:/config/spring/appContext-jdbc.xml", "classpath:/config/spring/appContext-repository.xml", "classpath:/config/spring/appContext-service.xml", "classpath:/config/spring/appContext-interceptor.xml"}, true); LOG.info("Loaded the context: " + ctx.getBeanDefinitionNames()); CategoryService categoryService = (CategoryService) ctx.getBean("categoryServiceImpl"); if(categoryService.isCategoryPresent(params.get("name"))) { System.out.println("Category taken"); System.exit(1); }
Category parentCategory = null;
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired
private JobService jobService;
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every five minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 5 * 60 * 1000L) public void scheduleNewJobsForExecution() { LOG.info("Fetching new jobs as per category and submit time priority...");
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every five minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 5 * 60 * 1000L) public void scheduleNewJobsForExecution() { LOG.info("Fetching new jobs as per category and submit time priority...");
List<Job> newJobs = jobService.fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(10);
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // }
import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;
package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every five minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 5 * 60 * 1000L) public void scheduleNewJobsForExecution() { LOG.info("Fetching new jobs as per category and submit time priority..."); List<Job> newJobs = jobService.fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); LOG.info("Fetched Jobs Count: "+newJobs.size());
// Path: src/main/java/yourwebproject2/model/entity/Job.java // @Entity // @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true), // @Index(name="status_idx", columnList = "status"), // @Index(name="category_idx", columnList = "category")}) // public class Job extends JPAEntity<Long> { // public enum Status { // NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL // } // // private String name; // private String metadataJson; // private String callbackUrl; // private Date submitTime; // private Status status; // private Date scheduledTime; // private Date completionTime; // private Integer retryCount; // private Category category; // // @NotNull @NotBlank // @Column // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Column // public String getCallbackUrl() { // return callbackUrl; // } // // public void setCallbackUrl(String callbackUrl) { // this.callbackUrl = callbackUrl; // } // // @Column // public String getMetadataJson() { // return metadataJson; // } // // public void setMetadataJson(String metadataJson) { // this.metadataJson = metadataJson; // } // // @NotNull // @Column // public Date getSubmitTime() { // return submitTime; // } // // public void setSubmitTime(Date submitTime) { // this.submitTime = submitTime; // } // // @OneToOne(fetch = FetchType.EAGER) // public Category getCategory() { // return category; // } // // public void setCategory(Category category) { // this.category = category; // } // // @NotNull // @Column // public Status getStatus() { // return status; // } // // public void setStatus(Status status) { // this.status = status; // } // // @Column // public Date getScheduledTime() { // return scheduledTime; // } // // public void setScheduledTime(Date scheduledTime) { // this.scheduledTime = scheduledTime; // } // // @Column // public Date getCompletionTime() { // return completionTime; // } // // public void setCompletionTime(Date completionTime) { // this.completionTime = completionTime; // } // // @Column // public Integer getRetryCount() { // return retryCount; // } // // public void setRetryCount(Integer retryCount) { // this.retryCount = retryCount; // } // // @Override // public String toString() { // return "Job{" + // "name='" + name + '\'' + // ", metadataJson='" + metadataJson + '\'' + // ", callbackUrl='" + callbackUrl + '\'' + // ", submitTime=" + submitTime + // ", status=" + status + // ", scheduledTime=" + scheduledTime + // ", completionTime=" + completionTime + // ", retryCount=" + retryCount + // ", category=" + category + // '}'; // } // } // // Path: src/main/java/yourwebproject2/model/entity/helper/CategoryPriorityComparator.java // public class CategoryPriorityComparator implements Comparator<Job> { // // /** // * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as // * the first argument is less than, equal to, or greater than the second. // * // * @param o1 // * @param o2 // * @return // */ // @Override // public int compare(Job o1, Job o2) { // // ordering of priority is 1... 2... 3.... N...., where 1 is higher // if(o1.getCategory().getPriority() > o2.getCategory().getPriority()) { // return 1; // } else if(o1.getCategory().getPriority() < o2.getCategory().getPriority()) { // return -1; // } else { // return 0; // } // } // } // // Path: src/main/java/yourwebproject2/service/JobService.java // public interface JobService extends BaseService<Job, Long> { // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // // /** // * // * @param count // * @return // */ // public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count); // } // Path: src/main/java/yourwebproject2/core/NewJobSchedulingWorker.java import yourwebproject2.model.entity.Job; import yourwebproject2.model.entity.helper.CategoryPriorityComparator; import yourwebproject2.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; package yourwebproject2.core; /** * Created by Y.Kamesh on 8/5/2015. */ public class NewJobSchedulingWorker extends AbstractJobSchedulingWorker { private static Logger LOG = LoggerFactory.getLogger(NewJobSchedulingWorker.class); @Autowired private JobService jobService; private ExecutorService executorService = Executors.newFixedThreadPool(50); /** * Runs every five minutes. */ @Scheduled(initialDelay = 5000L, fixedRate = 5 * 60 * 1000L) public void scheduleNewJobsForExecution() { LOG.info("Fetching new jobs as per category and submit time priority..."); List<Job> newJobs = jobService.fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(10); LOG.info("Fetched Jobs Count: "+newJobs.size());
Collections.sort(newJobs, new CategoryPriorityComparator());
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/unusedspringsecurity/UserRole.java
// Path: src/main/java/yourwebproject2/model/entity/User.java // @Entity // @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true), // @Index(name="displayName_idx", columnList = "display_name") }) // public class User extends JPAEntity<Long> implements Serializable { // public enum Role { // USER, // ADMIN // } // // private String email; // private @JsonIgnore String password; // private boolean enabled; // private Role role; // private String displayName; // // private @JsonIgnore Integer loginCount; // private Date currentLoginAt; // private Date lastLoginAt; // private @JsonIgnore String currentLoginIp; // private @JsonIgnore String lastLoginIp; // // private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // // @Column @Email @NotNull @NotBlank // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // @JsonIgnore @Column(nullable = false, length = 60) // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Column(nullable = false) // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // @Column(nullable = false) // public Role getRole() { // return this.role; // } // // public void setRole(Role role) { // this.role = role; // } // // @Column(name="display_name") // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // @JsonIgnore @Column // public Integer getLoginCount() { // return loginCount; // } // // public void setLoginCount(Integer loginCount) { // this.loginCount = loginCount; // } // // @Column // public Date getCurrentLoginAt() { // return currentLoginAt; // } // // public void setCurrentLoginAt(Date currentLoginAt) { // this.currentLoginAt = currentLoginAt; // } // // @Column // public Date getLastLoginAt() { // return lastLoginAt; // } // // public void setLastLoginAt(Date lastLoginAt) { // this.lastLoginAt = lastLoginAt; // } // // @JsonIgnore @Column // public String getCurrentLoginIp() { // return currentLoginIp; // } // // public void setCurrentLoginIp(String currentLoginIp) { // this.currentLoginIp = currentLoginIp; // } // // @JsonIgnore @Column // public String getLastLoginIp() { // return lastLoginIp; // } // // public void setLastLoginIp(String lastLoginIp) { // this.lastLoginIp = lastLoginIp; // } // // /** // * Method to create the hash of the password before storing // * // * @param pass // * // * @return SHA hash digest of the password // */ // public static synchronized String hashPassword(String pass) { // return passwordEncoder.encode(pass); // } // // public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) { // return passwordEncoder.matches(rawPass, encodedPass); // } // // @Override // public String toString() { // return "User{" + // "email='" + email + '\'' + // ", password='" + password + '\'' + // ", enabled=" + enabled + // ", role=" + role + // ", displayName='" + displayName + '\'' + // ", loginCount=" + loginCount + // ", currentLoginAt=" + currentLoginAt + // ", lastLoginAt=" + lastLoginAt + // ", currentLoginIp='" + currentLoginIp + '\'' + // ", lastLoginIp='" + lastLoginIp + '\'' + // '}'; // } // }
import yourwebproject2.model.entity.User; import javax.persistence.*; import java.io.Serializable;
package yourwebproject2.unusedspringsecurity; /** * @author: kameshr */ //@Entity //@Table(indexes = { @Index(name="email_fk_idx", columnList = "email", unique = true) }) public class UserRole implements Serializable { private Integer userRoleId;
// Path: src/main/java/yourwebproject2/model/entity/User.java // @Entity // @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true), // @Index(name="displayName_idx", columnList = "display_name") }) // public class User extends JPAEntity<Long> implements Serializable { // public enum Role { // USER, // ADMIN // } // // private String email; // private @JsonIgnore String password; // private boolean enabled; // private Role role; // private String displayName; // // private @JsonIgnore Integer loginCount; // private Date currentLoginAt; // private Date lastLoginAt; // private @JsonIgnore String currentLoginIp; // private @JsonIgnore String lastLoginIp; // // private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // // @Column @Email @NotNull @NotBlank // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // @JsonIgnore @Column(nullable = false, length = 60) // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Column(nullable = false) // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // @Column(nullable = false) // public Role getRole() { // return this.role; // } // // public void setRole(Role role) { // this.role = role; // } // // @Column(name="display_name") // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // // @JsonIgnore @Column // public Integer getLoginCount() { // return loginCount; // } // // public void setLoginCount(Integer loginCount) { // this.loginCount = loginCount; // } // // @Column // public Date getCurrentLoginAt() { // return currentLoginAt; // } // // public void setCurrentLoginAt(Date currentLoginAt) { // this.currentLoginAt = currentLoginAt; // } // // @Column // public Date getLastLoginAt() { // return lastLoginAt; // } // // public void setLastLoginAt(Date lastLoginAt) { // this.lastLoginAt = lastLoginAt; // } // // @JsonIgnore @Column // public String getCurrentLoginIp() { // return currentLoginIp; // } // // public void setCurrentLoginIp(String currentLoginIp) { // this.currentLoginIp = currentLoginIp; // } // // @JsonIgnore @Column // public String getLastLoginIp() { // return lastLoginIp; // } // // public void setLastLoginIp(String lastLoginIp) { // this.lastLoginIp = lastLoginIp; // } // // /** // * Method to create the hash of the password before storing // * // * @param pass // * // * @return SHA hash digest of the password // */ // public static synchronized String hashPassword(String pass) { // return passwordEncoder.encode(pass); // } // // public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) { // return passwordEncoder.matches(rawPass, encodedPass); // } // // @Override // public String toString() { // return "User{" + // "email='" + email + '\'' + // ", password='" + password + '\'' + // ", enabled=" + enabled + // ", role=" + role + // ", displayName='" + displayName + '\'' + // ", loginCount=" + loginCount + // ", currentLoginAt=" + currentLoginAt + // ", lastLoginAt=" + lastLoginAt + // ", currentLoginIp='" + currentLoginIp + '\'' + // ", lastLoginIp='" + lastLoginIp + '\'' + // '}'; // } // } // Path: src/main/java/yourwebproject2/unusedspringsecurity/UserRole.java import yourwebproject2.model.entity.User; import javax.persistence.*; import java.io.Serializable; package yourwebproject2.unusedspringsecurity; /** * @author: kameshr */ //@Entity //@Table(indexes = { @Index(name="email_fk_idx", columnList = "email", unique = true) }) public class UserRole implements Serializable { private Integer userRoleId;
private User user;
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/model/entity/User.java
// Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java // @MappedSuperclass // public abstract class JPAEntity<T extends Serializable> implements Entity { // protected T id; // protected Date createdAt; // protected Date updatedAt; // // // public JPAEntity() { // createdAt = new Date(); // updatedAt = new Date(); // } // // // /** // * To make XStream deserialization assign values to // * base class fields of createdAt and updatedAt // * // * @return // */ // public Object readResolve() { // if (this.createdAt == null) { // this.createdAt = new Date(); // this.updatedAt = createdAt; // } // // return this; // } // // // @XmlElement(type = Object.class) @Id @GeneratedValue // public T getId() { // return id; // } // // // public void setId(T id) { // this.id = id; // } // // // @JsonIgnore @Temporal(TemporalType.DATE) @Column // public Date getCreatedAt() { // return createdAt; // } // // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // // @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column // public Date getUpdatedAt() { // return updatedAt; // } // // // public void setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import yourwebproject2.framework.data.JPAEntity; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date;
package yourwebproject2.model.entity; /** * Created by Y.Kamesh on 10/9/2015. */ @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true), @Index(name="displayName_idx", columnList = "display_name") })
// Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java // @MappedSuperclass // public abstract class JPAEntity<T extends Serializable> implements Entity { // protected T id; // protected Date createdAt; // protected Date updatedAt; // // // public JPAEntity() { // createdAt = new Date(); // updatedAt = new Date(); // } // // // /** // * To make XStream deserialization assign values to // * base class fields of createdAt and updatedAt // * // * @return // */ // public Object readResolve() { // if (this.createdAt == null) { // this.createdAt = new Date(); // this.updatedAt = createdAt; // } // // return this; // } // // // @XmlElement(type = Object.class) @Id @GeneratedValue // public T getId() { // return id; // } // // // public void setId(T id) { // this.id = id; // } // // // @JsonIgnore @Temporal(TemporalType.DATE) @Column // public Date getCreatedAt() { // return createdAt; // } // // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // // @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column // public Date getUpdatedAt() { // return updatedAt; // } // // // public void setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // } // } // Path: src/main/java/yourwebproject2/model/entity/User.java import com.fasterxml.jackson.annotation.JsonIgnore; import yourwebproject2.framework.data.JPAEntity; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; package yourwebproject2.model.entity; /** * Created by Y.Kamesh on 10/9/2015. */ @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true), @Index(name="displayName_idx", columnList = "display_name") })
public class User extends JPAEntity<Long> implements Serializable {
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/interceptor/WebAppExceptionAdvice.java
// Path: src/main/java/yourwebproject2/framework/api/APIResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class APIResponse { // public static final String API_RESPONSE = "apiResponse"; // Object result; // String time; // long code; // // public static class ExceptionAPIResponse extends APIResponse { // Object details; // // public Object getDetails() { // return details; // } // // public void setDetails(Object details) { // this.details = details; // } // } // // public Object getResult() { // return result; // } // // public void setResult(Object result) { // this.result = result; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public long getCode() { // return code; // } // // public void setCode(long code) { // this.code = code; // } // // public static APIResponse toOkResponse(Object data) { // return toAPIResponse(data, 200); // } // // public static APIResponse toErrorResponse(Object data) { // return toAPIResponse(data, 2001); // } // // public static ExceptionAPIResponse toExceptionResponse(String result, Object details) { // ExceptionAPIResponse response = new ExceptionAPIResponse(); // response.setResult(result); // response.setDetails(details); // response.setCode(2001); // return response; // } // // public APIResponse withModelAndView(ModelAndView modelAndView) { // modelAndView.addObject(API_RESPONSE, this); // return this; // } // // public static APIResponse toAPIResponse(Object data, long code) { // APIResponse response = new APIResponse(); // response.setResult(data); // response.setCode(code); // return response; // } // }
import yourwebproject2.framework.api.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody;
package yourwebproject2.interceptor; /** * Exception Handler Controller Advice to catch all controller exceptions and respond gracefully to * the caller * * Created by Y.Kamesh on 8/2/2015. */ @ControllerAdvice public class WebAppExceptionAdvice { private static Logger LOG = LoggerFactory.getLogger(WebAppExceptionAdvice.class); @ExceptionHandler(Exception.class) @ResponseBody
// Path: src/main/java/yourwebproject2/framework/api/APIResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class APIResponse { // public static final String API_RESPONSE = "apiResponse"; // Object result; // String time; // long code; // // public static class ExceptionAPIResponse extends APIResponse { // Object details; // // public Object getDetails() { // return details; // } // // public void setDetails(Object details) { // this.details = details; // } // } // // public Object getResult() { // return result; // } // // public void setResult(Object result) { // this.result = result; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public long getCode() { // return code; // } // // public void setCode(long code) { // this.code = code; // } // // public static APIResponse toOkResponse(Object data) { // return toAPIResponse(data, 200); // } // // public static APIResponse toErrorResponse(Object data) { // return toAPIResponse(data, 2001); // } // // public static ExceptionAPIResponse toExceptionResponse(String result, Object details) { // ExceptionAPIResponse response = new ExceptionAPIResponse(); // response.setResult(result); // response.setDetails(details); // response.setCode(2001); // return response; // } // // public APIResponse withModelAndView(ModelAndView modelAndView) { // modelAndView.addObject(API_RESPONSE, this); // return this; // } // // public static APIResponse toAPIResponse(Object data, long code) { // APIResponse response = new APIResponse(); // response.setResult(data); // response.setCode(code); // return response; // } // } // Path: src/main/java/yourwebproject2/interceptor/WebAppExceptionAdvice.java import yourwebproject2.framework.api.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; package yourwebproject2.interceptor; /** * Exception Handler Controller Advice to catch all controller exceptions and respond gracefully to * the caller * * Created by Y.Kamesh on 8/2/2015. */ @ControllerAdvice public class WebAppExceptionAdvice { private static Logger LOG = LoggerFactory.getLogger(WebAppExceptionAdvice.class); @ExceptionHandler(Exception.class) @ResponseBody
public APIResponse handleAnyException(Exception e) {
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/BitSetTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java // public class BitSet implements Offheap { // // public static class Builder { // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public Builder(long bitCount, int paddingBytes) { // this.usableBytes = memoryOffset(bitCount) + Sizes.LONG_SIZE; // this.pointer = MemoryAllocator.allocateAndZero(usableBytes + paddingBytes); // this.directBuffer = pointer.directBuffer(); // } // // public void set(long bitIndex, boolean value) { // int offset = memoryOffset(bitIndex); // // if (value) { // //Set // directBuffer.putLong(offset, directBuffer.getLong(offset) | (1L << bitIndex)); // } else { // //Clear // directBuffer.putLong(offset, directBuffer.getLong(offset) & ~(1L << bitIndex)); // } // } // // public BitSet build() { // return new BitSet(pointer, usableBytes); // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // } // // private static final int ADDRESS_BITS_PER_WORD = 6; // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public BitSet(MemoryPointer pointer, int usableBytes) { // this.pointer = pointer; // this.directBuffer = pointer.directBuffer(); // this.usableBytes = usableBytes; // } // // public boolean get(long index) { // int offset = memoryOffset(index); // long currentValue = directBuffer.getLong(offset); // return (currentValue & (1L << index)) != 0; // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // // @Override // public MemoryPointer memory() { // return pointer; // } // // private static int memoryOffset(long bitIndex) { // return (int) (bitIndex >> ADDRESS_BITS_PER_WORD) * Sizes.LONG_SIZE; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.offheap.BitSet; import com.jordanwilliams.heftydb.util.Sizes; import org.junit.Assert; import org.junit.Test; import java.util.Random;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class BitSetTest { @Test public void getSetTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java // public class BitSet implements Offheap { // // public static class Builder { // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public Builder(long bitCount, int paddingBytes) { // this.usableBytes = memoryOffset(bitCount) + Sizes.LONG_SIZE; // this.pointer = MemoryAllocator.allocateAndZero(usableBytes + paddingBytes); // this.directBuffer = pointer.directBuffer(); // } // // public void set(long bitIndex, boolean value) { // int offset = memoryOffset(bitIndex); // // if (value) { // //Set // directBuffer.putLong(offset, directBuffer.getLong(offset) | (1L << bitIndex)); // } else { // //Clear // directBuffer.putLong(offset, directBuffer.getLong(offset) & ~(1L << bitIndex)); // } // } // // public BitSet build() { // return new BitSet(pointer, usableBytes); // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // } // // private static final int ADDRESS_BITS_PER_WORD = 6; // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public BitSet(MemoryPointer pointer, int usableBytes) { // this.pointer = pointer; // this.directBuffer = pointer.directBuffer(); // this.usableBytes = usableBytes; // } // // public boolean get(long index) { // int offset = memoryOffset(index); // long currentValue = directBuffer.getLong(offset); // return (currentValue & (1L << index)) != 0; // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // // @Override // public MemoryPointer memory() { // return pointer; // } // // private static int memoryOffset(long bitIndex) { // return (int) (bitIndex >> ADDRESS_BITS_PER_WORD) * Sizes.LONG_SIZE; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/BitSetTest.java import com.jordanwilliams.heftydb.offheap.BitSet; import com.jordanwilliams.heftydb.util.Sizes; import org.junit.Assert; import org.junit.Test; import java.util.Random; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class BitSetTest { @Test public void getSetTest() {
BitSet.Builder testSetBuilder = new BitSet.Builder(256, Sizes.INT_SIZE);
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/BitSetTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java // public class BitSet implements Offheap { // // public static class Builder { // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public Builder(long bitCount, int paddingBytes) { // this.usableBytes = memoryOffset(bitCount) + Sizes.LONG_SIZE; // this.pointer = MemoryAllocator.allocateAndZero(usableBytes + paddingBytes); // this.directBuffer = pointer.directBuffer(); // } // // public void set(long bitIndex, boolean value) { // int offset = memoryOffset(bitIndex); // // if (value) { // //Set // directBuffer.putLong(offset, directBuffer.getLong(offset) | (1L << bitIndex)); // } else { // //Clear // directBuffer.putLong(offset, directBuffer.getLong(offset) & ~(1L << bitIndex)); // } // } // // public BitSet build() { // return new BitSet(pointer, usableBytes); // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // } // // private static final int ADDRESS_BITS_PER_WORD = 6; // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public BitSet(MemoryPointer pointer, int usableBytes) { // this.pointer = pointer; // this.directBuffer = pointer.directBuffer(); // this.usableBytes = usableBytes; // } // // public boolean get(long index) { // int offset = memoryOffset(index); // long currentValue = directBuffer.getLong(offset); // return (currentValue & (1L << index)) != 0; // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // // @Override // public MemoryPointer memory() { // return pointer; // } // // private static int memoryOffset(long bitIndex) { // return (int) (bitIndex >> ADDRESS_BITS_PER_WORD) * Sizes.LONG_SIZE; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.offheap.BitSet; import com.jordanwilliams.heftydb.util.Sizes; import org.junit.Assert; import org.junit.Test; import java.util.Random;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class BitSetTest { @Test public void getSetTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java // public class BitSet implements Offheap { // // public static class Builder { // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public Builder(long bitCount, int paddingBytes) { // this.usableBytes = memoryOffset(bitCount) + Sizes.LONG_SIZE; // this.pointer = MemoryAllocator.allocateAndZero(usableBytes + paddingBytes); // this.directBuffer = pointer.directBuffer(); // } // // public void set(long bitIndex, boolean value) { // int offset = memoryOffset(bitIndex); // // if (value) { // //Set // directBuffer.putLong(offset, directBuffer.getLong(offset) | (1L << bitIndex)); // } else { // //Clear // directBuffer.putLong(offset, directBuffer.getLong(offset) & ~(1L << bitIndex)); // } // } // // public BitSet build() { // return new BitSet(pointer, usableBytes); // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // } // // private static final int ADDRESS_BITS_PER_WORD = 6; // // private final MemoryPointer pointer; // private final ByteBuffer directBuffer; // private final int usableBytes; // // public BitSet(MemoryPointer pointer, int usableBytes) { // this.pointer = pointer; // this.directBuffer = pointer.directBuffer(); // this.usableBytes = usableBytes; // } // // public boolean get(long index) { // int offset = memoryOffset(index); // long currentValue = directBuffer.getLong(offset); // return (currentValue & (1L << index)) != 0; // } // // public int usableBytes() { // return usableBytes; // } // // public long bitCount() { // return usableBytes * 8; // } // // @Override // public MemoryPointer memory() { // return pointer; // } // // private static int memoryOffset(long bitIndex) { // return (int) (bitIndex >> ADDRESS_BITS_PER_WORD) * Sizes.LONG_SIZE; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/BitSetTest.java import com.jordanwilliams.heftydb.offheap.BitSet; import com.jordanwilliams.heftydb.util.Sizes; import org.junit.Assert; import org.junit.Test; import java.util.Random; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class BitSetTest { @Test public void getSetTest() {
BitSet.Builder testSetBuilder = new BitSet.Builder(256, Sizes.INT_SIZE);
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/db/Config.java
// Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java // public enum CompactionStrategies implements CompactionStrategy { // // SIZE_TIERED_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new SizeTieredCompactionPlanner(tables); // } // }, // // NULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new CompactionPlanner() { // @Override // public CompactionPlan planCompaction() { // return new CompactionPlan(Collections.<CompactionTask>emptyList()); // } // // @Override // public boolean needsCompaction() { // return false; // } // }; // } // }, // // FULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new FullCompactionPlanner(tables); // } // }; // // @Override // public abstract CompactionPlanner initialize(CompactionTables tables); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategy.java // public interface CompactionStrategy { // // public CompactionPlanner initialize(CompactionTables tables); // }
import com.jordanwilliams.heftydb.compact.CompactionStrategies; import com.jordanwilliams.heftydb.compact.CompactionStrategy; import java.nio.file.Path;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * Encapsulates all of the tunable values for a database instance. */ public class Config { public static class Builder { //Default config values
// Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java // public enum CompactionStrategies implements CompactionStrategy { // // SIZE_TIERED_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new SizeTieredCompactionPlanner(tables); // } // }, // // NULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new CompactionPlanner() { // @Override // public CompactionPlan planCompaction() { // return new CompactionPlan(Collections.<CompactionTask>emptyList()); // } // // @Override // public boolean needsCompaction() { // return false; // } // }; // } // }, // // FULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new FullCompactionPlanner(tables); // } // }; // // @Override // public abstract CompactionPlanner initialize(CompactionTables tables); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategy.java // public interface CompactionStrategy { // // public CompactionPlanner initialize(CompactionTables tables); // } // Path: src/main/java/com/jordanwilliams/heftydb/db/Config.java import com.jordanwilliams.heftydb.compact.CompactionStrategies; import com.jordanwilliams.heftydb.compact.CompactionStrategy; import java.nio.file.Path; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * Encapsulates all of the tunable values for a database instance. */ public class Config { public static class Builder { //Default config values
private CompactionStrategy compactionStrategy = CompactionStrategies.SIZE_TIERED_COMPACTION_STRATEGY;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/db/Config.java
// Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java // public enum CompactionStrategies implements CompactionStrategy { // // SIZE_TIERED_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new SizeTieredCompactionPlanner(tables); // } // }, // // NULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new CompactionPlanner() { // @Override // public CompactionPlan planCompaction() { // return new CompactionPlan(Collections.<CompactionTask>emptyList()); // } // // @Override // public boolean needsCompaction() { // return false; // } // }; // } // }, // // FULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new FullCompactionPlanner(tables); // } // }; // // @Override // public abstract CompactionPlanner initialize(CompactionTables tables); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategy.java // public interface CompactionStrategy { // // public CompactionPlanner initialize(CompactionTables tables); // }
import com.jordanwilliams.heftydb.compact.CompactionStrategies; import com.jordanwilliams.heftydb.compact.CompactionStrategy; import java.nio.file.Path;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * Encapsulates all of the tunable values for a database instance. */ public class Config { public static class Builder { //Default config values
// Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java // public enum CompactionStrategies implements CompactionStrategy { // // SIZE_TIERED_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new SizeTieredCompactionPlanner(tables); // } // }, // // NULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new CompactionPlanner() { // @Override // public CompactionPlan planCompaction() { // return new CompactionPlan(Collections.<CompactionTask>emptyList()); // } // // @Override // public boolean needsCompaction() { // return false; // } // }; // } // }, // // FULL_COMPACTION_STRATEGY { // @Override // public CompactionPlanner initialize(CompactionTables tables) { // return new FullCompactionPlanner(tables); // } // }; // // @Override // public abstract CompactionPlanner initialize(CompactionTables tables); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategy.java // public interface CompactionStrategy { // // public CompactionPlanner initialize(CompactionTables tables); // } // Path: src/main/java/com/jordanwilliams/heftydb/db/Config.java import com.jordanwilliams.heftydb.compact.CompactionStrategies; import com.jordanwilliams.heftydb.compact.CompactionStrategy; import java.nio.file.Path; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * Encapsulates all of the tunable values for a database instance. */ public class Config { public static class Builder { //Default config values
private CompactionStrategy compactionStrategy = CompactionStrategies.SIZE_TIERED_COMPACTION_STRATEGY;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/data/Tuple.java
// Path: src/main/java/com/jordanwilliams/heftydb/util/Serializer.java // public interface Serializer<V> { // // public int size(V item); // // public void serialize(V item, ByteBuffer buffer); // // public V deserialize(ByteBuffer buffer); // // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.util.Serializer; import com.jordanwilliams.heftydb.util.Sizes; import java.nio.ByteBuffer;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.data; /** * A wrapper class that groups a Key and Value together. */ public class Tuple implements Comparable<Tuple> { public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { @Override public int size(Tuple tuple) { int size = 0; //Key
// Path: src/main/java/com/jordanwilliams/heftydb/util/Serializer.java // public interface Serializer<V> { // // public int size(V item); // // public void serialize(V item, ByteBuffer buffer); // // public V deserialize(ByteBuffer buffer); // // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java import com.jordanwilliams.heftydb.util.Serializer; import com.jordanwilliams.heftydb.util.Sizes; import java.nio.ByteBuffer; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.data; /** * A wrapper class that groups a Key and Value together. */ public class Tuple implements Comparable<Tuple> { public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { @Override public int size(Tuple tuple) { int size = 0; //Key
size += Sizes.INT_SIZE;
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/UnsafeAllocatorTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // }
import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import org.junit.Assert; import org.junit.Test;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class UnsafeAllocatorTest { @Test public void allocateFreeTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/offheap/UnsafeAllocatorTest.java import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import org.junit.Assert; import org.junit.Test; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.offheap; public class UnsafeAllocatorTest { @Test public void allocateFreeTest() {
UnsafeAllocator unsafeAllocator = new UnsafeAllocator();
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/read/MergingIteratorTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/read/MergingIterator.java // public class MergingIterator<T extends Comparable> implements CloseableIterator<T> { // // private static class ComparableIterator<T extends Comparable> implements PeekableIterator<T>, // Comparable<ComparableIterator<T>> { // // private final CloseableIterator<T> delegate; // private T current; // // private ComparableIterator(CloseableIterator<T> delegate) { // this.delegate = delegate; // // if (delegate.hasNext()) { // current = delegate.next(); // } // } // // @Override // public T current() { // return current; // } // // @Override // public boolean advance() { // if (delegate.hasNext()) { // current = delegate.next(); // return true; // } // // return false; // } // // public void close() throws IOException { // delegate.close(); // } // // @Override // public int compareTo(ComparableIterator<T> other) { // return current.compareTo(other.current); // } // } // // private final Queue<T> next = new LinkedList<T>(); // private final PriorityQueue<ComparableIterator<T>> iteratorHeap; // // public MergingIterator(List<CloseableIterator<T>> iterators) { // this.iteratorHeap = new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // public MergingIterator(CloseableIterator<T>... iterators) { // this(Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, CloseableIterator<T>... iterators) { // this(descending, Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, List<CloseableIterator<T>> iterators) { // this.iteratorHeap = descending ? new PriorityQueue<ComparableIterator<T>>(iterators.size(), // Collections.reverseOrder()) : new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // @Override // public boolean hasNext() { // if (!next.isEmpty()) { // return true; // } // // if (iteratorHeap.isEmpty()) { // return false; // } // // ComparableIterator<T> nextIterator = iteratorHeap.poll(); // T nextCandidate = nextIterator.current(); // // if (nextCandidate != null) { // next.add(nextCandidate); // } // // if (nextIterator.advance()) { // iteratorHeap.add(nextIterator); // } // // if (next.isEmpty()) { // return false; // } // // return true; // } // // @Override // public T next() { // if (next.isEmpty()) { // if (!hasNext()) { // throw new NoSuchElementException(); // } // } // // return next.poll(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void buildIteratorHeap(List<CloseableIterator<T>> iteratorList) { // for (CloseableIterator<T> iterator : iteratorList) { // if (iterator.hasNext()) { // iteratorHeap.add(new ComparableIterator<T>(iterator)); // } // } // } // // @Override // public void close() throws IOException { // for (ComparableIterator<T> comparableIterator : iteratorHeap) { // comparableIterator.close(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // }
import com.google.common.primitives.Ints; import com.jordanwilliams.heftydb.read.MergingIterator; import com.jordanwilliams.heftydb.util.CloseableIterator; import org.junit.Assert; import org.junit.Test; import java.util.Iterator;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.read; public class MergingIteratorTest { private static final int[] ARRAY1 = {1, 2, 3, 4, 5, 6}; private static final int[] ARRAY2 = {1, 4, 5, 7, 9, 10}; private static final int[] MERGED_ARRAY = {1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 9, 10}; @Test public void mergeTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/read/MergingIterator.java // public class MergingIterator<T extends Comparable> implements CloseableIterator<T> { // // private static class ComparableIterator<T extends Comparable> implements PeekableIterator<T>, // Comparable<ComparableIterator<T>> { // // private final CloseableIterator<T> delegate; // private T current; // // private ComparableIterator(CloseableIterator<T> delegate) { // this.delegate = delegate; // // if (delegate.hasNext()) { // current = delegate.next(); // } // } // // @Override // public T current() { // return current; // } // // @Override // public boolean advance() { // if (delegate.hasNext()) { // current = delegate.next(); // return true; // } // // return false; // } // // public void close() throws IOException { // delegate.close(); // } // // @Override // public int compareTo(ComparableIterator<T> other) { // return current.compareTo(other.current); // } // } // // private final Queue<T> next = new LinkedList<T>(); // private final PriorityQueue<ComparableIterator<T>> iteratorHeap; // // public MergingIterator(List<CloseableIterator<T>> iterators) { // this.iteratorHeap = new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // public MergingIterator(CloseableIterator<T>... iterators) { // this(Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, CloseableIterator<T>... iterators) { // this(descending, Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, List<CloseableIterator<T>> iterators) { // this.iteratorHeap = descending ? new PriorityQueue<ComparableIterator<T>>(iterators.size(), // Collections.reverseOrder()) : new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // @Override // public boolean hasNext() { // if (!next.isEmpty()) { // return true; // } // // if (iteratorHeap.isEmpty()) { // return false; // } // // ComparableIterator<T> nextIterator = iteratorHeap.poll(); // T nextCandidate = nextIterator.current(); // // if (nextCandidate != null) { // next.add(nextCandidate); // } // // if (nextIterator.advance()) { // iteratorHeap.add(nextIterator); // } // // if (next.isEmpty()) { // return false; // } // // return true; // } // // @Override // public T next() { // if (next.isEmpty()) { // if (!hasNext()) { // throw new NoSuchElementException(); // } // } // // return next.poll(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void buildIteratorHeap(List<CloseableIterator<T>> iteratorList) { // for (CloseableIterator<T> iterator : iteratorList) { // if (iterator.hasNext()) { // iteratorHeap.add(new ComparableIterator<T>(iterator)); // } // } // } // // @Override // public void close() throws IOException { // for (ComparableIterator<T> comparableIterator : iteratorHeap) { // comparableIterator.close(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/read/MergingIteratorTest.java import com.google.common.primitives.Ints; import com.jordanwilliams.heftydb.read.MergingIterator; import com.jordanwilliams.heftydb.util.CloseableIterator; import org.junit.Assert; import org.junit.Test; import java.util.Iterator; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.read; public class MergingIteratorTest { private static final int[] ARRAY1 = {1, 2, 3, 4, 5, 6}; private static final int[] ARRAY2 = {1, 4, 5, 7, 9, 10}; private static final int[] MERGED_ARRAY = {1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 9, 10}; @Test public void mergeTest() {
MergingIterator<Integer> mergingIterator = new MergingIterator<Integer>(new CloseableIterator
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/read/MergingIteratorTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/read/MergingIterator.java // public class MergingIterator<T extends Comparable> implements CloseableIterator<T> { // // private static class ComparableIterator<T extends Comparable> implements PeekableIterator<T>, // Comparable<ComparableIterator<T>> { // // private final CloseableIterator<T> delegate; // private T current; // // private ComparableIterator(CloseableIterator<T> delegate) { // this.delegate = delegate; // // if (delegate.hasNext()) { // current = delegate.next(); // } // } // // @Override // public T current() { // return current; // } // // @Override // public boolean advance() { // if (delegate.hasNext()) { // current = delegate.next(); // return true; // } // // return false; // } // // public void close() throws IOException { // delegate.close(); // } // // @Override // public int compareTo(ComparableIterator<T> other) { // return current.compareTo(other.current); // } // } // // private final Queue<T> next = new LinkedList<T>(); // private final PriorityQueue<ComparableIterator<T>> iteratorHeap; // // public MergingIterator(List<CloseableIterator<T>> iterators) { // this.iteratorHeap = new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // public MergingIterator(CloseableIterator<T>... iterators) { // this(Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, CloseableIterator<T>... iterators) { // this(descending, Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, List<CloseableIterator<T>> iterators) { // this.iteratorHeap = descending ? new PriorityQueue<ComparableIterator<T>>(iterators.size(), // Collections.reverseOrder()) : new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // @Override // public boolean hasNext() { // if (!next.isEmpty()) { // return true; // } // // if (iteratorHeap.isEmpty()) { // return false; // } // // ComparableIterator<T> nextIterator = iteratorHeap.poll(); // T nextCandidate = nextIterator.current(); // // if (nextCandidate != null) { // next.add(nextCandidate); // } // // if (nextIterator.advance()) { // iteratorHeap.add(nextIterator); // } // // if (next.isEmpty()) { // return false; // } // // return true; // } // // @Override // public T next() { // if (next.isEmpty()) { // if (!hasNext()) { // throw new NoSuchElementException(); // } // } // // return next.poll(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void buildIteratorHeap(List<CloseableIterator<T>> iteratorList) { // for (CloseableIterator<T> iterator : iteratorList) { // if (iterator.hasNext()) { // iteratorHeap.add(new ComparableIterator<T>(iterator)); // } // } // } // // @Override // public void close() throws IOException { // for (ComparableIterator<T> comparableIterator : iteratorHeap) { // comparableIterator.close(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // }
import com.google.common.primitives.Ints; import com.jordanwilliams.heftydb.read.MergingIterator; import com.jordanwilliams.heftydb.util.CloseableIterator; import org.junit.Assert; import org.junit.Test; import java.util.Iterator;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.read; public class MergingIteratorTest { private static final int[] ARRAY1 = {1, 2, 3, 4, 5, 6}; private static final int[] ARRAY2 = {1, 4, 5, 7, 9, 10}; private static final int[] MERGED_ARRAY = {1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 9, 10}; @Test public void mergeTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/read/MergingIterator.java // public class MergingIterator<T extends Comparable> implements CloseableIterator<T> { // // private static class ComparableIterator<T extends Comparable> implements PeekableIterator<T>, // Comparable<ComparableIterator<T>> { // // private final CloseableIterator<T> delegate; // private T current; // // private ComparableIterator(CloseableIterator<T> delegate) { // this.delegate = delegate; // // if (delegate.hasNext()) { // current = delegate.next(); // } // } // // @Override // public T current() { // return current; // } // // @Override // public boolean advance() { // if (delegate.hasNext()) { // current = delegate.next(); // return true; // } // // return false; // } // // public void close() throws IOException { // delegate.close(); // } // // @Override // public int compareTo(ComparableIterator<T> other) { // return current.compareTo(other.current); // } // } // // private final Queue<T> next = new LinkedList<T>(); // private final PriorityQueue<ComparableIterator<T>> iteratorHeap; // // public MergingIterator(List<CloseableIterator<T>> iterators) { // this.iteratorHeap = new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // public MergingIterator(CloseableIterator<T>... iterators) { // this(Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, CloseableIterator<T>... iterators) { // this(descending, Arrays.asList(iterators)); // } // // public MergingIterator(boolean descending, List<CloseableIterator<T>> iterators) { // this.iteratorHeap = descending ? new PriorityQueue<ComparableIterator<T>>(iterators.size(), // Collections.reverseOrder()) : new PriorityQueue<ComparableIterator<T>>(); // buildIteratorHeap(iterators); // } // // @Override // public boolean hasNext() { // if (!next.isEmpty()) { // return true; // } // // if (iteratorHeap.isEmpty()) { // return false; // } // // ComparableIterator<T> nextIterator = iteratorHeap.poll(); // T nextCandidate = nextIterator.current(); // // if (nextCandidate != null) { // next.add(nextCandidate); // } // // if (nextIterator.advance()) { // iteratorHeap.add(nextIterator); // } // // if (next.isEmpty()) { // return false; // } // // return true; // } // // @Override // public T next() { // if (next.isEmpty()) { // if (!hasNext()) { // throw new NoSuchElementException(); // } // } // // return next.poll(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void buildIteratorHeap(List<CloseableIterator<T>> iteratorList) { // for (CloseableIterator<T> iterator : iteratorList) { // if (iterator.hasNext()) { // iteratorHeap.add(new ComparableIterator<T>(iterator)); // } // } // } // // @Override // public void close() throws IOException { // for (ComparableIterator<T> comparableIterator : iteratorHeap) { // comparableIterator.close(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/read/MergingIteratorTest.java import com.google.common.primitives.Ints; import com.jordanwilliams.heftydb.read.MergingIterator; import com.jordanwilliams.heftydb.util.CloseableIterator; import org.junit.Assert; import org.junit.Test; import java.util.Iterator; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.read; public class MergingIteratorTest { private static final int[] ARRAY1 = {1, 2, 3, 4, 5, 6}; private static final int[] ARRAY2 = {1, 4, 5, 7, 9, 10}; private static final int[] MERGED_ARRAY = {1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 9, 10}; @Test public void mergeTest() {
MergingIterator<Integer> mergingIterator = new MergingIterator<Integer>(new CloseableIterator
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/base/FileTest.java
// Path: src/test/java/com/jordanwilliams/heftydb/test/helper/TestFileHelper.java // public class TestFileHelper { // // public static final Path TEMP_PATH = Paths.get("/tmp/heftytest"); // // public static void cleanUpTestFiles() throws IOException { // DirectoryStream<Path> filePaths = Files.newDirectoryStream(TEMP_PATH); // // for (Path f : filePaths) { // if (Files.exists(f)) { // Files.delete(f); // } // } // } // // public static void createTestDirectory() throws IOException { // if (!Files.exists(TEMP_PATH)) { // Files.createDirectory(TEMP_PATH); // } // } // }
import com.jordanwilliams.heftydb.test.helper.TestFileHelper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import java.io.IOException;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.base; public class FileTest { @BeforeClass public static void beforeClass() throws IOException {
// Path: src/test/java/com/jordanwilliams/heftydb/test/helper/TestFileHelper.java // public class TestFileHelper { // // public static final Path TEMP_PATH = Paths.get("/tmp/heftytest"); // // public static void cleanUpTestFiles() throws IOException { // DirectoryStream<Path> filePaths = Files.newDirectoryStream(TEMP_PATH); // // for (Path f : filePaths) { // if (Files.exists(f)) { // Files.delete(f); // } // } // } // // public static void createTestDirectory() throws IOException { // if (!Files.exists(TEMP_PATH)) { // Files.createDirectory(TEMP_PATH); // } // } // } // Path: src/test/java/com/jordanwilliams/heftydb/test/base/FileTest.java import com.jordanwilliams.heftydb.test.helper.TestFileHelper; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import java.io.IOException; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.base; public class FileTest { @BeforeClass public static void beforeClass() throws IOException {
TestFileHelper.createTestDirectory();
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/MemoryAllocator.java
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/Allocator.java // public interface Allocator { // // public long allocate(long bytes); // // public void deallocate(long address); // } // // Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // }
import com.codahale.metrics.Counter; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.jordanwilliams.heftydb.offheap.allocator.Allocator; import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A class that allocates off-heap memory and returns reference counted pointers to these blocks of memory. */ public class MemoryAllocator { private static final Unsafe unsafe = JVMUnsafe.unsafe;
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/Allocator.java // public interface Allocator { // // public long allocate(long bytes); // // public void deallocate(long address); // } // // Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/MemoryAllocator.java import com.codahale.metrics.Counter; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.jordanwilliams.heftydb.offheap.allocator.Allocator; import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A class that allocates off-heap memory and returns reference counted pointers to these blocks of memory. */ public class MemoryAllocator { private static final Unsafe unsafe = JVMUnsafe.unsafe;
private static final Allocator allocator = new UnsafeAllocator();
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/MemoryAllocator.java
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/Allocator.java // public interface Allocator { // // public long allocate(long bytes); // // public void deallocate(long address); // } // // Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // }
import com.codahale.metrics.Counter; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.jordanwilliams.heftydb.offheap.allocator.Allocator; import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A class that allocates off-heap memory and returns reference counted pointers to these blocks of memory. */ public class MemoryAllocator { private static final Unsafe unsafe = JVMUnsafe.unsafe;
// Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/Allocator.java // public interface Allocator { // // public long allocate(long bytes); // // public void deallocate(long address); // } // // Path: src/main/java/com/jordanwilliams/heftydb/offheap/allocator/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator { // // private static final Unsafe unsafe = JVMUnsafe.unsafe; // // @Override // public long allocate(long size) { // return unsafe.allocateMemory(size); // } // // @Override // public void deallocate(long address) { // unsafe.freeMemory(address); // } // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/MemoryAllocator.java import com.codahale.metrics.Counter; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.jordanwilliams.heftydb.offheap.allocator.Allocator; import com.jordanwilliams.heftydb.offheap.allocator.UnsafeAllocator; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A class that allocates off-heap memory and returns reference counted pointers to these blocks of memory. */ public class MemoryAllocator { private static final Unsafe unsafe = JVMUnsafe.unsafe;
private static final Allocator allocator = new UnsafeAllocator();
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/io/ImmutableChannelFile.java
// Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.util.Sizes; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.io; /** * A read only wrapper around a FileChannel. */ public class ImmutableChannelFile implements ImmutableFile { private static final ThreadLocal<ByteBuffer> primitiveBuffer = new ThreadLocal<ByteBuffer>() { @Override protected ByteBuffer initialValue() {
// Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/io/ImmutableChannelFile.java import com.jordanwilliams.heftydb.util.Sizes; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.io; /** * A read only wrapper around a FileChannel. */ public class ImmutableChannelFile implements ImmutableFile { private static final ThreadLocal<ByteBuffer> primitiveBuffer = new ThreadLocal<ByteBuffer>() { @Override protected ByteBuffer initialValue() {
ByteBuffer primitiveBuffer = ByteBuffer.allocate(Sizes.LONG_SIZE);
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/db/DB.java
// Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // }
import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.Future;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * The public API for a database implementation. */ public interface DB { public Snapshot put(ByteBuffer key, ByteBuffer value) throws IOException; public Snapshot put(ByteBuffer key, ByteBuffer value, boolean fsync) throws IOException; public Record get(ByteBuffer key) throws IOException; public Record get(ByteBuffer key, Snapshot snapshot) throws IOException; public Snapshot delete(ByteBuffer key) throws IOException;
// Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // } // Path: src/main/java/com/jordanwilliams/heftydb/db/DB.java import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.Future; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * The public API for a database implementation. */ public interface DB { public Snapshot put(ByteBuffer key, ByteBuffer value) throws IOException; public Snapshot put(ByteBuffer key, ByteBuffer value, boolean fsync) throws IOException; public Record get(ByteBuffer key) throws IOException; public Record get(ByteBuffer key, Snapshot snapshot) throws IOException; public Snapshot delete(ByteBuffer key) throws IOException;
public CloseableIterator<Record> ascendingIterator(Snapshot snapshot) throws IOException;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionTables.java
// Path: src/main/java/com/jordanwilliams/heftydb/state/Tables.java // public class Tables implements Iterable<Table> { // // public interface ChangeHandler { // public void changed(); // } // // private final AtomicLong currentTableId = new AtomicLong(); // private final NavigableSet<Table> tables = new TreeSet<Table>(); // private final ReadWriteLock tableLock = new ReentrantReadWriteLock(); // private final List<ChangeHandler> changeHandlers = new ArrayList<ChangeHandler>(); // // public Tables(Collection<Table> initialTables) { // this.tables.addAll(initialTables); // this.currentTableId.set(tables.isEmpty() ? 0 : tables.last().id()); // } // // public synchronized void addChangeHandler(ChangeHandler changeHandler) { // changeHandlers.add(changeHandler); // } // // public synchronized void removeChangeHandler(ChangeHandler changeHandler) { // changeHandlers.remove(changeHandler); // } // // public long nextId() { // return currentTableId.incrementAndGet(); // } // // public long currentId() { // return currentTableId.get(); // } // // public void readLock() { // tableLock.readLock().lock(); // } // // public void readUnlock() { // tableLock.readLock().unlock(); // } // // public void add(Table toAdd) { // try { // tableLock.writeLock().lock(); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void removeAll(List<Table> toRemove) { // try { // tableLock.writeLock().lock(); // for (Table table : toRemove) { // tables.remove(table); // } // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void remove(Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void swap(Table toAdd, Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public int count() { // return tables.size(); // } // // @Override // public Iterator<Table> iterator() { // return tables.iterator(); // } // // private synchronized void notifyChanged() { // for (ChangeHandler changeHandler : changeHandlers) { // changeHandler.changed(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // }
import com.jordanwilliams.heftydb.state.Tables; import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Wraps a set of Tables and tracks compaction status for each table. */ public class CompactionTables { private final Set<Long> alreadyCompactedTables = new HashSet<Long>();
// Path: src/main/java/com/jordanwilliams/heftydb/state/Tables.java // public class Tables implements Iterable<Table> { // // public interface ChangeHandler { // public void changed(); // } // // private final AtomicLong currentTableId = new AtomicLong(); // private final NavigableSet<Table> tables = new TreeSet<Table>(); // private final ReadWriteLock tableLock = new ReentrantReadWriteLock(); // private final List<ChangeHandler> changeHandlers = new ArrayList<ChangeHandler>(); // // public Tables(Collection<Table> initialTables) { // this.tables.addAll(initialTables); // this.currentTableId.set(tables.isEmpty() ? 0 : tables.last().id()); // } // // public synchronized void addChangeHandler(ChangeHandler changeHandler) { // changeHandlers.add(changeHandler); // } // // public synchronized void removeChangeHandler(ChangeHandler changeHandler) { // changeHandlers.remove(changeHandler); // } // // public long nextId() { // return currentTableId.incrementAndGet(); // } // // public long currentId() { // return currentTableId.get(); // } // // public void readLock() { // tableLock.readLock().lock(); // } // // public void readUnlock() { // tableLock.readLock().unlock(); // } // // public void add(Table toAdd) { // try { // tableLock.writeLock().lock(); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void removeAll(List<Table> toRemove) { // try { // tableLock.writeLock().lock(); // for (Table table : toRemove) { // tables.remove(table); // } // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void remove(Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void swap(Table toAdd, Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public int count() { // return tables.size(); // } // // @Override // public Iterator<Table> iterator() { // return tables.iterator(); // } // // private synchronized void notifyChanged() { // for (ChangeHandler changeHandler : changeHandlers) { // changeHandler.changed(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionTables.java import com.jordanwilliams.heftydb.state.Tables; import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Wraps a set of Tables and tracks compaction status for each table. */ public class CompactionTables { private final Set<Long> alreadyCompactedTables = new HashSet<Long>();
private final Tables tables;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionTables.java
// Path: src/main/java/com/jordanwilliams/heftydb/state/Tables.java // public class Tables implements Iterable<Table> { // // public interface ChangeHandler { // public void changed(); // } // // private final AtomicLong currentTableId = new AtomicLong(); // private final NavigableSet<Table> tables = new TreeSet<Table>(); // private final ReadWriteLock tableLock = new ReentrantReadWriteLock(); // private final List<ChangeHandler> changeHandlers = new ArrayList<ChangeHandler>(); // // public Tables(Collection<Table> initialTables) { // this.tables.addAll(initialTables); // this.currentTableId.set(tables.isEmpty() ? 0 : tables.last().id()); // } // // public synchronized void addChangeHandler(ChangeHandler changeHandler) { // changeHandlers.add(changeHandler); // } // // public synchronized void removeChangeHandler(ChangeHandler changeHandler) { // changeHandlers.remove(changeHandler); // } // // public long nextId() { // return currentTableId.incrementAndGet(); // } // // public long currentId() { // return currentTableId.get(); // } // // public void readLock() { // tableLock.readLock().lock(); // } // // public void readUnlock() { // tableLock.readLock().unlock(); // } // // public void add(Table toAdd) { // try { // tableLock.writeLock().lock(); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void removeAll(List<Table> toRemove) { // try { // tableLock.writeLock().lock(); // for (Table table : toRemove) { // tables.remove(table); // } // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void remove(Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void swap(Table toAdd, Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public int count() { // return tables.size(); // } // // @Override // public Iterator<Table> iterator() { // return tables.iterator(); // } // // private synchronized void notifyChanged() { // for (ChangeHandler changeHandler : changeHandlers) { // changeHandler.changed(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // }
import com.jordanwilliams.heftydb.state.Tables; import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Wraps a set of Tables and tracks compaction status for each table. */ public class CompactionTables { private final Set<Long> alreadyCompactedTables = new HashSet<Long>(); private final Tables tables; public CompactionTables(Tables tables) { this.tables = tables; }
// Path: src/main/java/com/jordanwilliams/heftydb/state/Tables.java // public class Tables implements Iterable<Table> { // // public interface ChangeHandler { // public void changed(); // } // // private final AtomicLong currentTableId = new AtomicLong(); // private final NavigableSet<Table> tables = new TreeSet<Table>(); // private final ReadWriteLock tableLock = new ReentrantReadWriteLock(); // private final List<ChangeHandler> changeHandlers = new ArrayList<ChangeHandler>(); // // public Tables(Collection<Table> initialTables) { // this.tables.addAll(initialTables); // this.currentTableId.set(tables.isEmpty() ? 0 : tables.last().id()); // } // // public synchronized void addChangeHandler(ChangeHandler changeHandler) { // changeHandlers.add(changeHandler); // } // // public synchronized void removeChangeHandler(ChangeHandler changeHandler) { // changeHandlers.remove(changeHandler); // } // // public long nextId() { // return currentTableId.incrementAndGet(); // } // // public long currentId() { // return currentTableId.get(); // } // // public void readLock() { // tableLock.readLock().lock(); // } // // public void readUnlock() { // tableLock.readLock().unlock(); // } // // public void add(Table toAdd) { // try { // tableLock.writeLock().lock(); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void removeAll(List<Table> toRemove) { // try { // tableLock.writeLock().lock(); // for (Table table : toRemove) { // tables.remove(table); // } // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void remove(Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public void swap(Table toAdd, Table toRemove) { // try { // tableLock.writeLock().lock(); // tables.remove(toRemove); // tables.add(toAdd); // notifyChanged(); // } finally { // tableLock.writeLock().unlock(); // } // } // // public int count() { // return tables.size(); // } // // @Override // public Iterator<Table> iterator() { // return tables.iterator(); // } // // private synchronized void notifyChanged() { // for (ChangeHandler changeHandler : changeHandlers) { // changeHandler.changed(); // } // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionTables.java import com.jordanwilliams.heftydb.state.Tables; import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Wraps a set of Tables and tracks compaction status for each table. */ public class CompactionTables { private final Set<Long> alreadyCompactedTables = new HashSet<Long>(); private final Tables tables; public CompactionTables(Tables tables) { this.tables = tables; }
public List<Table> eligibleTables() {
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/index/IndexRecord.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.util.Sizes;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.index; /** * Represents a single entry in an IndexBlock. */ public class IndexRecord { private final Key startKey; private final long blockOffset; private final int blockSize; private final boolean isLeaf; public IndexRecord(Key startKey, long blockOffset, int blockSize, boolean isLeaf) { this.startKey = startKey; this.blockOffset = blockOffset; this.blockSize = blockSize; this.isLeaf = isLeaf; } public IndexRecord(Key startKey, long blockOffset, int blockSize) { this(startKey, blockOffset, blockSize, true); } public Key startKey() { return startKey; } public long blockOffset() { return blockOffset; } public int blockSize() { return blockSize; } public int size() {
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/index/IndexRecord.java import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.util.Sizes; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.index; /** * Represents a single entry in an IndexBlock. */ public class IndexRecord { private final Key startKey; private final long blockOffset; private final int blockSize; private final boolean isLeaf; public IndexRecord(Key startKey, long blockOffset, int blockSize, boolean isLeaf) { this.startKey = startKey; this.blockOffset = blockOffset; this.blockSize = blockSize; this.isLeaf = isLeaf; } public IndexRecord(Key startKey, long blockOffset, int blockSize) { this(startKey, blockOffset, blockSize, true); } public Key startKey() { return startKey; } public long blockOffset() { return blockOffset; } public int blockSize() { return blockSize; } public int size() {
return Sizes.INT_SIZE + //Key blockSize
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/db/Record.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/ByteBuffers.java // public class ByteBuffers { // // public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); // // public static ByteBuffer fromString(String string) { // return ByteBuffer.wrap(string.getBytes(Charset.defaultCharset())); // } // // public static String toString(ByteBuffer byteBuffer) { // byte[] bytes = new byte[byteBuffer.capacity()]; // // for (int i = 0; i < byteBuffer.capacity(); i++) { // bytes[i] = byteBuffer.get(i); // } // // return new String(bytes); // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // }
import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.util.ByteBuffers; import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * A public wrapper class that represents the results of a database read. */ public class Record implements Comparable<Record> { public static class TupleIterator implements CloseableIterator<Record> {
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/ByteBuffers.java // public class ByteBuffers { // // public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); // // public static ByteBuffer fromString(String string) { // return ByteBuffer.wrap(string.getBytes(Charset.defaultCharset())); // } // // public static String toString(ByteBuffer byteBuffer) { // byte[] bytes = new byte[byteBuffer.capacity()]; // // for (int i = 0; i < byteBuffer.capacity(); i++) { // bytes[i] = byteBuffer.get(i); // } // // return new String(bytes); // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // } // Path: src/main/java/com/jordanwilliams/heftydb/db/Record.java import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.util.ByteBuffers; import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.db; /** * A public wrapper class that represents the results of a database read. */ public class Record implements Comparable<Record> { public static class TupleIterator implements CloseableIterator<Record> {
private final CloseableIterator<Tuple> tupleIterator;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/db/Record.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/ByteBuffers.java // public class ByteBuffers { // // public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); // // public static ByteBuffer fromString(String string) { // return ByteBuffer.wrap(string.getBytes(Charset.defaultCharset())); // } // // public static String toString(ByteBuffer byteBuffer) { // byte[] bytes = new byte[byteBuffer.capacity()]; // // for (int i = 0; i < byteBuffer.capacity(); i++) { // bytes[i] = byteBuffer.get(i); // } // // return new String(bytes); // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // }
import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.util.ByteBuffers; import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer;
} return Long.compare(snapshot.id(), o.snapshot.id()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; if (key != null ? !key.equals(record.key) : record.key != null) return false; if (snapshot != null ? !snapshot.equals(record.snapshot) : record.snapshot != null) return false; if (value != null ? !value.equals(record.value) : record.value != null) return false; return true; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (snapshot != null ? snapshot.hashCode() : 0); return result; } @Override public String toString() { return "Record{" +
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/ByteBuffers.java // public class ByteBuffers { // // public static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); // // public static ByteBuffer fromString(String string) { // return ByteBuffer.wrap(string.getBytes(Charset.defaultCharset())); // } // // public static String toString(ByteBuffer byteBuffer) { // byte[] bytes = new byte[byteBuffer.capacity()]; // // for (int i = 0; i < byteBuffer.capacity(); i++) { // bytes[i] = byteBuffer.get(i); // } // // return new String(bytes); // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/CloseableIterator.java // public interface CloseableIterator<T> extends Iterator<T>, Closeable { // // public static class Wrapper<T> implements CloseableIterator<T> { // // private final Iterator<T> delegate; // // public Wrapper(Iterator<T> delegate) { // this.delegate = delegate; // } // // @Override // public void close() throws IOException { // // } // // @Override // public boolean hasNext() { // return delegate.hasNext(); // } // // @Override // public T next() { // return delegate.next(); // } // // @Override // public void remove() { // delegate.remove(); // } // } // // } // Path: src/main/java/com/jordanwilliams/heftydb/db/Record.java import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.util.ByteBuffers; import com.jordanwilliams.heftydb.util.CloseableIterator; import java.io.IOException; import java.nio.ByteBuffer; } return Long.compare(snapshot.id(), o.snapshot.id()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; if (key != null ? !key.equals(record.key) : record.key != null) return false; if (snapshot != null ? !snapshot.equals(record.snapshot) : record.snapshot != null) return false; if (value != null ? !value.equals(record.value) : record.value != null) return false; return true; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (snapshot != null ? snapshot.hashCode() : 0); return result; } @Override public String toString() { return "Record{" +
"key=" + ByteBuffers.toString(key) +
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // }
import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override
public CompactionPlanner initialize(CompactionTables tables) {
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // }
import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) {
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) {
return new SizeTieredCompactionPlanner(tables);
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // }
import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) { return new SizeTieredCompactionPlanner(tables); } }, NULL_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) { return new CompactionPlanner() { @Override public CompactionPlan planCompaction() { return new CompactionPlan(Collections.<CompactionTask>emptyList()); } @Override public boolean needsCompaction() { return false; } }; } }, FULL_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) {
// Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/CompactionPlanner.java // public interface CompactionPlanner { // // public CompactionPlan planCompaction(); // // public boolean needsCompaction(); // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/FullCompactionPlanner.java // public class FullCompactionPlanner implements CompactionPlanner { // // private final CompactionTables tables; // // public FullCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // CompactionTask.Builder taskBuilder = new CompactionTask.Builder(2, CompactionTask.Priority.NORMAL); // // List<Table> eligibleTables = tables.eligibleTables(); // // if (eligibleTables.size() > 1) { // for (Table table : eligibleTables){ // taskBuilder.add(table); // } // // return new CompactionPlan(taskBuilder.build()); // } // // return null; // } // // @Override // public boolean needsCompaction() { // return false; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/compact/planner/SizeTieredCompactionPlanner.java // public class SizeTieredCompactionPlanner implements CompactionPlanner { // // private static final int MAX_LEVEL_TABLES = 5; // // private final CompactionTables tables; // // public SizeTieredCompactionPlanner(CompactionTables tables) { // this.tables = tables; // } // // @Override // public CompactionPlan planCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // List<CompactionTask> compactionTasks = new ArrayList<CompactionTask>(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // int level = entry.getKey(); // compactionTasks.add(new CompactionTask(entry.getValue(), level + 1, level < 3 ? CompactionTask // .Priority.HIGH : CompactionTask.Priority.NORMAL)); // } // } // // return new CompactionPlan(compactionTasks); // } // // @Override // public boolean needsCompaction() { // SortedMap<Integer, List<Table>> leveledTables = leveledTables(); // // for (Map.Entry<Integer, List<Table>> entry : leveledTables.entrySet()) { // if (entry.getValue().size() >= MAX_LEVEL_TABLES) { // return true; // } // } // // return false; // } // // private SortedMap<Integer, List<Table>> leveledTables() { // SortedMap<Integer, List<Table>> tableMap = new TreeMap<Integer, List<Table>>(); // // List<Table> eligibleTables = tables.eligibleTables(); // // for (Table table : eligibleTables) { // List<Table> levelTables = tableMap.get(table.level()); // // if (levelTables == null) { // levelTables = new ArrayList<Table>(); // tableMap.put(table.level(), levelTables); // } // // levelTables.add(table); // } // // return tableMap; // } // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionStrategies.java import com.jordanwilliams.heftydb.compact.planner.CompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.FullCompactionPlanner; import com.jordanwilliams.heftydb.compact.planner.SizeTieredCompactionPlanner; import java.util.Collections; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Contains built in compaction strategies. */ public enum CompactionStrategies implements CompactionStrategy { SIZE_TIERED_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) { return new SizeTieredCompactionPlanner(tables); } }, NULL_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) { return new CompactionPlanner() { @Override public CompactionPlan planCompaction() { return new CompactionPlan(Collections.<CompactionTask>emptyList()); } @Override public boolean needsCompaction() { return false; } }; } }, FULL_COMPACTION_STRATEGY { @Override public CompactionPlanner initialize(CompactionTables tables) {
return new FullCompactionPlanner(tables);
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A sorted block of key-value entries optimized for efficient binary search and backed by off-heap memory. A binary * search over a SortedByteMap requires no object allocations, and is thus quite fast. */ public class SortedByteMap implements Offheap, Iterable<SortedByteMap.Entry> { private static final Unsafe unsafe = JVMUnsafe.unsafe; private static final int PAGE_SIZE = unsafe.pageSize(); public static class Entry {
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A sorted block of key-value entries optimized for efficient binary search and backed by off-heap memory. A binary * search over a SortedByteMap requires no object allocations, and is thus quite fast. */ public class SortedByteMap implements Offheap, Iterable<SortedByteMap.Entry> { private static final Unsafe unsafe = JVMUnsafe.unsafe; private static final int PAGE_SIZE = unsafe.pageSize(); public static class Entry {
private final Key key;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A sorted block of key-value entries optimized for efficient binary search and backed by off-heap memory. A binary * search over a SortedByteMap requires no object allocations, and is thus quite fast. */ public class SortedByteMap implements Offheap, Iterable<SortedByteMap.Entry> { private static final Unsafe unsafe = JVMUnsafe.unsafe; private static final int PAGE_SIZE = unsafe.pageSize(); public static class Entry { private final Key key;
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * A sorted block of key-value entries optimized for efficient binary search and backed by off-heap memory. A binary * search over a SortedByteMap requires no object allocations, and is thus quite fast. */ public class SortedByteMap implements Offheap, Iterable<SortedByteMap.Entry> { private static final Unsafe unsafe = JVMUnsafe.unsafe; private static final int PAGE_SIZE = unsafe.pageSize(); public static class Entry { private final Key key;
private final Value value;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException;
public Value value() { return value; } @Override public String toString() { return "Entry{" + "key=" + key + ", value=" + value + '}'; } } public static class Builder { private final List<Entry> entries = new LinkedList<Entry>(); public void add(Key key, Value value) { entries.add(new Entry(key, value)); } public SortedByteMap build() { return new SortedByteMap(serializeEntries()); } private MemoryPointer serializeEntries() { //Allocate pointer int memorySize = 0; int[] entryOffsets = new int[entries.size()];
// Path: src/main/java/com/jordanwilliams/heftydb/data/Key.java // public class Key implements Comparable<Key> { // // private final ByteBuffer data; // private final long snapshotId; // // public Key(ByteBuffer data, long snapshotId) { // this.data = data; // this.snapshotId = snapshotId; // } // // public ByteBuffer data() { // return data; // } // // public long snapshotId() { // return snapshotId; // } // // public int size() { // return data.capacity(); // } // // @Override // public int compareTo(Key o) { // int compared = data.compareTo(o.data); // // if (compared != 0) { // return compared; // } // // return Long.compare(snapshotId, o.snapshotId); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Key key = (Key) o; // // if (snapshotId != key.snapshotId) return false; // if (data != null ? !data.equals(key.data) : key.data != null) return false; // // return true; // } // // @Override // public int hashCode() { // return data != null ? data.hashCode() : 0; // } // // @Override // public String toString() { // byte[] keyArray = new byte[data.capacity()]; // data.rewind(); // data.get(keyArray); // data.rewind(); // // return "Key{" + // "data=" + new String(keyArray) + // ", snapshotId=" + snapshotId + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/data/Value.java // public class Value implements Comparable<Value> { // // public static Value TOMBSTONE_VALUE = new Value(ByteBuffers.EMPTY_BUFFER); // // private final ByteBuffer value; // // public Value(ByteBuffer value) { // this.value = value; // } // // public ByteBuffer data() { // return value; // } // // public boolean isEmpty() { // return value.capacity() == 0; // } // // public int size() { // return value.capacity(); // } // // @Override // public int compareTo(Value o) { // return value.compareTo(o.value); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // Value value1 = (Value) o; // // if (value != null ? !value.equals(value1.value) : value1.value != null) { // return false; // } // // return true; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // // @Override // public String toString() { // return "Value{" + // "data=" + new String(value.array()) + // "}"; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/SortedByteMap.java import com.jordanwilliams.heftydb.data.Key; import com.jordanwilliams.heftydb.data.Value; import com.jordanwilliams.heftydb.util.Sizes; import sun.misc.Unsafe; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; public Value value() { return value; } @Override public String toString() { return "Entry{" + "key=" + key + ", value=" + value + '}'; } } public static class Builder { private final List<Entry> entries = new LinkedList<Entry>(); public void add(Key key, Value value) { entries.add(new Entry(key, value)); } public SortedByteMap build() { return new SortedByteMap(serializeEntries()); } private MemoryPointer serializeEntries() { //Allocate pointer int memorySize = 0; int[] entryOffsets = new int[entries.size()];
memorySize += Sizes.INT_SIZE; //MemoryPointer count
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/compact/CompactionTask.java
// Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // }
import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.List;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Represents a single CompactionTask. */ public class CompactionTask { public enum Priority { HIGH, NORMAL } public static class Builder {
// Path: src/main/java/com/jordanwilliams/heftydb/table/Table.java // public interface Table extends Iterable<Tuple>, Comparable<Table> { // // public long id(); // // public boolean mightContain(Key key); // // public Tuple get(Key key); // // public CloseableIterator<Tuple> ascendingIterator(long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(long snapshotId); // // public CloseableIterator<Tuple> ascendingIterator(Key key, long snapshotId); // // public CloseableIterator<Tuple> descendingIterator(Key key, long snapshotId); // // public long tupleCount(); // // public long size(); // // public int level(); // // public long maxSnapshotId(); // // public void close(); // // public boolean isPersistent(); // } // Path: src/main/java/com/jordanwilliams/heftydb/compact/CompactionTask.java import com.jordanwilliams.heftydb.table.Table; import java.util.ArrayList; import java.util.List; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.compact; /** * Represents a single CompactionTask. */ public class CompactionTask { public enum Priority { HIGH, NORMAL } public static class Builder {
private final List<Table> tables = new ArrayList<Table>();
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java
// Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // }
import com.jordanwilliams.heftydb.util.Sizes; import java.nio.ByteBuffer;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * An immutable bit set that is backed by off-heap memory. */ public class BitSet implements Offheap { public static class Builder { private final MemoryPointer pointer; private final ByteBuffer directBuffer; private final int usableBytes; public Builder(long bitCount, int paddingBytes) {
// Path: src/main/java/com/jordanwilliams/heftydb/util/Sizes.java // public class Sizes { // // public static int LONG_SIZE = 8; // // public static int INT_SIZE = 4; // } // Path: src/main/java/com/jordanwilliams/heftydb/offheap/BitSet.java import com.jordanwilliams.heftydb.util.Sizes; import java.nio.ByteBuffer; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.offheap; /** * An immutable bit set that is backed by off-heap memory. */ public class BitSet implements Offheap { public static class Builder { private final MemoryPointer pointer; private final ByteBuffer directBuffer; private final int usableBytes; public Builder(long bitCount, int paddingBytes) {
this.usableBytes = memoryOffset(bitCount) + Sizes.LONG_SIZE;
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/table/file/TableTrailer.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/io/ImmutableFile.java // public interface ImmutableFile extends Closeable { // // public long read(ByteBuffer bufferToRead, long position) throws IOException; // // public int readInt(long position) throws IOException; // // public long readLong(long position) throws IOException; // // public long size() throws IOException; // }
import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.io.ImmutableFile; import java.io.IOException; import java.nio.ByteBuffer;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.table.file; /** * Encapsulates meta data stored at the end of a Table file. */ public class TableTrailer { public static final int SIZE = 28; public static class Builder { private final long tableId; private final int level; private long recordCount; private long maxSnapshotId; public Builder(long tableId, int level) { this.tableId = tableId; this.level = level; }
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/io/ImmutableFile.java // public interface ImmutableFile extends Closeable { // // public long read(ByteBuffer bufferToRead, long position) throws IOException; // // public int readInt(long position) throws IOException; // // public long readLong(long position) throws IOException; // // public long size() throws IOException; // } // Path: src/main/java/com/jordanwilliams/heftydb/table/file/TableTrailer.java import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.io.ImmutableFile; import java.io.IOException; import java.nio.ByteBuffer; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.table.file; /** * Encapsulates meta data stored at the end of a Table file. */ public class TableTrailer { public static final int SIZE = 28; public static class Builder { private final long tableId; private final int level; private long recordCount; private long maxSnapshotId; public Builder(long tableId, int level) { this.tableId = tableId; this.level = level; }
public void put(Tuple tuple) {
jordw/heftydb
src/main/java/com/jordanwilliams/heftydb/table/file/TableTrailer.java
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/io/ImmutableFile.java // public interface ImmutableFile extends Closeable { // // public long read(ByteBuffer bufferToRead, long position) throws IOException; // // public int readInt(long position) throws IOException; // // public long readLong(long position) throws IOException; // // public long size() throws IOException; // }
import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.io.ImmutableFile; import java.io.IOException; import java.nio.ByteBuffer;
public TableTrailer(ByteBuffer buffer) { this.tableId = buffer.getLong(); this.level = buffer.getInt(); this.recordCount = buffer.getLong(); this.maxSnapshotId = buffer.getLong(); buffer.rewind(); this.buffer = buffer; } public long tableId() { return tableId; } public long maxSnapshotId() { return maxSnapshotId; } public long recordCount() { return recordCount; } public int level() { return level; } public ByteBuffer buffer() { return buffer; }
// Path: src/main/java/com/jordanwilliams/heftydb/data/Tuple.java // public class Tuple implements Comparable<Tuple> { // // public static Serializer<Tuple> SERIALIZER = new Serializer<Tuple>() { // @Override // public int size(Tuple tuple) { // int size = 0; // // //Key // size += Sizes.INT_SIZE; // size += tuple.key().size(); // size += Sizes.LONG_SIZE; // // //Value // size += Sizes.INT_SIZE; // size += tuple.value().size(); // // return size; // } // // @Override // public void serialize(Tuple tuple, ByteBuffer recordBuffer) { // //Key // recordBuffer.putInt(tuple.key.size()); // recordBuffer.put(tuple.key.data()); // recordBuffer.putLong(tuple.key.snapshotId()); // tuple.key().data().rewind(); // // //Value // recordBuffer.putInt(tuple.value.size()); // recordBuffer.put(tuple.value().data()); // tuple.value().data().rewind(); // // recordBuffer.rewind(); // } // // @Override // public Tuple deserialize(ByteBuffer recordBuffer) { // //Key // int keySize = recordBuffer.getInt(); // ByteBuffer keyBuffer = ByteBuffer.allocate(keySize); // recordBuffer.get(keyBuffer.array()); // long snapshotId = recordBuffer.getLong(); // Key key = new Key(keyBuffer, snapshotId); // // //Value // int valueSize = recordBuffer.getInt(); // ByteBuffer valueBuffer = ByteBuffer.allocate(valueSize); // recordBuffer.get(valueBuffer.array()); // Value value = new Value(valueBuffer); // // return new Tuple(key, value); // } // }; // // private final Key key; // private final Value value; // // public Tuple(Key key, Value value) { // this.key = key; // this.value = value; // } // // public Key key() { // return key; // } // // public Value value() { // return value; // } // // public int size() { // return key.size() + value().size(); // } // // public void rewind() { // key.data().rewind(); // value.data().rewind(); // } // // @Override // public int compareTo(Tuple o) { // return key.compareTo(o.key); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Tuple tuple = (Tuple) o; // // if (key != null ? !key.equals(tuple.key) : tuple.key != null) return false; // if (value != null ? !value.equals(tuple.value) : tuple.value != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = key != null ? key.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Tuple{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/com/jordanwilliams/heftydb/io/ImmutableFile.java // public interface ImmutableFile extends Closeable { // // public long read(ByteBuffer bufferToRead, long position) throws IOException; // // public int readInt(long position) throws IOException; // // public long readLong(long position) throws IOException; // // public long size() throws IOException; // } // Path: src/main/java/com/jordanwilliams/heftydb/table/file/TableTrailer.java import com.jordanwilliams.heftydb.data.Tuple; import com.jordanwilliams.heftydb.io.ImmutableFile; import java.io.IOException; import java.nio.ByteBuffer; public TableTrailer(ByteBuffer buffer) { this.tableId = buffer.getLong(); this.level = buffer.getInt(); this.recordCount = buffer.getLong(); this.maxSnapshotId = buffer.getLong(); buffer.rewind(); this.buffer = buffer; } public long tableId() { return tableId; } public long maxSnapshotId() { return maxSnapshotId; } public long recordCount() { return recordCount; } public int level() { return level; } public ByteBuffer buffer() { return buffer; }
public static TableTrailer read(ImmutableFile tableFile) throws IOException {
jordw/heftydb
src/test/java/com/jordanwilliams/heftydb/test/unit/util/XORShiftRandomTest.java
// Path: src/main/java/com/jordanwilliams/heftydb/util/XORShiftRandom.java // public class XORShiftRandom { // // private long last; // // public XORShiftRandom(long seed) { // this.last = seed; // } // // public int nextInt(int max) { // last ^= (last << 21); // last ^= (last >>> 35); // last ^= (last << 4); // int out = (int) last % max; // return (out < 0) ? -out : out; // } // // public int nextInt() { // last ^= (last << 21); // last ^= (last >>> 35); // last ^= (last << 4); // int out = (int) last; // return (out < 0) ? -out : out; // } // }
import com.jordanwilliams.heftydb.util.XORShiftRandom; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List;
/* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.util; public class XORShiftRandomTest { @Test public void randomTest() {
// Path: src/main/java/com/jordanwilliams/heftydb/util/XORShiftRandom.java // public class XORShiftRandom { // // private long last; // // public XORShiftRandom(long seed) { // this.last = seed; // } // // public int nextInt(int max) { // last ^= (last << 21); // last ^= (last >>> 35); // last ^= (last << 4); // int out = (int) last % max; // return (out < 0) ? -out : out; // } // // public int nextInt() { // last ^= (last << 21); // last ^= (last >>> 35); // last ^= (last << 4); // int out = (int) last; // return (out < 0) ? -out : out; // } // } // Path: src/test/java/com/jordanwilliams/heftydb/test/unit/util/XORShiftRandomTest.java import com.jordanwilliams.heftydb.util.XORShiftRandom; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; /* * Copyright (c) 2014. Jordan Williams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jordanwilliams.heftydb.test.unit.util; public class XORShiftRandomTest { @Test public void randomTest() {
XORShiftRandom random = new XORShiftRandom(32);
sangupta/dry-redis
src/test/java/com/sangupta/dryredis/TestDryRedisList.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.junit.Assert; import org.junit.Test; import com.sangupta.dryredis.support.DryRedisInsertOrder;
Assert.assertEquals("OK", redis.ltrim("key", 1, 3)); Assert.assertEquals(TestUtils.asList("value2", "value3", "value4"), redis.lrange("key", 0, 20)); Assert.assertEquals("OK", redis.ltrim("key", 0, 10)); Assert.assertEquals(TestUtils.asList("value2", "value3", "value4"), redis.lrange("key", 0, 20)); redis.rpush("next", list); Assert.assertEquals("OK", redis.ltrim("next", -3, -2)); Assert.assertEquals(TestUtils.asList("value3", "value4"), redis.lrange("next", 0, 20)); redis.rpush("tp", list); Assert.assertEquals("OK", redis.ltrim("tp", -3, -4)); Assert.assertTrue(redis.lrange("tp", 0, 20).isEmpty()); Assert.assertEquals("OK", redis.ltrim("non-existent", 0, 10)); redis.rpush("empty", list); redis.rpop("empty"); Assert.assertEquals("OK", redis.ltrim("empty", 0, 10)); // key deleted redis.rpush("some", list); Assert.assertEquals("OK", redis.ltrim("some", 10, 15)); Assert.assertNull(redis.lrange("some", 0, 10)); } @Test public void testLINSERT() { DryRedisListOperations redis = getRedis(); // non-existent list
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // Path: src/test/java/com/sangupta/dryredis/TestDryRedisList.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.junit.Assert; import org.junit.Test; import com.sangupta.dryredis.support.DryRedisInsertOrder; Assert.assertEquals("OK", redis.ltrim("key", 1, 3)); Assert.assertEquals(TestUtils.asList("value2", "value3", "value4"), redis.lrange("key", 0, 20)); Assert.assertEquals("OK", redis.ltrim("key", 0, 10)); Assert.assertEquals(TestUtils.asList("value2", "value3", "value4"), redis.lrange("key", 0, 20)); redis.rpush("next", list); Assert.assertEquals("OK", redis.ltrim("next", -3, -2)); Assert.assertEquals(TestUtils.asList("value3", "value4"), redis.lrange("next", 0, 20)); redis.rpush("tp", list); Assert.assertEquals("OK", redis.ltrim("tp", -3, -4)); Assert.assertTrue(redis.lrange("tp", 0, 20).isEmpty()); Assert.assertEquals("OK", redis.ltrim("non-existent", 0, 10)); redis.rpush("empty", list); redis.rpop("empty"); Assert.assertEquals("OK", redis.ltrim("empty", 0, 10)); // key deleted redis.rpush("some", list); Assert.assertEquals("OK", redis.ltrim("some", 10, 15)); Assert.assertNull(redis.lrange("some", 0, 10)); } @Test public void testLINSERT() { DryRedisListOperations redis = getRedis(); // non-existent list
Assert.assertEquals(0, redis.linsert("non-existent", DryRedisInsertOrder.BEFORE, "4", "3"));
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisKeys.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // }
import java.util.List; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType; import java.util.ArrayList;
} if(key.equals(newKey)) { return 0; } if(this.exists(key) == 0) { return 0; } if(this.exists(newKey) == 1) { return 0; } DryRedisCache cache = this.getCache(key); cache.rename(key, newKey); return 1; } public List<String> keys(String pattern) { List<String> keys = new ArrayList<String>(); for(DryRedisCache cache : caches) { cache.keys(pattern, keys); } return keys; } public String type(String key) {
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisKeys.java import java.util.List; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType; import java.util.ArrayList; } if(key.equals(newKey)) { return 0; } if(this.exists(key) == 0) { return 0; } if(this.exists(newKey) == 1) { return 0; } DryRedisCache cache = this.getCache(key); cache.rename(key, newKey); return 1; } public List<String> keys(String pattern) { List<String> keys = new ArrayList<String>(); for(DryRedisCache cache : caches) { cache.keys(pattern, keys); } return keys; } public String type(String key) {
DryRedisCacheType type = keyType(key);
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisSet.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // }
import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType;
continue; } clonedSet.addAll(otherSet); } return clonedSet; } /* (non-Javadoc) * @see com.sangupta.dryredis.cache.impl.DryRedisSetOperations#sunionstore(java.lang.String, java.lang.String, java.lang.String) */ @Override public int sunionstore(String destination, String key, String... otherKeys) { Set<String> setToStore = this.sunion(key, otherKeys); this.store.put(destination, setToStore); return setToStore.size(); } /* (non-Javadoc) * @see com.sangupta.dryredis.cache.impl.DryRedisSetOperations#sscan(java.lang.String, int) */ @Override public List<String> sscan(String key, int cursor) { throw new RuntimeException("Not yet implemented"); } // commands for DryRedisCache @Override
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisSet.java import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType; continue; } clonedSet.addAll(otherSet); } return clonedSet; } /* (non-Javadoc) * @see com.sangupta.dryredis.cache.impl.DryRedisSetOperations#sunionstore(java.lang.String, java.lang.String, java.lang.String) */ @Override public int sunionstore(String destination, String key, String... otherKeys) { Set<String> setToStore = this.sunion(key, otherKeys); this.store.put(destination, setToStore); return setToStore.size(); } /* (non-Javadoc) * @see com.sangupta.dryredis.cache.impl.DryRedisSetOperations#sscan(java.lang.String, int) */ @Override public List<String> sscan(String key, int cursor) { throw new RuntimeException("Not yet implemented"); } // commands for DryRedisCache @Override
public DryRedisCacheType getType() {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisGeoOperations.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // }
import com.sangupta.dryredis.support.DryRedisGeoUnit; import java.util.List;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisGeoOperations { public int geoadd(String key, double longitude, double latitude, String member); public String geohash(String key, String member); public double[] geopos(String key, String member);
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisGeoOperations.java import com.sangupta.dryredis.support.DryRedisGeoUnit; import java.util.List; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisGeoOperations { public int geoadd(String key, double longitude, double latitude, String member); public String geohash(String key, String member); public double[] geopos(String key, String member);
public Double geodist(String key, String member1, String member2, DryRedisGeoUnit unit);
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisStringOperations.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // }
import java.util.List; import java.util.Map; import com.sangupta.dryredis.support.DryRedisBitOperation; import java.util.Collection;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisStringOperations { int append(String key, String value); long incr(String key); long incrby(String key, long delta); double incrbyfloat(String key, double delta); List<String> mget(String[] keys); List<String> mget(Collection<String> keys); String set(String key, String value); String setnx(String key, String value); String setxx(String key, String value); String getrange(String key, int start, int end); int setrange(String key, int offset, String value); long bitcount(String key); long bitcount(String key, int start, int end); long decr(String key); long decrby(String key, long delta); String get(String key); int strlen(String key); String getset(String key, String value);
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisStringOperations.java import java.util.List; import java.util.Map; import com.sangupta.dryredis.support.DryRedisBitOperation; import java.util.Collection; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisStringOperations { int append(String key, String value); long incr(String key); long incrby(String key, long delta); double incrbyfloat(String key, double delta); List<String> mget(String[] keys); List<String> mget(Collection<String> keys); String set(String key, String value); String setnx(String key, String value); String setxx(String key, String value); String getrange(String key, int start, int end); int setrange(String key, int offset, String value); long bitcount(String key); long bitcount(String key, int start, int end); long decr(String key); long decrby(String key, long delta); String get(String key); int strlen(String key); String getset(String key, String value);
int bitop(DryRedisBitOperation operation, String destinationKey, String sourceKey, String... otherKeys);
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder;
for(String key : keys) { matchKeyType(key, DryRedisCacheType.HYPER_LOG_LOG); } return this.hyperLogLogCommands.pfmerge(destination, keys); } // LIST commands public String blpop(String key, int maxSecondsToBlock) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.blpop(key, maxSecondsToBlock); } public String brpop(String key, int maxSecondsToBlock) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.brpop(key, maxSecondsToBlock); } public String brpoplpush(String source, String destination, int maxSecondsToBlock) { matchKeyType(source, DryRedisCacheType.LIST); matchKeyType(destination, DryRedisCacheType.LIST); return this.listCommands.brpoplpush(source, destination, maxSecondsToBlock); } public String lindex(String key, int index) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.lindex(key, index); }
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder; for(String key : keys) { matchKeyType(key, DryRedisCacheType.HYPER_LOG_LOG); } return this.hyperLogLogCommands.pfmerge(destination, keys); } // LIST commands public String blpop(String key, int maxSecondsToBlock) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.blpop(key, maxSecondsToBlock); } public String brpop(String key, int maxSecondsToBlock) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.brpop(key, maxSecondsToBlock); } public String brpoplpush(String source, String destination, int maxSecondsToBlock) { matchKeyType(source, DryRedisCacheType.LIST); matchKeyType(destination, DryRedisCacheType.LIST); return this.listCommands.brpoplpush(source, destination, maxSecondsToBlock); } public String lindex(String key, int index) { matchKeyType(key, DryRedisCacheType.LIST); return this.listCommands.lindex(key, index); }
public int linsert(String key, DryRedisInsertOrder order, String pivot, String value) {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder;
return this.sortedSetCommands.zremrangebylex(key, min, max); } public int zremrangebyrank(String key, int start, int stop) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zremrangebyrank(key, start, stop); } public int zremrangebyscore(String key, DryRedisRangeArgument min, DryRedisRangeArgument max) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zremrangebyscore(key, min, max); } public List<String> zrevrange(String key, int start, int stop, boolean withScores) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zrevrange(key, start, stop, withScores); } public int zinterstore(String destination, List<String> keys) { if(keys == null) { return 0; } for(String key : keys) { matchKeyType(key, DryRedisCacheType.SORTED_SET); } return this.sortedSetCommands.zinterstore(destination, keys); }
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder; return this.sortedSetCommands.zremrangebylex(key, min, max); } public int zremrangebyrank(String key, int start, int stop) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zremrangebyrank(key, start, stop); } public int zremrangebyscore(String key, DryRedisRangeArgument min, DryRedisRangeArgument max) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zremrangebyscore(key, min, max); } public List<String> zrevrange(String key, int start, int stop, boolean withScores) { matchKeyType(key, DryRedisCacheType.SORTED_SET); return this.sortedSetCommands.zrevrange(key, start, stop, withScores); } public int zinterstore(String destination, List<String> keys) { if(keys == null) { return 0; } for(String key : keys) { matchKeyType(key, DryRedisCacheType.SORTED_SET); } return this.sortedSetCommands.zinterstore(destination, keys); }
public int zinterstore(String destination, List<String> keys, double[] weights, DryRedisSetAggregationType aggregation) {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder;
public long decr(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.decr(key); } public long decrby(String key, long delta) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.decrby(key, delta); } public String get(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.get(key); } public int strlen(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.strlen(key); } public String getset(String key, String value) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.getset(key, value); } public long bitcount(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.bitcount(key); }
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisBitOperation.java // public enum DryRedisBitOperation { // // AND, // // OR, // // XOR, // // NOT; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisGeoUnit.java // public enum DryRedisGeoUnit { // // Meters, // // KiloMeters, // // Miles, // // Feet; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisOperationFacade.java import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisBitOperation; import com.sangupta.dryredis.support.DryRedisCacheType; import com.sangupta.dryredis.support.DryRedisGeoUnit; import com.sangupta.dryredis.support.DryRedisInsertOrder; public long decr(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.decr(key); } public long decrby(String key, long delta) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.decrby(key, delta); } public String get(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.get(key); } public int strlen(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.strlen(key); } public String getset(String key, String value) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.getset(key, value); } public long bitcount(String key) { matchKeyType(key, DryRedisCacheType.STRING); return this.stringCommands.bitcount(key); }
public int bitop(DryRedisBitOperation operation, String destinationKey, String sourceKey, String... otherKeys) {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisAbstractCache.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisUtils.java // public class DryRedisUtils { // // private static final Charset UTF_8 = Charset.forName("UTF-8"); // // public static <V> List<V> subList(List<V> list, int start, int stop) { // return list.subList(start, stop); // } // // public static byte[] createDump(DryRedisCacheType cacheType, String key, Object value) { // ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // // outStream.write(DryRedis.DRY_REDIS_DUMP_VERSION); // outStream.write(cacheType.getCode()); // // // write the key // outStream.write(key.length()); // try { // outStream.write(key.getBytes(UTF_8)); // } catch (IOException e) { // // eat up // } // // // write a dummy length for now // final int pointer = outStream.size(); // outStream.write(0); // // // write the object itself // try { // ObjectOutputStream objectStream = new ObjectOutputStream(outStream); // objectStream.writeObject(value); // objectStream.close(); // } catch (IOException e) { // // eat up // } // // final int bytesWrittenForObject = outStream.size() - pointer; // // byte[] bytes = outStream.toByteArray(); // // // TODO: write the bytes written for object to the // // // TODO: write and compute checksum // // return bytes; // } // // public static boolean wildcardMatch(String string, String pattern) { // int i = 0; // int j = 0; // int starIndex = -1; // int iIndex = -1; // // while (i < string.length()) { // if (j < pattern.length() && (pattern.charAt(j) == '?' || pattern.charAt(j) == string.charAt(i))) { // ++i; // ++j; // } else if (j < pattern.length() && pattern.charAt(j) == '*') { // starIndex = j; // iIndex = i; // j++; // } else if (starIndex != -1) { // j = starIndex + 1; // i = iIndex+1; // iIndex++; // } else { // return false; // } // } // // while (j < pattern.length() && pattern.charAt(j) == '*') { // ++j; // } // // return j == pattern.length(); // } // // public static int getNextBit(byte[] bytes, boolean onOrOff, int start, int end) { // throw new RuntimeException("not yet implemented"); // } // // }
import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisUtils;
* Check if a key has expired or not. * * @param key * @return */ protected boolean isExpired(String key) { Long expiry = EXPIRE_TIMES.get(key); if(expiry == null) { return false; } long value = expiry.longValue(); if(System.currentTimeMillis() >= value) { return true; } return false; } @Override public int del(String keyPattern) { if(keyPattern.contains("*") || keyPattern.contains("?")) { // wildcard-match Set<String> keySet = this.store.keySet(); if(keySet == null || keySet.isEmpty()) { return 0; } Set<String> toRemove = new HashSet<String>(); for(String key : keySet) {
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisUtils.java // public class DryRedisUtils { // // private static final Charset UTF_8 = Charset.forName("UTF-8"); // // public static <V> List<V> subList(List<V> list, int start, int stop) { // return list.subList(start, stop); // } // // public static byte[] createDump(DryRedisCacheType cacheType, String key, Object value) { // ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // // outStream.write(DryRedis.DRY_REDIS_DUMP_VERSION); // outStream.write(cacheType.getCode()); // // // write the key // outStream.write(key.length()); // try { // outStream.write(key.getBytes(UTF_8)); // } catch (IOException e) { // // eat up // } // // // write a dummy length for now // final int pointer = outStream.size(); // outStream.write(0); // // // write the object itself // try { // ObjectOutputStream objectStream = new ObjectOutputStream(outStream); // objectStream.writeObject(value); // objectStream.close(); // } catch (IOException e) { // // eat up // } // // final int bytesWrittenForObject = outStream.size() - pointer; // // byte[] bytes = outStream.toByteArray(); // // // TODO: write the bytes written for object to the // // // TODO: write and compute checksum // // return bytes; // } // // public static boolean wildcardMatch(String string, String pattern) { // int i = 0; // int j = 0; // int starIndex = -1; // int iIndex = -1; // // while (i < string.length()) { // if (j < pattern.length() && (pattern.charAt(j) == '?' || pattern.charAt(j) == string.charAt(i))) { // ++i; // ++j; // } else if (j < pattern.length() && pattern.charAt(j) == '*') { // starIndex = j; // iIndex = i; // j++; // } else if (starIndex != -1) { // j = starIndex + 1; // i = iIndex+1; // iIndex++; // } else { // return false; // } // } // // while (j < pattern.length() && pattern.charAt(j) == '*') { // ++j; // } // // return j == pattern.length(); // } // // public static int getNextBit(byte[] bytes, boolean onOrOff, int start, int end) { // throw new RuntimeException("not yet implemented"); // } // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisAbstractCache.java import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisUtils; * Check if a key has expired or not. * * @param key * @return */ protected boolean isExpired(String key) { Long expiry = EXPIRE_TIMES.get(key); if(expiry == null) { return false; } long value = expiry.longValue(); if(System.currentTimeMillis() >= value) { return true; } return false; } @Override public int del(String keyPattern) { if(keyPattern.contains("*") || keyPattern.contains("?")) { // wildcard-match Set<String> keySet = this.store.keySet(); if(keySet == null || keySet.isEmpty()) { return 0; } Set<String> toRemove = new HashSet<String>(); for(String key : keySet) {
if(DryRedisUtils.wildcardMatch(key, keyPattern)) {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisListOperations.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // }
import com.sangupta.dryredis.support.DryRedisInsertOrder; import java.util.List;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisListOperations { String blpop(String key, int maxSecondsToBlock); String brpop(String key, int maxSecondsToBlock); String brpoplpush(String source, String destination, int maxSecondsToBlock); String lindex(String key, int index);
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisInsertOrder.java // public enum DryRedisInsertOrder { // // BEFORE, // // AFTER; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisListOperations.java import com.sangupta.dryredis.support.DryRedisInsertOrder; import java.util.List; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisListOperations { String blpop(String key, int maxSecondsToBlock); String brpop(String key, int maxSecondsToBlock); String brpoplpush(String source, String destination, int maxSecondsToBlock); String lindex(String key, int index);
int linsert(String key, DryRedisInsertOrder order, String pivot, String value);
sangupta/dry-redis
src/test/java/com/sangupta/dryredis/TestDryRedisSortedSet.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import org.junit.Test; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import org.junit.Assert;
public void testZRANGEBYLEX() { DryRedisSortedSetOperations redis = getRedis(); redis.zadd("key", 0, "a"); redis.zadd("key", 0, "b"); redis.zadd("key", 0, "c"); redis.zadd("key", 0, "d"); redis.zadd("key", 0, "e"); redis.zadd("key", 0, "f"); redis.zadd("key", 0, "g"); Assert.assertEquals(TestUtils.asList("a", "b", "c", "d", "e", "f", "g"), redis.zrangebylex("key", "-", "+")); Assert.assertEquals(TestUtils.asList("a", "b", "c"), redis.zrangebylex("key", "-", "[c")); Assert.assertEquals(TestUtils.asList("b", "c", "d", "e"), redis.zrangebylex("key", "[aaa", "(f")); } @Test public void testZINTERSTORE() { DryRedisSortedSetOperations redis = getRedis(); // same keys redis.zadd("key1", 1, "a"); redis.zadd("key1", 2, "b"); redis.zadd("key2", 3, "a"); redis.zadd("key2", 4, "b"); redis.zadd("key3", 3, "c"); // sum aggregate
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/test/java/com/sangupta/dryredis/TestDryRedisSortedSet.java import org.junit.Test; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import org.junit.Assert; public void testZRANGEBYLEX() { DryRedisSortedSetOperations redis = getRedis(); redis.zadd("key", 0, "a"); redis.zadd("key", 0, "b"); redis.zadd("key", 0, "c"); redis.zadd("key", 0, "d"); redis.zadd("key", 0, "e"); redis.zadd("key", 0, "f"); redis.zadd("key", 0, "g"); Assert.assertEquals(TestUtils.asList("a", "b", "c", "d", "e", "f", "g"), redis.zrangebylex("key", "-", "+")); Assert.assertEquals(TestUtils.asList("a", "b", "c"), redis.zrangebylex("key", "-", "[c")); Assert.assertEquals(TestUtils.asList("b", "c", "d", "e"), redis.zrangebylex("key", "[aaa", "(f")); } @Test public void testZINTERSTORE() { DryRedisSortedSetOperations redis = getRedis(); // same keys redis.zadd("key1", 1, "a"); redis.zadd("key1", 2, "b"); redis.zadd("key2", 3, "a"); redis.zadd("key2", 4, "b"); redis.zadd("key3", 3, "c"); // sum aggregate
Assert.assertEquals(2, redis.zinterstore("result", TestUtils.asList("key1", "key2"), new double[] { 2.0d, 3.0d }, DryRedisSetAggregationType.SUM));
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/ds/SortedSetWithPriority.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet;
public <T> T[] toArray(T[] a) { return this.delegate.toArray(a); } @Override public boolean add(ElementWithPriority<E> e) { // ordering is important here boolean added = this.delegate.add(e); if(added) { this.priorities.put(e, e.getPriority()); } return added; } @Override public boolean remove(Object o) { boolean removed = this.delegate.remove(o); if(removed) { this.priorities.remove(o); } return removed; } @Override public boolean containsAll(Collection<?> c) { return this.delegate.containsAll(c); }
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/ds/SortedSetWithPriority.java import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; public <T> T[] toArray(T[] a) { return this.delegate.toArray(a); } @Override public boolean add(ElementWithPriority<E> e) { // ordering is important here boolean added = this.delegate.add(e); if(added) { this.priorities.put(e, e.getPriority()); } return added; } @Override public boolean remove(Object o) { boolean removed = this.delegate.remove(o); if(removed) { this.priorities.remove(o); } return removed; } @Override public boolean containsAll(Collection<?> c) { return this.delegate.containsAll(c); }
public boolean addAll(SortedSetWithPriority<E> set, double weight, DryRedisSetAggregationType aggregation) {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisHash.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType;
if(map == null) { return null; } List<String> list = new ArrayList<String>(); for(String field : fields) { list.add(map.get(field)); } return list; } /* (non-Javadoc) * @see com.sangupta.dryredis.DryRedisHashOperations#hmset(java.lang.String, java.util.Map) */ @Override public String hmset(String key, Map<String, String> fieldValues) { Map<String, String> map = this.store.get(key); if(map == null) { map = new HashMap<String, String>(); this.store.put(key, map); } map.putAll(fieldValues); return "OK"; } // commands for DryRedisCache @Override
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisCache.java // public interface DryRedisCache { // // /** // * Delete the keys matching the pattern and return the number of keys // * removed. // * // * @param key // * the key to remove // * // * @return the number of keys removed // */ // public int del(String key); // // /** // * Get the {@link DryRedisCacheType} for this cache. // * // * @return the {@link DryRedisCacheType} for this cache // */ // public DryRedisCacheType getType(); // // /** // * Check if a key is present in this cache or not. // * // * @param key // * the key being looked for // * // * @return <code>true</code> if found, <code>false</code> otherwise // */ // public boolean hasKey(String key); // // public void keys(String pattern, List<String> keys); // // /** // * Dump the value stored against the key so that it can be later restored // * using the RESTORE command. // * // * @param key // * the key to dump // * // * @return the byte-array representation // */ // public byte[] dump(String key); // // /** // * Rename the given key to the new key name. // * // * @param key // * the source key name // * // * @param newKey // * the destiantion key name // */ // public void rename(String key, String newKey); // // /** // * Flush the entire cache for the database. // * // */ // public void flushCache(); // // public int pexpireat(String key, long epochAsMilliseconds); // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisCacheType.java // public enum DryRedisCacheType { // // LIST(1), // // SET(2), // // SORTED_SET(3), // // STRING(4), // // HASH(5), // // GEO(6), // // HYPER_LOG_LOG(7); // // private byte code; // // private DryRedisCacheType(int code) { // this.code = (byte) code; // } // // public byte getCode() { // return this.code; // } // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisHash.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.sangupta.dryredis.support.DryRedisCache; import com.sangupta.dryredis.support.DryRedisCacheType; if(map == null) { return null; } List<String> list = new ArrayList<String>(); for(String field : fields) { list.add(map.get(field)); } return list; } /* (non-Javadoc) * @see com.sangupta.dryredis.DryRedisHashOperations#hmset(java.lang.String, java.util.Map) */ @Override public String hmset(String key, Map<String, String> fieldValues) { Map<String, String> map = this.store.get(key); if(map == null) { map = new HashMap<String, String>(); this.store.put(key, map); } map.putAll(fieldValues); return "OK"; } // commands for DryRedisCache @Override
public DryRedisCacheType getType() {
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/support/DryRedisUtils.java
// Path: src/main/java/com/sangupta/dryredis/DryRedis.java // public class DryRedis extends DryRedisOperationFacade { // // public static final int DRY_REDIS_DUMP_VERSION = 1; // // private static final Map<String, DryRedis> INSTANCES = new HashMap<String, DryRedis>(); // // /** // * The default database // */ // private static final DryRedis DEFAULT_DATABASE = new DryRedis(); // // /** // * Private constructor - needed to make sure that people // * use the {@link #getDatabase(String)} method to obtain instance. // */ // private DryRedis() { // // do nothing // } // // public static DryRedis getDatabase() { // return DEFAULT_DATABASE; // } // // /** // * Get the {@link DryRedis} instance for the given database. For a given // * name the same database instance is returned always. // * // * @param dbName // * the name of the database // * // * @return the {@link DryRedis} instance for that database // */ // public static DryRedis getDatabase(String dbName) { // if(dbName == null || dbName.trim().isEmpty()) { // return DEFAULT_DATABASE; // } // // DryRedis instance = INSTANCES.get(dbName); // if(instance != null) { // return instance; // } // // instance = new DryRedis(); // INSTANCES.put(dbName, instance); // return instance; // } // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.Charset; import java.util.List; import com.sangupta.dryredis.DryRedis;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis.support; public class DryRedisUtils { private static final Charset UTF_8 = Charset.forName("UTF-8"); public static <V> List<V> subList(List<V> list, int start, int stop) { return list.subList(start, stop); } public static byte[] createDump(DryRedisCacheType cacheType, String key, Object value) { ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Path: src/main/java/com/sangupta/dryredis/DryRedis.java // public class DryRedis extends DryRedisOperationFacade { // // public static final int DRY_REDIS_DUMP_VERSION = 1; // // private static final Map<String, DryRedis> INSTANCES = new HashMap<String, DryRedis>(); // // /** // * The default database // */ // private static final DryRedis DEFAULT_DATABASE = new DryRedis(); // // /** // * Private constructor - needed to make sure that people // * use the {@link #getDatabase(String)} method to obtain instance. // */ // private DryRedis() { // // do nothing // } // // public static DryRedis getDatabase() { // return DEFAULT_DATABASE; // } // // /** // * Get the {@link DryRedis} instance for the given database. For a given // * name the same database instance is returned always. // * // * @param dbName // * the name of the database // * // * @return the {@link DryRedis} instance for that database // */ // public static DryRedis getDatabase(String dbName) { // if(dbName == null || dbName.trim().isEmpty()) { // return DEFAULT_DATABASE; // } // // DryRedis instance = INSTANCES.get(dbName); // if(instance != null) { // return instance; // } // // instance = new DryRedis(); // INSTANCES.put(dbName, instance); // return instance; // } // // } // Path: src/main/java/com/sangupta/dryredis/support/DryRedisUtils.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.Charset; import java.util.List; import com.sangupta.dryredis.DryRedis; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis.support; public class DryRedisUtils { private static final Charset UTF_8 = Charset.forName("UTF-8"); public static <V> List<V> subList(List<V> list, int start, int stop) { return list.subList(start, stop); } public static byte[] createDump(DryRedisCacheType cacheType, String key, Object value) { ByteArrayOutputStream outStream = new ByteArrayOutputStream();
outStream.write(DryRedis.DRY_REDIS_DUMP_VERSION);
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisSortedSetOperations.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import java.util.Set; import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.List;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisSortedSetOperations { public int zadd(String key, double score, String member); public long zcard(String key); public long zcount(String key, double min, double max); public double zincrby(String key, double increment, String member); public Integer zrank(String key, String member); public Integer zrevrank(String key, String member); public int zrem(String key, String member); public int zrem(String key, Set<String> members); public Double zscore(String key, String member); public List<String> zrange(String key, int start, int stop, boolean withScores); public List<String> zrangebylex(String key, String min, String max);
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisSortedSetOperations.java import java.util.Set; import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.List; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisSortedSetOperations { public int zadd(String key, double score, String member); public long zcard(String key); public long zcount(String key, double min, double max); public double zincrby(String key, double increment, String member); public Integer zrank(String key, String member); public Integer zrevrank(String key, String member); public int zrem(String key, String member); public int zrem(String key, Set<String> members); public Double zscore(String key, String member); public List<String> zrange(String key, int start, int stop, boolean withScores); public List<String> zrangebylex(String key, String min, String max);
public List<String> zrangebylex(String key, DryRedisRangeArgument min, DryRedisRangeArgument max);
sangupta/dry-redis
src/main/java/com/sangupta/dryredis/DryRedisSortedSetOperations.java
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // }
import java.util.Set; import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.List;
/** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisSortedSetOperations { public int zadd(String key, double score, String member); public long zcard(String key); public long zcount(String key, double min, double max); public double zincrby(String key, double increment, String member); public Integer zrank(String key, String member); public Integer zrevrank(String key, String member); public int zrem(String key, String member); public int zrem(String key, Set<String> members); public Double zscore(String key, String member); public List<String> zrange(String key, int start, int stop, boolean withScores); public List<String> zrangebylex(String key, String min, String max); public List<String> zrangebylex(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public List<String> zrevrangebylex(String key, String min, String max); public List<String> zrevrangebylex(String key, DryRedisRangeArgument max, DryRedisRangeArgument min); public int zlexcount(String key, String min, String max); public int zlexcount(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public int zremrangebylex(String key, String min, String max); public int zremrangebylex(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public int zremrangebyrank(String key, int start, int stop); public int zremrangebyscore(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public List<String> zrevrange(String key, int start, int stop, boolean withScores); public int zinterstore(String destination, List<String> keys);
// Path: src/main/java/com/sangupta/dryredis/support/DryRedisRangeArgument.java // public class DryRedisRangeArgument { // // private final boolean infinity; // // private final boolean inclusive; // // private final String value; // // public DryRedisRangeArgument(String value) { // if(value.equals("-")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // if(value.equals("+")) { // this.inclusive = true; // this.infinity = true; // this.value = value; // return; // } // // this.infinity = false; // // if(value.startsWith("(") || value.startsWith("[")) { // this.value = value.substring(1); // } else { // this.value = value; // } // // this.inclusive = value.startsWith("["); // } // // public boolean lessThan(String s) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare <= 0; // } // // return compare < 0; // } // // public boolean lessThan(double score) { // if(this.infinity) { // if("-".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value <= score; // } // // return value < score; // } // // public boolean greaterThan(String s) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // int compare = this.value.compareTo(s); // if(this.inclusive) { // return compare >= 0; // } // // return compare > 0; // } // // public boolean greaterThan(double score) { // if(this.infinity) { // if("+".equals(this.value)) { // return true; // } // // return false; // } // // double value = Double.parseDouble(this.value); // if(this.inclusive) { // return value >= score; // } // // return value > score; // } // // public boolean isInclusive() { // return this.inclusive; // } // // public String getValue() { // return this.value; // } // // } // // Path: src/main/java/com/sangupta/dryredis/support/DryRedisSetAggregationType.java // public enum DryRedisSetAggregationType { // // SUM, // // MIN, // // MAX; // // } // Path: src/main/java/com/sangupta/dryredis/DryRedisSortedSetOperations.java import java.util.Set; import com.sangupta.dryredis.support.DryRedisRangeArgument; import com.sangupta.dryredis.support.DryRedisSetAggregationType; import java.util.List; /** * * dry-redis: In-memory pure java implementation to Redis * Copyright (c) 2016, Sandeep Gupta * * http://sangupta.com/projects/dry-redis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.sangupta.dryredis; interface DryRedisSortedSetOperations { public int zadd(String key, double score, String member); public long zcard(String key); public long zcount(String key, double min, double max); public double zincrby(String key, double increment, String member); public Integer zrank(String key, String member); public Integer zrevrank(String key, String member); public int zrem(String key, String member); public int zrem(String key, Set<String> members); public Double zscore(String key, String member); public List<String> zrange(String key, int start, int stop, boolean withScores); public List<String> zrangebylex(String key, String min, String max); public List<String> zrangebylex(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public List<String> zrevrangebylex(String key, String min, String max); public List<String> zrevrangebylex(String key, DryRedisRangeArgument max, DryRedisRangeArgument min); public int zlexcount(String key, String min, String max); public int zlexcount(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public int zremrangebylex(String key, String min, String max); public int zremrangebylex(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public int zremrangebyrank(String key, int start, int stop); public int zremrangebyscore(String key, DryRedisRangeArgument min, DryRedisRangeArgument max); public List<String> zrevrange(String key, int start, int stop, boolean withScores); public int zinterstore(String destination, List<String> keys);
public int zinterstore(String destination, List<String> keys, double[] weights, DryRedisSetAggregationType aggregation);
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderForBasicTypesTest.java
// Path: spring-wadl-generator/src/main/java/com/autentia/xml/namespace/QNameBuilder.java // public class QNameBuilder { // // private static final Logger logger = LoggerFactory.getLogger(QNameBuilder.class); // // private static final Pattern BY_DOTS = Pattern.compile("\\."); // private static final Pattern VOWELS = Pattern.compile("[aeiou]"); // private static final QName EMPTY_Q_NAME = new QName("", "", ""); // // private final QNameMemory memory; // // public QNameBuilder(QNameMemory memory) { // this.memory = memory; // } // // public QName buildFor(Class<?> classType) { // return discoverQNameAndCachesIt(classType, "", "", memory.forSingleTypes()); // } // // public QName buildForCollectionOf(Class<?> clazz) { // return discoverQNameAndCachesIt(clazz, "Collection", "cll", memory.forCollectionTypes()); // } // // private QName discoverQNameAndCachesIt(Class<?> classType, String classTypeNameSuffix, String prefixSuffix, QNamesCache cache) { // QName qName = cache.getQNameFor(classType); // if (qName == null) { // qName = discoverQNameFromJaxb(classType); // // final String localPart = (isNotBlank(qName.getLocalPart()) ? qName.getLocalPart() : discoverLocalPartFor(classType)) + classTypeNameSuffix; // final String namespaceUri = isNotBlank(qName.getNamespaceURI()) ? qName.getNamespaceURI() : discoverNamespaceUriFor(classType, localPart); // final String prefix = isNotBlank(qName.getPrefix()) ? qName.getPrefix() : discoverPrefixFor(classType, prefixSuffix); // qName = new QName(namespaceUri, localPart, prefix); // // cache.putQNameFor(classType, qName); // } // return qName; // } // // private QName discoverQNameFromJaxb(Class<?> classType) { // QName qName = null; // try { // final JAXBIntrospector jaxbIntrospector = JAXBContext.newInstance(classType).createJAXBIntrospector(); // qName = jaxbIntrospector.getElementName(classType.getConstructor().newInstance()); // // } catch (Exception e) { // // Add e to the logger message because JAXB Exceptions has a lot of information in the toString(). // // and some loggers implementations just print the getMessage(); // logger.warn("Cannot discover QName from JAXB annotations for class: " + classType.getName() // + ". Preparing generic QName." + e, e); // } // // if (qName == null) { // // Could be null if getElementName returned null, or a exception was thrown. // return EMPTY_Q_NAME; // } // return qName; // } // // private String discoverNamespaceUriFor(Class<?> classType, String localPart) { // final String[] classNameSections = BY_DOTS.split(classType.getName()); // return "http://www." + classNameSections[1] + '.' + classNameSections[0] + "/schema/" + localPart; // } // // private String discoverLocalPartFor(Class<?> classType) { // final String classTypeName = classType.getSimpleName(); // return classTypeName.substring(0, 1).toLowerCase() + classTypeName.substring(1); // } // // private String discoverPrefixFor(Class<?> classType, String suffix) { // final String simpleName = classType.getSimpleName(); // final String classNameWithoutVowels = VOWELS.matcher(simpleName.toLowerCase()).replaceAll(""); // final String reducedClassName = classNameWithoutVowels.length() >= 3 ? classNameWithoutVowels : simpleName; // // String prefix = reducedClassName.substring(0, 3) + suffix; // // int i = 4; // int numberedSuffix = 2; // while (memory.forAlreadyUsedPrefixes().contains(prefix)) { // if (i < reducedClassName.length()) { // prefix = reducedClassName.substring(0, i) + suffix; // i++; // // } else { // prefix = reducedClassName.substring(0, 3) + suffix + numberedSuffix; // numberedSuffix++; // } // } // // memory.forAlreadyUsedPrefixes().add(prefix); // return prefix; // } // }
import com.autentia.xml.namespace.QNameBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.xml.namespace.QName; import java.util.Arrays; import java.util.Collection; import java.util.Date; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.namespace; @RunWith(Parameterized.class) public class QNameBuilderForBasicTypesTest {
// Path: spring-wadl-generator/src/main/java/com/autentia/xml/namespace/QNameBuilder.java // public class QNameBuilder { // // private static final Logger logger = LoggerFactory.getLogger(QNameBuilder.class); // // private static final Pattern BY_DOTS = Pattern.compile("\\."); // private static final Pattern VOWELS = Pattern.compile("[aeiou]"); // private static final QName EMPTY_Q_NAME = new QName("", "", ""); // // private final QNameMemory memory; // // public QNameBuilder(QNameMemory memory) { // this.memory = memory; // } // // public QName buildFor(Class<?> classType) { // return discoverQNameAndCachesIt(classType, "", "", memory.forSingleTypes()); // } // // public QName buildForCollectionOf(Class<?> clazz) { // return discoverQNameAndCachesIt(clazz, "Collection", "cll", memory.forCollectionTypes()); // } // // private QName discoverQNameAndCachesIt(Class<?> classType, String classTypeNameSuffix, String prefixSuffix, QNamesCache cache) { // QName qName = cache.getQNameFor(classType); // if (qName == null) { // qName = discoverQNameFromJaxb(classType); // // final String localPart = (isNotBlank(qName.getLocalPart()) ? qName.getLocalPart() : discoverLocalPartFor(classType)) + classTypeNameSuffix; // final String namespaceUri = isNotBlank(qName.getNamespaceURI()) ? qName.getNamespaceURI() : discoverNamespaceUriFor(classType, localPart); // final String prefix = isNotBlank(qName.getPrefix()) ? qName.getPrefix() : discoverPrefixFor(classType, prefixSuffix); // qName = new QName(namespaceUri, localPart, prefix); // // cache.putQNameFor(classType, qName); // } // return qName; // } // // private QName discoverQNameFromJaxb(Class<?> classType) { // QName qName = null; // try { // final JAXBIntrospector jaxbIntrospector = JAXBContext.newInstance(classType).createJAXBIntrospector(); // qName = jaxbIntrospector.getElementName(classType.getConstructor().newInstance()); // // } catch (Exception e) { // // Add e to the logger message because JAXB Exceptions has a lot of information in the toString(). // // and some loggers implementations just print the getMessage(); // logger.warn("Cannot discover QName from JAXB annotations for class: " + classType.getName() // + ". Preparing generic QName." + e, e); // } // // if (qName == null) { // // Could be null if getElementName returned null, or a exception was thrown. // return EMPTY_Q_NAME; // } // return qName; // } // // private String discoverNamespaceUriFor(Class<?> classType, String localPart) { // final String[] classNameSections = BY_DOTS.split(classType.getName()); // return "http://www." + classNameSections[1] + '.' + classNameSections[0] + "/schema/" + localPart; // } // // private String discoverLocalPartFor(Class<?> classType) { // final String classTypeName = classType.getSimpleName(); // return classTypeName.substring(0, 1).toLowerCase() + classTypeName.substring(1); // } // // private String discoverPrefixFor(Class<?> classType, String suffix) { // final String simpleName = classType.getSimpleName(); // final String classNameWithoutVowels = VOWELS.matcher(simpleName.toLowerCase()).replaceAll(""); // final String reducedClassName = classNameWithoutVowels.length() >= 3 ? classNameWithoutVowels : simpleName; // // String prefix = reducedClassName.substring(0, 3) + suffix; // // int i = 4; // int numberedSuffix = 2; // while (memory.forAlreadyUsedPrefixes().contains(prefix)) { // if (i < reducedClassName.length()) { // prefix = reducedClassName.substring(0, i) + suffix; // i++; // // } else { // prefix = reducedClassName.substring(0, 3) + suffix + numberedSuffix; // numberedSuffix++; // } // } // // memory.forAlreadyUsedPrefixes().add(prefix); // return prefix; // } // } // Path: spring-wadl-generator/src/test/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderForBasicTypesTest.java import com.autentia.xml.namespace.QNameBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.xml.namespace.QName; import java.util.Arrays; import java.util.Collection; import java.util.Date; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.namespace; @RunWith(Parameterized.class) public class QNameBuilderForBasicTypesTest {
private static final QNameBuilder Q_NAME_BUILDER = new QNameBuilderFactory().getBuilder();
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/lang/ClassMetadataForCollectionsTest.java
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // }
import com.autentia.dummy.Contact; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.typeCompatibleWith; import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; @RunWith(Parameterized.class) public class ClassMetadataForCollectionsTest { private final ClassMetadata classMetadata; private final Class<? extends Collection<?>> expectedCollectionClass; private final Class<?> expectedComponentClass; @Parameters public static Collection<Object[]> parameters() throws Exception { return Arrays.asList(new Object[][]{ {new ClassMetadataFromReturnType(DummyClass.class.getDeclaredMethod("returnsCollection", Collection.class)), Set.class, Integer.class}, {new ClassMetadataFromParam(DummyClass.class.getDeclaredMethod("returnsCollection", Collection.class), 0),
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // } // Path: spring-wadl-generator/src/test/java/com/autentia/lang/ClassMetadataForCollectionsTest.java import com.autentia.dummy.Contact; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.typeCompatibleWith; import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; @RunWith(Parameterized.class) public class ClassMetadataForCollectionsTest { private final ClassMetadata classMetadata; private final Class<? extends Collection<?>> expectedCollectionClass; private final Class<?> expectedComponentClass; @Parameters public static Collection<Object[]> parameters() throws Exception { return Arrays.asList(new Object[][]{ {new ClassMetadataFromReturnType(DummyClass.class.getDeclaredMethod("returnsCollection", Collection.class)), Set.class, Integer.class}, {new ClassMetadataFromParam(DummyClass.class.getDeclaredMethod("returnsCollection", Collection.class), 0),
Collection.class, Contact.class},
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/IncludeBuilder.java
// Path: spring-wadl-generator/src/main/java/net/java/dev/wadl/_2009/_02/Include.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "doc" // }) // @XmlRootElement(name = "include") // public class Include { // // protected List<Doc> doc; // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAnyAttribute // private Map<QName, String> otherAttributes = new HashMap<QName, String>(); // // /** // * Default no-arg constructor // * // */ // public Include() { // super(); // } // // /** // * Fully-initialising value constructor // * // */ // public Include(final List<Doc> doc, final String href, final Map<QName, String> otherAttributes) { // this.doc = doc; // this.href = href; // this.otherAttributes = otherAttributes; // } // // /** // * Gets the value of the doc property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the doc property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getDoc().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Doc } // * // * // */ // public List<Doc> getDoc() { // if (doc == null) { // doc = new ArrayList<Doc>(); // } // return this.doc; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets a map that contains attributes that aren't bound to any typed property on this class. // * // * <p> // * the map is keyed by the name of the attribute and // * the value is the string value of the attribute. // * // * the map returned by this method is live, and you can add new attribute // * by updating the map directly. Because of this design, there's no setter. // * // * // * @return // * always non-null // */ // public Map<QName, String> getOtherAttributes() { // return otherAttributes; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // // @Override // public boolean equals(Object that) { // return EqualsBuilder.reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // public Include withDoc(Doc... values) { // if (values!= null) { // for (Doc value: values) { // getDoc().add(value); // } // } // return this; // } // // public Include withDoc(Collection<Doc> values) { // if (values!= null) { // getDoc().addAll(values); // } // return this; // } // // public Include withHref(String value) { // setHref(value); // return this; // } // // }
import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import net.java.dev.wadl._2009._02.Include; import java.util.ArrayList; import java.util.Collection; import java.util.List;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; class IncludeBuilder { private final GrammarsDiscoverer grammarsDiscoverer; IncludeBuilder(GrammarsDiscoverer grammarsDiscoverer) { this.grammarsDiscoverer = grammarsDiscoverer; }
// Path: spring-wadl-generator/src/main/java/net/java/dev/wadl/_2009/_02/Include.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "doc" // }) // @XmlRootElement(name = "include") // public class Include { // // protected List<Doc> doc; // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAnyAttribute // private Map<QName, String> otherAttributes = new HashMap<QName, String>(); // // /** // * Default no-arg constructor // * // */ // public Include() { // super(); // } // // /** // * Fully-initialising value constructor // * // */ // public Include(final List<Doc> doc, final String href, final Map<QName, String> otherAttributes) { // this.doc = doc; // this.href = href; // this.otherAttributes = otherAttributes; // } // // /** // * Gets the value of the doc property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the doc property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getDoc().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Doc } // * // * // */ // public List<Doc> getDoc() { // if (doc == null) { // doc = new ArrayList<Doc>(); // } // return this.doc; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets a map that contains attributes that aren't bound to any typed property on this class. // * // * <p> // * the map is keyed by the name of the attribute and // * the value is the string value of the attribute. // * // * the map returned by this method is live, and you can add new attribute // * by updating the map directly. Because of this design, there's no setter. // * // * // * @return // * always non-null // */ // public Map<QName, String> getOtherAttributes() { // return otherAttributes; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // // @Override // public boolean equals(Object that) { // return EqualsBuilder.reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // public Include withDoc(Doc... values) { // if (values!= null) { // for (Doc value: values) { // getDoc().add(value); // } // } // return this; // } // // public Include withDoc(Collection<Doc> values) { // if (values!= null) { // getDoc().addAll(values); // } // return this; // } // // public Include withHref(String value) { // setHref(value); // return this; // } // // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/IncludeBuilder.java import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import net.java.dev.wadl._2009._02.Include; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; class IncludeBuilder { private final GrammarsDiscoverer grammarsDiscoverer; IncludeBuilder(GrammarsDiscoverer grammarsDiscoverer) { this.grammarsDiscoverer = grammarsDiscoverer; }
Collection<Include> build() {
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/web/rest/wadl/builder/IncludeBuilderTest.java
// Path: spring-wadl-generator/src/main/java/net/java/dev/wadl/_2009/_02/Include.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "doc" // }) // @XmlRootElement(name = "include") // public class Include { // // protected List<Doc> doc; // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAnyAttribute // private Map<QName, String> otherAttributes = new HashMap<QName, String>(); // // /** // * Default no-arg constructor // * // */ // public Include() { // super(); // } // // /** // * Fully-initialising value constructor // * // */ // public Include(final List<Doc> doc, final String href, final Map<QName, String> otherAttributes) { // this.doc = doc; // this.href = href; // this.otherAttributes = otherAttributes; // } // // /** // * Gets the value of the doc property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the doc property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getDoc().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Doc } // * // * // */ // public List<Doc> getDoc() { // if (doc == null) { // doc = new ArrayList<Doc>(); // } // return this.doc; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets a map that contains attributes that aren't bound to any typed property on this class. // * // * <p> // * the map is keyed by the name of the attribute and // * the value is the string value of the attribute. // * // * the map returned by this method is live, and you can add new attribute // * by updating the map directly. Because of this design, there's no setter. // * // * // * @return // * always non-null // */ // public Map<QName, String> getOtherAttributes() { // return otherAttributes; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // // @Override // public boolean equals(Object that) { // return EqualsBuilder.reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // public Include withDoc(Doc... values) { // if (values!= null) { // for (Doc value: values) { // getDoc().add(value); // } // } // return this; // } // // public Include withDoc(Collection<Doc> values) { // if (values!= null) { // getDoc().addAll(values); // } // return this; // } // // public Include withHref(String value) { // setHref(value); // return this; // } // // }
import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import net.java.dev.wadl._2009._02.Include; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; public class IncludeBuilderTest { private static final String[] DUMMY_URLS = {"schema/a"}; private final GrammarsDiscoverer grammarsDiscovererMock = Mockito.mock(GrammarsDiscoverer.class); private final IncludeBuilder builder = new IncludeBuilder(grammarsDiscovererMock); @Test public void name() { doReturn(new ArrayList<String>(Arrays.asList(DUMMY_URLS))).when(grammarsDiscovererMock).getSchemaUrlsForComplexTypes();
// Path: spring-wadl-generator/src/main/java/net/java/dev/wadl/_2009/_02/Include.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "doc" // }) // @XmlRootElement(name = "include") // public class Include { // // protected List<Doc> doc; // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAnyAttribute // private Map<QName, String> otherAttributes = new HashMap<QName, String>(); // // /** // * Default no-arg constructor // * // */ // public Include() { // super(); // } // // /** // * Fully-initialising value constructor // * // */ // public Include(final List<Doc> doc, final String href, final Map<QName, String> otherAttributes) { // this.doc = doc; // this.href = href; // this.otherAttributes = otherAttributes; // } // // /** // * Gets the value of the doc property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the doc property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getDoc().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Doc } // * // * // */ // public List<Doc> getDoc() { // if (doc == null) { // doc = new ArrayList<Doc>(); // } // return this.doc; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets a map that contains attributes that aren't bound to any typed property on this class. // * // * <p> // * the map is keyed by the name of the attribute and // * the value is the string value of the attribute. // * // * the map returned by this method is live, and you can add new attribute // * by updating the map directly. Because of this design, there's no setter. // * // * // * @return // * always non-null // */ // public Map<QName, String> getOtherAttributes() { // return otherAttributes; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // // @Override // public boolean equals(Object that) { // return EqualsBuilder.reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // public Include withDoc(Doc... values) { // if (values!= null) { // for (Doc value: values) { // getDoc().add(value); // } // } // return this; // } // // public Include withDoc(Collection<Doc> values) { // if (values!= null) { // getDoc().addAll(values); // } // return this; // } // // public Include withHref(String value) { // setHref(value); // return this; // } // // } // Path: spring-wadl-generator/src/test/java/com/autentia/web/rest/wadl/builder/IncludeBuilderTest.java import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import net.java.dev.wadl._2009._02.Include; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; public class IncludeBuilderTest { private static final String[] DUMMY_URLS = {"schema/a"}; private final GrammarsDiscoverer grammarsDiscovererMock = Mockito.mock(GrammarsDiscoverer.class); private final IncludeBuilder builder = new IncludeBuilder(grammarsDiscovererMock); @Test public void name() { doReturn(new ArrayList<String>(Arrays.asList(DUMMY_URLS))).when(grammarsDiscovererMock).getSchemaUrlsForComplexTypes();
final Collection<Include> expectedIncludes = new ArrayList<Include>();
autentia/wadl-tools
wadl-packaging/wadl-zipper-maven-plugin/src/main/java/com/autentia/maven/plugin/WadlZipperMojo.java
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // public class WadlZipper { // // static final String DEFAULT_WADL_FILENAME = "wadl.xml"; // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // private final URI wadlUri; // // public WadlZipper(String wadlUri) throws URISyntaxException { // this.wadlUri = new URI(wadlUri); // } // // public void saveTo(String zipPathName) throws IOException, URISyntaxException { // saveTo(new File(zipPathName)); // } // // public void saveTo(File zipFile) throws IOException, URISyntaxException { // final HttpClient httpClient = new HttpClient(); // final Zip zip = new Zip(zipFile); // saveTo(httpClient, zip); // } // // /** // * Just for easily inject dependencies on tests. // */ // void saveTo(HttpClient httpClient, Zip zip) throws IOException, URISyntaxException { // try { // final String wadlContent = httpClient.getAsString(wadlUri); // zip.add(DEFAULT_WADL_FILENAME, IOUtils.toInputStream(wadlContent)); // // for (String grammarUri : new GrammarsUrisExtractor().extractFrom(wadlContent)) { // final URI uri = new URI(grammarUri); // final String name = composesGrammarFileNameWith(uri); // final InputStream inputStream = httpClient.getAsStream(wadlUri.resolve(uri)); // zip.add(name, inputStream); // } // // } finally { // zip.close(); // } // } // // private String composesGrammarFileNameWith(URI grammarUri) { // String pathName = ""; // // final String host = grammarUri.getHost(); // if (host != null) { // pathName = host + '/'; // } // // String uriPath = grammarUri.getPath(); // if (uriPath.startsWith("/")) { // uriPath = uriPath.substring(1); // } // pathName += uriPath; // // if (!pathName.toLowerCase().endsWith(DEFAULT_SCHEMA_EXTENSION)) { // pathName += DEFAULT_SCHEMA_EXTENSION; // } // return pathName; // } // }
import com.autentia.web.rest.wadl.zipper.WadlZipper; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import java.io.IOException; import java.net.URISyntaxException;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.maven.plugin; /** * This plugin connects to the URI where WADL is located, then get it and all the related grammars, * and store all in a zip file. */ @Mojo(name = "zip") public class WadlZipperMojo extends AbstractMojo { /** URI of the WADL */ @Parameter(required = true) private String wadlUri; /** Path to the zip file where store all the data. By default is 'target/wadl.zip' */ @Parameter(defaultValue = "${project.build.directory}/wadl.zip") private String zipFile; @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Extracting WADL from: " + wadlUri + ", to zip file: " + zipFile); try {
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // public class WadlZipper { // // static final String DEFAULT_WADL_FILENAME = "wadl.xml"; // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // private final URI wadlUri; // // public WadlZipper(String wadlUri) throws URISyntaxException { // this.wadlUri = new URI(wadlUri); // } // // public void saveTo(String zipPathName) throws IOException, URISyntaxException { // saveTo(new File(zipPathName)); // } // // public void saveTo(File zipFile) throws IOException, URISyntaxException { // final HttpClient httpClient = new HttpClient(); // final Zip zip = new Zip(zipFile); // saveTo(httpClient, zip); // } // // /** // * Just for easily inject dependencies on tests. // */ // void saveTo(HttpClient httpClient, Zip zip) throws IOException, URISyntaxException { // try { // final String wadlContent = httpClient.getAsString(wadlUri); // zip.add(DEFAULT_WADL_FILENAME, IOUtils.toInputStream(wadlContent)); // // for (String grammarUri : new GrammarsUrisExtractor().extractFrom(wadlContent)) { // final URI uri = new URI(grammarUri); // final String name = composesGrammarFileNameWith(uri); // final InputStream inputStream = httpClient.getAsStream(wadlUri.resolve(uri)); // zip.add(name, inputStream); // } // // } finally { // zip.close(); // } // } // // private String composesGrammarFileNameWith(URI grammarUri) { // String pathName = ""; // // final String host = grammarUri.getHost(); // if (host != null) { // pathName = host + '/'; // } // // String uriPath = grammarUri.getPath(); // if (uriPath.startsWith("/")) { // uriPath = uriPath.substring(1); // } // pathName += uriPath; // // if (!pathName.toLowerCase().endsWith(DEFAULT_SCHEMA_EXTENSION)) { // pathName += DEFAULT_SCHEMA_EXTENSION; // } // return pathName; // } // } // Path: wadl-packaging/wadl-zipper-maven-plugin/src/main/java/com/autentia/maven/plugin/WadlZipperMojo.java import com.autentia.web.rest.wadl.zipper.WadlZipper; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import java.io.IOException; import java.net.URISyntaxException; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.maven.plugin; /** * This plugin connects to the URI where WADL is located, then get it and all the related grammars, * and store all in a zip file. */ @Mojo(name = "zip") public class WadlZipperMojo extends AbstractMojo { /** URI of the WADL */ @Parameter(required = true) private String wadlUri; /** Path to the zip file where store all the data. By default is 'target/wadl.zip' */ @Parameter(defaultValue = "${project.build.directory}/wadl.zip") private String zipFile; @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Extracting WADL from: " + wadlUri + ", to zip file: " + zipFile); try {
final WadlZipper wadlZipper = new WadlZipper(wadlUri);
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/lang/DummyClass.java
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // }
import com.autentia.dummy.Contact; import java.util.Collection; import java.util.List; import java.util.Set;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; class DummyClass { private String field; private List<String> fieldCollection;
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // } // Path: spring-wadl-generator/src/test/java/com/autentia/lang/DummyClass.java import com.autentia.dummy.Contact; import java.util.Collection; import java.util.List; import java.util.Set; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; class DummyClass { private String field; private List<String> fieldCollection;
Set<Integer> returnsCollection(Collection<Contact> parameterCollection) {
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/lang/ClassUtilsTest.java
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // }
import com.autentia.dummy.Contact; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.autentia.lang.ClassUtils.*; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.typeCompatibleWith; import static org.junit.Assert.assertThat;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; public class ClassUtilsTest { @Test public void givenSingleType_whenAskIsArrayOrCollection_thenReturnFalse() { assertThat(isArrayOrCollection(String.class), is(false)); assertThat(isArrayOrCollection(Integer.class), is(false));
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/Contact.java // public class Contact { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:complexType name=\"contact\">\n" + // " <xs:sequence/>\n" + // " </xs:complexType>\n" + // "</xs:schema>" + // "\n\n"; // // final String name; // final String email; // // public Contact(String name, String email) { // this.name = name; // this.email = email; // } // // public Contact() { // this("unknown name", "unknown email"); // } // // } // Path: spring-wadl-generator/src/test/java/com/autentia/lang/ClassUtilsTest.java import com.autentia.dummy.Contact; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.autentia.lang.ClassUtils.*; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.typeCompatibleWith; import static org.junit.Assert.assertThat; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.lang; public class ClassUtilsTest { @Test public void givenSingleType_whenAskIsArrayOrCollection_thenReturnFalse() { assertThat(isArrayOrCollection(String.class), is(false)); assertThat(isArrayOrCollection(Integer.class), is(false));
assertThat(isArrayOrCollection(Contact.class), is(false));
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // }
import com.autentia.web.HttpMethod; import org.springframework.http.MediaType; import java.lang.reflect.Method; import java.util.Set;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; public abstract class MethodContext { private final ApplicationContext parentContext; private ParamBuilder paramBuilder; protected MethodContext(ApplicationContext parentContext) { this.parentContext = parentContext; } ApplicationContext getParentContext() { return parentContext; } ParamBuilder getParamBuilder() { return paramBuilder; } void setParamBuilder(ParamBuilder paramBuilder) { this.paramBuilder = paramBuilder; } protected abstract String discoverPath(); protected abstract Method getJavaMethod();
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java import com.autentia.web.HttpMethod; import org.springframework.http.MediaType; import java.lang.reflect.Method; import java.util.Set; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder; public abstract class MethodContext { private final ApplicationContext parentContext; private ParamBuilder paramBuilder; protected MethodContext(ApplicationContext parentContext) { this.parentContext = parentContext; } ApplicationContext getParentContext() { return parentContext; } ParamBuilder getParamBuilder() { return paramBuilder; } void setParamBuilder(ParamBuilder paramBuilder) { this.paramBuilder = paramBuilder; } protected abstract String discoverPath(); protected abstract Method getJavaMethod();
protected abstract Set<HttpMethod> getHttpMethods();
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/xml/schema/CollectionTypeTest.java
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/ContactAnnotated.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class ContactAnnotated { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:element name=\"contactAnnotated\" type=\"contactAnnotated\"/>\n" + // '\n' + // " <xs:complexType name=\"contactAnnotated\">\n" + // " <xs:sequence>\n" + // " <xs:element name=\"name\" type=\"xs:string\" minOccurs=\"0\"/>\n" + // " <xs:element name=\"email\" type=\"xs:string\" minOccurs=\"0\"/>\n" + // " </xs:sequence>\n" + // " </xs:complexType>\n" + // "</xs:schema>\n\n"; // // public static final String EXPECTED_COLLECTION_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:element name=\"contactAnnotatedCollection\" type=\"contactAnnotatedCollection\"/>\n" + // '\n' + // " <xs:complexType name=\"contactAnnotatedCollection\">\n" + // " <xs:sequence>\n" + // " <xs:element name=\"contactAnnotated\" type=\"contactAnnotated\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n" + // " </xs:sequence>\n" + // " </xs:complexType>\n" + // "</xs:schema>\n\n"; // // private final String name; // private final String email; // // public ContactAnnotated(String name, String email) { // this.name = name; // this.email = email; // } // // public ContactAnnotated() { // this("unknown name", "unknown email"); // } // // }
import com.autentia.dummy.ContactAnnotated; import org.junit.Test; import javax.xml.namespace.QName; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.xml.schema; public class CollectionTypeTest { @Test public void givenNameOfComplexTypeCollection_whenBuild_thenReturnSchemaWithTheCollection() {
// Path: spring-wadl-generator/src/test/java/com/autentia/dummy/ContactAnnotated.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class ContactAnnotated { // // public static final String EXPECTED_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:element name=\"contactAnnotated\" type=\"contactAnnotated\"/>\n" + // '\n' + // " <xs:complexType name=\"contactAnnotated\">\n" + // " <xs:sequence>\n" + // " <xs:element name=\"name\" type=\"xs:string\" minOccurs=\"0\"/>\n" + // " <xs:element name=\"email\" type=\"xs:string\" minOccurs=\"0\"/>\n" + // " </xs:sequence>\n" + // " </xs:complexType>\n" + // "</xs:schema>\n\n"; // // public static final String EXPECTED_COLLECTION_SCHEMA = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + // "<xs:schema version=\"1.0\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + // '\n' + // " <xs:element name=\"contactAnnotatedCollection\" type=\"contactAnnotatedCollection\"/>\n" + // '\n' + // " <xs:complexType name=\"contactAnnotatedCollection\">\n" + // " <xs:sequence>\n" + // " <xs:element name=\"contactAnnotated\" type=\"contactAnnotated\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n" + // " </xs:sequence>\n" + // " </xs:complexType>\n" + // "</xs:schema>\n\n"; // // private final String name; // private final String email; // // public ContactAnnotated(String name, String email) { // this.name = name; // this.email = email; // } // // public ContactAnnotated() { // this("unknown name", "unknown email"); // } // // } // Path: spring-wadl-generator/src/test/java/com/autentia/xml/schema/CollectionTypeTest.java import com.autentia.dummy.ContactAnnotated; import org.junit.Test; import javax.xml.namespace.QName; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.xml.schema; public class CollectionTypeTest { @Test public void givenNameOfComplexTypeCollection_whenBuild_thenReturnSchemaWithTheCollection() {
assertThat(new CollectionType(ContactAnnotated[].class, new QName("contactAnnotatedCollection"), new QName("contactAnnotated")).toSchema(),
autentia/wadl-tools
spring-wadl-showcase/src/main/java/com/autentia/showcase/web/rest/contacts/AddressBookController.java
// Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/AddressBook.java // @Service // public class AddressBook { // // private final Map<String, Contact> contacts = new ConcurrentHashMap<String, Contact>(); // // public AddressBook() { // prepareSomeFakeContacts(); // } // // private void prepareSomeFakeContacts() { // save(new Contact("1111-1111-1111-1111", "Scott Summers", "summers@gmail.com")); // save(new Contact("2222-2222-2222-2222", "Peter Parker", "parker@gmail.com")); // save(new Contact("3333-3333-3333-3333", "Steve Rogers", "rogers@gmail.com")); // save(new Contact("4444-4444-4444-4444", "Red Richards", "richards@gmail.com")); // } // // public Collection<Contact> contacts() { // return Collections.unmodifiableCollection(contacts.values()); // } // // public void save(Contact contact) { // if (contact.getId().equals(Contact.NEW)) { // contact = new Contact(generateUUID(), contact); // } // contacts.put(contact.getId(), contact); // } // // private String generateUUID() { // return UUID.randomUUID().toString(); // } // // public Contact load(String contactId) { // return contacts.get(contactId); // } // // public Collection<Contact> filterContactsBy(String name) { // final Collection<Contact> contactsWithName = new ArrayList<Contact>(); // for (Contact contact : contacts.values()) { // if (contact.getName().contains(name)) { // contactsWithName.add(contact); // } // } // return Collections.unmodifiableCollection(contactsWithName); // } // // } // // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/Contact.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class Contact { // // public static final String NEW = "new"; // // private final String id; // private final String name; // private final String email; // // public Contact() { // this("", "", ""); // } // // public Contact(String name, String email) { // this(NEW, name, email); // } // // Contact(String id, String name, String email) { // this.id = id; // this.name = name; // this.email = email; // } // // Contact(String id, Contact contact) { // this(id, contact.name, contact.email); // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // }
import com.autentia.showcase.contacts.AddressBook; import com.autentia.showcase.contacts.Contact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Collection;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.showcase.web.rest.contacts; @Controller @RequestMapping(value = AppRestConstants.REST_SERVICES_LOCATION, produces = AppRestConstants.JSON) public class AddressBookController { private static final Logger logger = LoggerFactory.getLogger(AddressBookController.class);
// Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/AddressBook.java // @Service // public class AddressBook { // // private final Map<String, Contact> contacts = new ConcurrentHashMap<String, Contact>(); // // public AddressBook() { // prepareSomeFakeContacts(); // } // // private void prepareSomeFakeContacts() { // save(new Contact("1111-1111-1111-1111", "Scott Summers", "summers@gmail.com")); // save(new Contact("2222-2222-2222-2222", "Peter Parker", "parker@gmail.com")); // save(new Contact("3333-3333-3333-3333", "Steve Rogers", "rogers@gmail.com")); // save(new Contact("4444-4444-4444-4444", "Red Richards", "richards@gmail.com")); // } // // public Collection<Contact> contacts() { // return Collections.unmodifiableCollection(contacts.values()); // } // // public void save(Contact contact) { // if (contact.getId().equals(Contact.NEW)) { // contact = new Contact(generateUUID(), contact); // } // contacts.put(contact.getId(), contact); // } // // private String generateUUID() { // return UUID.randomUUID().toString(); // } // // public Contact load(String contactId) { // return contacts.get(contactId); // } // // public Collection<Contact> filterContactsBy(String name) { // final Collection<Contact> contactsWithName = new ArrayList<Contact>(); // for (Contact contact : contacts.values()) { // if (contact.getName().contains(name)) { // contactsWithName.add(contact); // } // } // return Collections.unmodifiableCollection(contactsWithName); // } // // } // // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/Contact.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class Contact { // // public static final String NEW = "new"; // // private final String id; // private final String name; // private final String email; // // public Contact() { // this("", "", ""); // } // // public Contact(String name, String email) { // this(NEW, name, email); // } // // Contact(String id, String name, String email) { // this.id = id; // this.name = name; // this.email = email; // } // // Contact(String id, Contact contact) { // this(id, contact.name, contact.email); // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // } // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/web/rest/contacts/AddressBookController.java import com.autentia.showcase.contacts.AddressBook; import com.autentia.showcase.contacts.Contact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Collection; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.showcase.web.rest.contacts; @Controller @RequestMapping(value = AppRestConstants.REST_SERVICES_LOCATION, produces = AppRestConstants.JSON) public class AddressBookController { private static final Logger logger = LoggerFactory.getLogger(AddressBookController.class);
private final AddressBook addressBook;
autentia/wadl-tools
spring-wadl-showcase/src/main/java/com/autentia/showcase/web/rest/contacts/AddressBookController.java
// Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/AddressBook.java // @Service // public class AddressBook { // // private final Map<String, Contact> contacts = new ConcurrentHashMap<String, Contact>(); // // public AddressBook() { // prepareSomeFakeContacts(); // } // // private void prepareSomeFakeContacts() { // save(new Contact("1111-1111-1111-1111", "Scott Summers", "summers@gmail.com")); // save(new Contact("2222-2222-2222-2222", "Peter Parker", "parker@gmail.com")); // save(new Contact("3333-3333-3333-3333", "Steve Rogers", "rogers@gmail.com")); // save(new Contact("4444-4444-4444-4444", "Red Richards", "richards@gmail.com")); // } // // public Collection<Contact> contacts() { // return Collections.unmodifiableCollection(contacts.values()); // } // // public void save(Contact contact) { // if (contact.getId().equals(Contact.NEW)) { // contact = new Contact(generateUUID(), contact); // } // contacts.put(contact.getId(), contact); // } // // private String generateUUID() { // return UUID.randomUUID().toString(); // } // // public Contact load(String contactId) { // return contacts.get(contactId); // } // // public Collection<Contact> filterContactsBy(String name) { // final Collection<Contact> contactsWithName = new ArrayList<Contact>(); // for (Contact contact : contacts.values()) { // if (contact.getName().contains(name)) { // contactsWithName.add(contact); // } // } // return Collections.unmodifiableCollection(contactsWithName); // } // // } // // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/Contact.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class Contact { // // public static final String NEW = "new"; // // private final String id; // private final String name; // private final String email; // // public Contact() { // this("", "", ""); // } // // public Contact(String name, String email) { // this(NEW, name, email); // } // // Contact(String id, String name, String email) { // this.id = id; // this.name = name; // this.email = email; // } // // Contact(String id, Contact contact) { // this(id, contact.name, contact.email); // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // }
import com.autentia.showcase.contacts.AddressBook; import com.autentia.showcase.contacts.Contact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Collection;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.showcase.web.rest.contacts; @Controller @RequestMapping(value = AppRestConstants.REST_SERVICES_LOCATION, produces = AppRestConstants.JSON) public class AddressBookController { private static final Logger logger = LoggerFactory.getLogger(AddressBookController.class); private final AddressBook addressBook; @Autowired public AddressBookController(AddressBook addressBook) { this.addressBook = addressBook; } @RequestMapping(value = "/contacts", method = RequestMethod.GET) @ResponseBody
// Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/AddressBook.java // @Service // public class AddressBook { // // private final Map<String, Contact> contacts = new ConcurrentHashMap<String, Contact>(); // // public AddressBook() { // prepareSomeFakeContacts(); // } // // private void prepareSomeFakeContacts() { // save(new Contact("1111-1111-1111-1111", "Scott Summers", "summers@gmail.com")); // save(new Contact("2222-2222-2222-2222", "Peter Parker", "parker@gmail.com")); // save(new Contact("3333-3333-3333-3333", "Steve Rogers", "rogers@gmail.com")); // save(new Contact("4444-4444-4444-4444", "Red Richards", "richards@gmail.com")); // } // // public Collection<Contact> contacts() { // return Collections.unmodifiableCollection(contacts.values()); // } // // public void save(Contact contact) { // if (contact.getId().equals(Contact.NEW)) { // contact = new Contact(generateUUID(), contact); // } // contacts.put(contact.getId(), contact); // } // // private String generateUUID() { // return UUID.randomUUID().toString(); // } // // public Contact load(String contactId) { // return contacts.get(contactId); // } // // public Collection<Contact> filterContactsBy(String name) { // final Collection<Contact> contactsWithName = new ArrayList<Contact>(); // for (Contact contact : contacts.values()) { // if (contact.getName().contains(name)) { // contactsWithName.add(contact); // } // } // return Collections.unmodifiableCollection(contactsWithName); // } // // } // // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/contacts/Contact.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement // public class Contact { // // public static final String NEW = "new"; // // private final String id; // private final String name; // private final String email; // // public Contact() { // this("", "", ""); // } // // public Contact(String name, String email) { // this(NEW, name, email); // } // // Contact(String id, String name, String email) { // this.id = id; // this.name = name; // this.email = email; // } // // Contact(String id, Contact contact) { // this(id, contact.name, contact.email); // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEmail() { // return email; // } // } // Path: spring-wadl-showcase/src/main/java/com/autentia/showcase/web/rest/contacts/AddressBookController.java import com.autentia.showcase.contacts.AddressBook; import com.autentia.showcase.contacts.Contact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Collection; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.showcase.web.rest.contacts; @Controller @RequestMapping(value = AppRestConstants.REST_SERVICES_LOCATION, produces = AppRestConstants.JSON) public class AddressBookController { private static final Logger logger = LoggerFactory.getLogger(AddressBookController.class); private final AddressBook addressBook; @Autowired public AddressBookController(AddressBook addressBook) { this.addressBook = addressBook; } @RequestMapping(value = "/contacts", method = RequestMethod.GET) @ResponseBody
public Collection<Contact> getAllContacts() {
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // }
import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) {
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) {
final ClassTypeDiscoverer classTypeDiscoverer = new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder());
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // }
import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) {
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) {
final ClassTypeDiscoverer classTypeDiscoverer = new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder());
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // }
import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) { final ClassTypeDiscoverer classTypeDiscoverer = new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder()); final GrammarsDiscoverer grammarsDiscoverer = new GrammarsDiscoverer(classTypeDiscoverer);
// Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationBuilder.java // public class ApplicationBuilder { // // private final ResourcesBuilder resourcesBuilder; // private final IncludeBuilder includeBuilder; // // public ApplicationBuilder(ApplicationContext ctx) { // resourcesBuilder = new ResourcesBuilder(ctx); // includeBuilder = new IncludeBuilder(ctx.getGrammarsDiscoverer()); // } // // public Application build(HttpServletRequest request) { // return build(HttpServletRequestUtils.getBaseUrlOf(request)); // } // // public Application build(String baseUrl) { // return new Application() // .withDoc(new Doc().withTitle("REST Service WADL")) // .withResources(resourcesBuilder.build(baseUrl)) // .withGrammars(new Grammars().withInclude(includeBuilder.build())); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java // public class ClassTypeDiscoverer { // // final QNameBuilder qNameBuilder; // final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); // // public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { // this.qNameBuilder = qNameBuilder; // } // // public ClassType discoverFor(ClassMetadata classMetadata) { // ClassType classType = classTypeStore.findBy(classMetadata.getType()); // if (classType == null) { // classType = buildClassTypeFor(classMetadata); // classTypeStore.add(classType); // } // // return classType; // } // // private ClassType buildClassTypeFor(ClassMetadata classMetadata) { // final ClassType classType; // if (classMetadata.isCollection()) { // final QName collectionQName = qNameBuilder.buildForCollectionOf(classMetadata.getComponentType()); // final QName elementsQName = qNameBuilder.buildFor(classMetadata.getComponentType()); // classType = new CollectionType(classMetadata.getType(), collectionQName, elementsQName); // // } else { // final QName qName = qNameBuilder.buildFor(classMetadata.getType()); // classType = new SingleType(classMetadata.getType(), qName); // } // return classType; // } // // public ClassType getBy(String localPart) { // final ClassType classType = classTypeStore.findBy(localPart); // if (classType == null) { // throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); // } // return classType; // } // // public Map<String, ClassType> getAllByLocalPart() { // return classTypeStore.getAllByLocalPart(); // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderFactory.java // public class QNameBuilderFactory { // // public QNameBuilder getBuilder() { // return new QNameBuilder( // new QNameMemory( // initCacheForSingleTypes(), // initCacheForCollectionTypes(), // initCacheForAlreadyUsedPrefixes())); // } // // private QNamesCache initCacheForSingleTypes() { // return new InMemoryQNamesCache(BASIC_SINGLE_TYPES); // } // // private QNamesCache initCacheForCollectionTypes() { // return new InMemoryQNamesCache(BASIC_COLLECTION_TYPES); // } // // private QNamePrefixesCache initCacheForAlreadyUsedPrefixes() { // final QNamePrefixesCache cache = new InMemoryQNamePrefixesCache(); // cache.add("xs"); // cache.add("wadl"); // cache.add("tc"); // // return cache; // } // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringWadlBuilderFactory.java import com.autentia.web.rest.wadl.builder.ApplicationBuilder; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.xml.schema.ClassTypeDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.GrammarsDiscoverer; import com.autentia.web.rest.wadl.builder.namespace.QNameBuilderFactory; import com.autentia.xml.schema.SchemaBuilder; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; public class SpringWadlBuilderFactory { private final ApplicationBuilder applicationBuilder; private final SchemaBuilder schemaBuilder; public SpringWadlBuilderFactory(RequestMappingHandlerMapping handlerMapping) { final ClassTypeDiscoverer classTypeDiscoverer = new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder()); final GrammarsDiscoverer grammarsDiscoverer = new GrammarsDiscoverer(classTypeDiscoverer);
final ApplicationContext appCtx = new ApplicationContext(new SpringMethodContextIterator(handlerMapping), grammarsDiscoverer);
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java
// Path: spring-wadl-generator/src/main/java/com/autentia/lang/ClassMetadata.java // public interface ClassMetadata { // boolean isCollection(); // // Class<?> getType(); // // Class<?> getComponentType(); // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/namespace/QNameBuilder.java // public class QNameBuilder { // // private static final Logger logger = LoggerFactory.getLogger(QNameBuilder.class); // // private static final Pattern BY_DOTS = Pattern.compile("\\."); // private static final Pattern VOWELS = Pattern.compile("[aeiou]"); // private static final QName EMPTY_Q_NAME = new QName("", "", ""); // // private final QNameMemory memory; // // public QNameBuilder(QNameMemory memory) { // this.memory = memory; // } // // public QName buildFor(Class<?> classType) { // return discoverQNameAndCachesIt(classType, "", "", memory.forSingleTypes()); // } // // public QName buildForCollectionOf(Class<?> clazz) { // return discoverQNameAndCachesIt(clazz, "Collection", "cll", memory.forCollectionTypes()); // } // // private QName discoverQNameAndCachesIt(Class<?> classType, String classTypeNameSuffix, String prefixSuffix, QNamesCache cache) { // QName qName = cache.getQNameFor(classType); // if (qName == null) { // qName = discoverQNameFromJaxb(classType); // // final String localPart = (isNotBlank(qName.getLocalPart()) ? qName.getLocalPart() : discoverLocalPartFor(classType)) + classTypeNameSuffix; // final String namespaceUri = isNotBlank(qName.getNamespaceURI()) ? qName.getNamespaceURI() : discoverNamespaceUriFor(classType, localPart); // final String prefix = isNotBlank(qName.getPrefix()) ? qName.getPrefix() : discoverPrefixFor(classType, prefixSuffix); // qName = new QName(namespaceUri, localPart, prefix); // // cache.putQNameFor(classType, qName); // } // return qName; // } // // private QName discoverQNameFromJaxb(Class<?> classType) { // QName qName = null; // try { // final JAXBIntrospector jaxbIntrospector = JAXBContext.newInstance(classType).createJAXBIntrospector(); // qName = jaxbIntrospector.getElementName(classType.getConstructor().newInstance()); // // } catch (Exception e) { // // Add e to the logger message because JAXB Exceptions has a lot of information in the toString(). // // and some loggers implementations just print the getMessage(); // logger.warn("Cannot discover QName from JAXB annotations for class: " + classType.getName() // + ". Preparing generic QName." + e, e); // } // // if (qName == null) { // // Could be null if getElementName returned null, or a exception was thrown. // return EMPTY_Q_NAME; // } // return qName; // } // // private String discoverNamespaceUriFor(Class<?> classType, String localPart) { // final String[] classNameSections = BY_DOTS.split(classType.getName()); // return "http://www." + classNameSections[1] + '.' + classNameSections[0] + "/schema/" + localPart; // } // // private String discoverLocalPartFor(Class<?> classType) { // final String classTypeName = classType.getSimpleName(); // return classTypeName.substring(0, 1).toLowerCase() + classTypeName.substring(1); // } // // private String discoverPrefixFor(Class<?> classType, String suffix) { // final String simpleName = classType.getSimpleName(); // final String classNameWithoutVowels = VOWELS.matcher(simpleName.toLowerCase()).replaceAll(""); // final String reducedClassName = classNameWithoutVowels.length() >= 3 ? classNameWithoutVowels : simpleName; // // String prefix = reducedClassName.substring(0, 3) + suffix; // // int i = 4; // int numberedSuffix = 2; // while (memory.forAlreadyUsedPrefixes().contains(prefix)) { // if (i < reducedClassName.length()) { // prefix = reducedClassName.substring(0, i) + suffix; // i++; // // } else { // prefix = reducedClassName.substring(0, 3) + suffix + numberedSuffix; // numberedSuffix++; // } // } // // memory.forAlreadyUsedPrefixes().add(prefix); // return prefix; // } // }
import com.autentia.lang.ClassMetadata; import com.autentia.xml.namespace.QNameBuilder; import javax.xml.namespace.QName; import java.util.Map;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.xml.schema; public class ClassTypeDiscoverer { final QNameBuilder qNameBuilder; final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { this.qNameBuilder = qNameBuilder; }
// Path: spring-wadl-generator/src/main/java/com/autentia/lang/ClassMetadata.java // public interface ClassMetadata { // boolean isCollection(); // // Class<?> getType(); // // Class<?> getComponentType(); // } // // Path: spring-wadl-generator/src/main/java/com/autentia/xml/namespace/QNameBuilder.java // public class QNameBuilder { // // private static final Logger logger = LoggerFactory.getLogger(QNameBuilder.class); // // private static final Pattern BY_DOTS = Pattern.compile("\\."); // private static final Pattern VOWELS = Pattern.compile("[aeiou]"); // private static final QName EMPTY_Q_NAME = new QName("", "", ""); // // private final QNameMemory memory; // // public QNameBuilder(QNameMemory memory) { // this.memory = memory; // } // // public QName buildFor(Class<?> classType) { // return discoverQNameAndCachesIt(classType, "", "", memory.forSingleTypes()); // } // // public QName buildForCollectionOf(Class<?> clazz) { // return discoverQNameAndCachesIt(clazz, "Collection", "cll", memory.forCollectionTypes()); // } // // private QName discoverQNameAndCachesIt(Class<?> classType, String classTypeNameSuffix, String prefixSuffix, QNamesCache cache) { // QName qName = cache.getQNameFor(classType); // if (qName == null) { // qName = discoverQNameFromJaxb(classType); // // final String localPart = (isNotBlank(qName.getLocalPart()) ? qName.getLocalPart() : discoverLocalPartFor(classType)) + classTypeNameSuffix; // final String namespaceUri = isNotBlank(qName.getNamespaceURI()) ? qName.getNamespaceURI() : discoverNamespaceUriFor(classType, localPart); // final String prefix = isNotBlank(qName.getPrefix()) ? qName.getPrefix() : discoverPrefixFor(classType, prefixSuffix); // qName = new QName(namespaceUri, localPart, prefix); // // cache.putQNameFor(classType, qName); // } // return qName; // } // // private QName discoverQNameFromJaxb(Class<?> classType) { // QName qName = null; // try { // final JAXBIntrospector jaxbIntrospector = JAXBContext.newInstance(classType).createJAXBIntrospector(); // qName = jaxbIntrospector.getElementName(classType.getConstructor().newInstance()); // // } catch (Exception e) { // // Add e to the logger message because JAXB Exceptions has a lot of information in the toString(). // // and some loggers implementations just print the getMessage(); // logger.warn("Cannot discover QName from JAXB annotations for class: " + classType.getName() // + ". Preparing generic QName." + e, e); // } // // if (qName == null) { // // Could be null if getElementName returned null, or a exception was thrown. // return EMPTY_Q_NAME; // } // return qName; // } // // private String discoverNamespaceUriFor(Class<?> classType, String localPart) { // final String[] classNameSections = BY_DOTS.split(classType.getName()); // return "http://www." + classNameSections[1] + '.' + classNameSections[0] + "/schema/" + localPart; // } // // private String discoverLocalPartFor(Class<?> classType) { // final String classTypeName = classType.getSimpleName(); // return classTypeName.substring(0, 1).toLowerCase() + classTypeName.substring(1); // } // // private String discoverPrefixFor(Class<?> classType, String suffix) { // final String simpleName = classType.getSimpleName(); // final String classNameWithoutVowels = VOWELS.matcher(simpleName.toLowerCase()).replaceAll(""); // final String reducedClassName = classNameWithoutVowels.length() >= 3 ? classNameWithoutVowels : simpleName; // // String prefix = reducedClassName.substring(0, 3) + suffix; // // int i = 4; // int numberedSuffix = 2; // while (memory.forAlreadyUsedPrefixes().contains(prefix)) { // if (i < reducedClassName.length()) { // prefix = reducedClassName.substring(0, i) + suffix; // i++; // // } else { // prefix = reducedClassName.substring(0, 3) + suffix + numberedSuffix; // numberedSuffix++; // } // } // // memory.forAlreadyUsedPrefixes().add(prefix); // return prefix; // } // } // Path: spring-wadl-generator/src/main/java/com/autentia/xml/schema/ClassTypeDiscoverer.java import com.autentia.lang.ClassMetadata; import com.autentia.xml.namespace.QNameBuilder; import javax.xml.namespace.QName; import java.util.Map; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.xml.schema; public class ClassTypeDiscoverer { final QNameBuilder qNameBuilder; final ClassTypeInMemoryStore classTypeStore = new ClassTypeInMemoryStore(); public ClassTypeDiscoverer(QNameBuilder qNameBuilder) { this.qNameBuilder = qNameBuilder; }
public ClassType discoverFor(ClassMetadata classMetadata) {
autentia/wadl-tools
wadl-packaging/wadl-zipper/src/test/java/com/autentia/web/rest/wadl/zipper/WadlZipperTest.java
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // // Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_WADL_FILENAME = "wadl.xml";
import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import static com.autentia.web.rest.wadl.zipper.GrammarsUrisExtractorTest.*; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_SCHEMA_EXTENSION; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_WADL_FILENAME; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.zipper; public class WadlZipperTest { private static final String HOST_URI = "http://localhost:7070"; private static final String REST_URI = HOST_URI + "/spring-wadl-showcase/rest"; private static final String WADL_URI = REST_URI + "/wadl"; private final WadlZipper wadlZipper; private final HttpClient httpClientMock = mock(HttpClient.class); private final Zip zipMock = mock(Zip.class); public WadlZipperTest() throws URISyntaxException { wadlZipper = new WadlZipper(WADL_URI); } @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { // Given doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); // When wadlZipper.saveTo(httpClientMock, zipMock); // Then final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(),
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // // Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_WADL_FILENAME = "wadl.xml"; // Path: wadl-packaging/wadl-zipper/src/test/java/com/autentia/web/rest/wadl/zipper/WadlZipperTest.java import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import static com.autentia.web.rest.wadl.zipper.GrammarsUrisExtractorTest.*; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_SCHEMA_EXTENSION; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_WADL_FILENAME; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.zipper; public class WadlZipperTest { private static final String HOST_URI = "http://localhost:7070"; private static final String REST_URI = HOST_URI + "/spring-wadl-showcase/rest"; private static final String WADL_URI = REST_URI + "/wadl"; private final WadlZipper wadlZipper; private final HttpClient httpClientMock = mock(HttpClient.class); private final Zip zipMock = mock(Zip.class); public WadlZipperTest() throws URISyntaxException { wadlZipper = new WadlZipper(WADL_URI); } @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { // Given doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); // When wadlZipper.saveTo(httpClientMock, zipMock); // Then final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(),
contains(DEFAULT_WADL_FILENAME,
autentia/wadl-tools
wadl-packaging/wadl-zipper/src/test/java/com/autentia/web/rest/wadl/zipper/WadlZipperTest.java
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // // Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_WADL_FILENAME = "wadl.xml";
import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import static com.autentia.web.rest.wadl.zipper.GrammarsUrisExtractorTest.*; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_SCHEMA_EXTENSION; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_WADL_FILENAME; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.zipper; public class WadlZipperTest { private static final String HOST_URI = "http://localhost:7070"; private static final String REST_URI = HOST_URI + "/spring-wadl-showcase/rest"; private static final String WADL_URI = REST_URI + "/wadl"; private final WadlZipper wadlZipper; private final HttpClient httpClientMock = mock(HttpClient.class); private final Zip zipMock = mock(Zip.class); public WadlZipperTest() throws URISyntaxException { wadlZipper = new WadlZipper(WADL_URI); } @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { // Given doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); // When wadlZipper.saveTo(httpClientMock, zipMock); // Then final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(), contains(DEFAULT_WADL_FILENAME,
// Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_SCHEMA_EXTENSION = ".xsd"; // // Path: wadl-packaging/wadl-zipper/src/main/java/com/autentia/web/rest/wadl/zipper/WadlZipper.java // static final String DEFAULT_WADL_FILENAME = "wadl.xml"; // Path: wadl-packaging/wadl-zipper/src/test/java/com/autentia/web/rest/wadl/zipper/WadlZipperTest.java import org.junit.Test; import org.mockito.ArgumentCaptor; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import static com.autentia.web.rest.wadl.zipper.GrammarsUrisExtractorTest.*; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_SCHEMA_EXTENSION; import static com.autentia.web.rest.wadl.zipper.WadlZipper.DEFAULT_WADL_FILENAME; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.zipper; public class WadlZipperTest { private static final String HOST_URI = "http://localhost:7070"; private static final String REST_URI = HOST_URI + "/spring-wadl-showcase/rest"; private static final String WADL_URI = REST_URI + "/wadl"; private final WadlZipper wadlZipper; private final HttpClient httpClientMock = mock(HttpClient.class); private final Zip zipMock = mock(Zip.class); public WadlZipperTest() throws URISyntaxException { wadlZipper = new WadlZipper(WADL_URI); } @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { // Given doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); // When wadlZipper.saveTo(httpClientMock, zipMock); // Then final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(), contains(DEFAULT_WADL_FILENAME,
RELATIVE_URI + DEFAULT_SCHEMA_EXTENSION,
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringMethodContext.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java // public abstract class MethodContext { // // private final ApplicationContext parentContext; // private ParamBuilder paramBuilder; // // protected MethodContext(ApplicationContext parentContext) { // this.parentContext = parentContext; // } // // ApplicationContext getParentContext() { // return parentContext; // } // // ParamBuilder getParamBuilder() { // return paramBuilder; // } // // void setParamBuilder(ParamBuilder paramBuilder) { // this.paramBuilder = paramBuilder; // } // // protected abstract String discoverPath(); // // protected abstract Method getJavaMethod(); // // protected abstract Set<HttpMethod> getHttpMethods(); // // protected abstract Set<MediaType> getMediaTypes(); // }
import com.autentia.web.HttpMethod; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.web.rest.wadl.builder.MethodContext; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import java.lang.reflect.Method; import java.util.EnumSet; import java.util.Set;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; class SpringMethodContext extends MethodContext { private final RequestMappingInfo mappingInfo; private final HandlerMethod handlerMethod;
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java // public abstract class MethodContext { // // private final ApplicationContext parentContext; // private ParamBuilder paramBuilder; // // protected MethodContext(ApplicationContext parentContext) { // this.parentContext = parentContext; // } // // ApplicationContext getParentContext() { // return parentContext; // } // // ParamBuilder getParamBuilder() { // return paramBuilder; // } // // void setParamBuilder(ParamBuilder paramBuilder) { // this.paramBuilder = paramBuilder; // } // // protected abstract String discoverPath(); // // protected abstract Method getJavaMethod(); // // protected abstract Set<HttpMethod> getHttpMethods(); // // protected abstract Set<MediaType> getMediaTypes(); // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringMethodContext.java import com.autentia.web.HttpMethod; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.web.rest.wadl.builder.MethodContext; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import java.lang.reflect.Method; import java.util.EnumSet; import java.util.Set; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; class SpringMethodContext extends MethodContext { private final RequestMappingInfo mappingInfo; private final HandlerMethod handlerMethod;
SpringMethodContext(ApplicationContext parentContext, RequestMappingInfo mappingInfo, HandlerMethod handlerMethod) {
autentia/wadl-tools
spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringMethodContext.java
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java // public abstract class MethodContext { // // private final ApplicationContext parentContext; // private ParamBuilder paramBuilder; // // protected MethodContext(ApplicationContext parentContext) { // this.parentContext = parentContext; // } // // ApplicationContext getParentContext() { // return parentContext; // } // // ParamBuilder getParamBuilder() { // return paramBuilder; // } // // void setParamBuilder(ParamBuilder paramBuilder) { // this.paramBuilder = paramBuilder; // } // // protected abstract String discoverPath(); // // protected abstract Method getJavaMethod(); // // protected abstract Set<HttpMethod> getHttpMethods(); // // protected abstract Set<MediaType> getMediaTypes(); // }
import com.autentia.web.HttpMethod; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.web.rest.wadl.builder.MethodContext; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import java.lang.reflect.Method; import java.util.EnumSet; import java.util.Set;
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; class SpringMethodContext extends MethodContext { private final RequestMappingInfo mappingInfo; private final HandlerMethod handlerMethod; SpringMethodContext(ApplicationContext parentContext, RequestMappingInfo mappingInfo, HandlerMethod handlerMethod) { super(parentContext); this.mappingInfo = mappingInfo; this.handlerMethod = handlerMethod; } @Override protected String discoverPath() { String path = null; for (String uri : mappingInfo.getPatternsCondition().getPatterns()) { path = uri; } return path; } @Override protected Method getJavaMethod() { return handlerMethod.getMethod(); } @Override
// Path: spring-wadl-generator/src/main/java/com/autentia/web/HttpMethod.java // public enum HttpMethod { // // GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE // // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/ApplicationContext.java // public class ApplicationContext implements Iterable<MethodContext> { // // private final MethodContextIterator methodContextIterator; // private final GrammarsDiscoverer grammarsDiscoverer; // // public ApplicationContext(MethodContextIterator methodContextIterator, GrammarsDiscoverer grammarsDiscoverer) { // this.methodContextIterator = methodContextIterator; // this.grammarsDiscoverer = grammarsDiscoverer; // } // // @Override // public MethodContextIterator iterator() { // methodContextIterator.initWith(this); // return methodContextIterator; // } // // public GrammarsDiscoverer getGrammarsDiscoverer() { // return grammarsDiscoverer; // } // } // // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/MethodContext.java // public abstract class MethodContext { // // private final ApplicationContext parentContext; // private ParamBuilder paramBuilder; // // protected MethodContext(ApplicationContext parentContext) { // this.parentContext = parentContext; // } // // ApplicationContext getParentContext() { // return parentContext; // } // // ParamBuilder getParamBuilder() { // return paramBuilder; // } // // void setParamBuilder(ParamBuilder paramBuilder) { // this.paramBuilder = paramBuilder; // } // // protected abstract String discoverPath(); // // protected abstract Method getJavaMethod(); // // protected abstract Set<HttpMethod> getHttpMethods(); // // protected abstract Set<MediaType> getMediaTypes(); // } // Path: spring-wadl-generator/src/main/java/com/autentia/web/rest/wadl/builder/impl/springframework/SpringMethodContext.java import com.autentia.web.HttpMethod; import com.autentia.web.rest.wadl.builder.ApplicationContext; import com.autentia.web.rest.wadl.builder.MethodContext; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import java.lang.reflect.Method; import java.util.EnumSet; import java.util.Set; /** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.impl.springframework; class SpringMethodContext extends MethodContext { private final RequestMappingInfo mappingInfo; private final HandlerMethod handlerMethod; SpringMethodContext(ApplicationContext parentContext, RequestMappingInfo mappingInfo, HandlerMethod handlerMethod) { super(parentContext); this.mappingInfo = mappingInfo; this.handlerMethod = handlerMethod; } @Override protected String discoverPath() { String path = null; for (String uri : mappingInfo.getPatternsCondition().getPatterns()) { path = uri; } return path; } @Override protected Method getJavaMethod() { return handlerMethod.getMethod(); } @Override
protected Set<HttpMethod> getHttpMethods() {
andremion/Villains-and-Heroes
app/src/androidTest/java/com/andremion/heroes/util/DataConstants.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.ArrayList;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.util; public class DataConstants { public static final CharacterVO CHARACTER = new CharacterVO(); public static final long CHARACTER_ID = 1011334; public static final String CHARACTER_NAME = "3-D Man"; public static final String CHARACTER_TO_FIND = "Hulk"; static { CHARACTER.setId(CHARACTER_ID); CHARACTER.setName(CHARACTER_NAME);
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/androidTest/java/com/andremion/heroes/util/DataConstants.java import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.ArrayList; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.util; public class DataConstants { public static final CharacterVO CHARACTER = new CharacterVO(); public static final long CHARACTER_ID = 1011334; public static final String CHARACTER_NAME = "3-D Man"; public static final String CHARACTER_TO_FIND = "Hulk"; static { CHARACTER.setId(CHARACTER_ID); CHARACTER.setName(CHARACTER_NAME);
CHARACTER.setComics(new ArrayList<SectionVO>());
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/section/SectionContract.java
// Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import com.andremion.heroes.api.data.SectionVO; import java.util.List;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.section; public interface SectionContract { interface View {
// Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/main/java/com/andremion/heroes/ui/section/SectionContract.java import com.andremion.heroes.api.data.SectionVO; import java.util.List; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.section; public interface SectionContract { interface View {
void showItems(List<SectionVO> entries, int position);
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/home/MainContract.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // }
import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import java.util.List;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.home; public interface MainContract { interface View { void showProgress(); void stopProgress(boolean hasMore); void showAttribution(String attribution);
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // Path: app/src/main/java/com/andremion/heroes/ui/home/MainContract.java import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import java.util.List; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.home; public interface MainContract { interface View { void showProgress(); void stopProgress(boolean hasMore); void showAttribution(String attribution);
void showResult(@NonNull List<CharacterVO> entries);
andremion/Villains-and-Heroes
app/src/test/java/com/andremion/heroes/api/MarvelApiTest.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.api; public class MarvelApiTest { private static final int OFFSET = 0; private static final long CHARACTER_ID = 1011334; private MarvelApi mMarvelApi; @Before public void setUp() { mMarvelApi = MarvelApi.getInstance(); } @Test public void listCharacters() throws IOException, MarvelException { // Fetch the character result and check for not null
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/test/java/com/andremion/heroes/api/MarvelApiTest.java import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.api; public class MarvelApiTest { private static final int OFFSET = 0; private static final long CHARACTER_ID = 1011334; private MarvelApi mMarvelApi; @Before public void setUp() { mMarvelApi = MarvelApi.getInstance(); } @Test public void listCharacters() throws IOException, MarvelException { // Fetch the character result and check for not null
MarvelResult<CharacterVO> result = mMarvelApi.listCharacters(OFFSET);
andremion/Villains-and-Heroes
app/src/test/java/com/andremion/heroes/api/MarvelApiTest.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.api; public class MarvelApiTest { private static final int OFFSET = 0; private static final long CHARACTER_ID = 1011334; private MarvelApi mMarvelApi; @Before public void setUp() { mMarvelApi = MarvelApi.getInstance(); } @Test public void listCharacters() throws IOException, MarvelException { // Fetch the character result and check for not null MarvelResult<CharacterVO> result = mMarvelApi.listCharacters(OFFSET); assertNotNull(result); // Get the character list and check for not null List<CharacterVO> entries = result.getEntries(); assertNotNull(entries); // Get the character list and check for not empty assertFalse(entries.isEmpty()); } @Test public void listComicsByCharacter() throws IOException, MarvelException { // Fetch the comic result and check for not null
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/test/java/com/andremion/heroes/api/MarvelApiTest.java import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.api; public class MarvelApiTest { private static final int OFFSET = 0; private static final long CHARACTER_ID = 1011334; private MarvelApi mMarvelApi; @Before public void setUp() { mMarvelApi = MarvelApi.getInstance(); } @Test public void listCharacters() throws IOException, MarvelException { // Fetch the character result and check for not null MarvelResult<CharacterVO> result = mMarvelApi.listCharacters(OFFSET); assertNotNull(result); // Get the character list and check for not null List<CharacterVO> entries = result.getEntries(); assertNotNull(entries); // Get the character list and check for not empty assertFalse(entries.isEmpty()); } @Test public void listComicsByCharacter() throws IOException, MarvelException { // Fetch the comic result and check for not null
MarvelResult<SectionVO> result = mMarvelApi.listComics(CHARACTER_ID, OFFSET);
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/search/SearchContract.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // }
import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import java.util.List;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.search; public interface SearchContract { interface View { void showProgress(); void stopProgress();
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // Path: app/src/main/java/com/andremion/heroes/ui/search/SearchContract.java import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import java.util.List; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.search; public interface SearchContract { interface View { void showProgress(); void stopProgress();
void showResult(List<CharacterVO> entries);
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/character/CharacterContract.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.List;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.character; public interface CharacterContract { interface View { void showAttribution(String attribution);
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/main/java/com/andremion/heroes/ui/character/CharacterContract.java import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.List; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.character; public interface CharacterContract { interface View { void showAttribution(String attribution);
void showCharacter(@NonNull CharacterVO character);
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/character/CharacterContract.java
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // }
import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.List;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.character; public interface CharacterContract { interface View { void showAttribution(String attribution); void showCharacter(@NonNull CharacterVO character);
// Path: app/src/main/java/com/andremion/heroes/api/data/CharacterVO.java // public class CharacterVO implements Serializable { // // private long mId; // private String mName; // private String mDescription; // private String mThumbnail; // private String mImage; // private List<SectionVO> mComics; // private List<SectionVO> mSeries; // private List<SectionVO> mStories; // private List<SectionVO> mEvents; // private String mDetail; // private String mWiki; // private String mComicLink; // // public CharacterVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public String getDescription() { // return mDescription; // } // // public void setDescription(String description) { // mDescription = description; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // public List<SectionVO> getComics() { // return mComics; // } // // public void setComics(List<SectionVO> comics) { // mComics = comics; // } // // public List<SectionVO> getSeries() { // return mSeries; // } // // public void setSeries(List<SectionVO> series) { // mSeries = series; // } // // public List<SectionVO> getStories() { // return mStories; // } // // public void setStories(List<SectionVO> stories) { // mStories = stories; // } // // public List<SectionVO> getEvents() { // return mEvents; // } // // public void setEvents(List<SectionVO> events) { // mEvents = events; // } // // public String getDetail() { // return mDetail; // } // // public void setDetail(String detail) { // mDetail = detail; // } // // public String getWiki() { // return mWiki; // } // // public void setWiki(String wiki) { // mWiki = wiki; // } // // public String getComicLink() { // return mComicLink; // } // // public void setComicLink(String comicLink) { // mComicLink = comicLink; // } // // @Override // public String toString() { // return "Character{" + mId + ", '" + mName + "'}"; // } // } // // Path: app/src/main/java/com/andremion/heroes/api/data/SectionVO.java // public class SectionVO implements Serializable { // // public static final int TYPE_COMIC = 0; // public static final int TYPE_SERIES = 1; // public static final int TYPE_STORY = 2; // public static final int TYPE_EVENT = 3; // // @IntDef({TYPE_COMIC, TYPE_SERIES, TYPE_STORY, TYPE_EVENT}) // @Retention(RetentionPolicy.SOURCE) // public @interface Type { // } // // private long mId; // private String mTitle; // private String mThumbnail; // private String mImage; // // public SectionVO() { // } // // public long getId() { // return mId; // } // // public void setId(long id) { // mId = id; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // mTitle = title; // } // // public String getThumbnail() { // return mThumbnail; // } // // public void setThumbnail(String thumbnail) { // mThumbnail = thumbnail; // } // // public String getImage() { // return mImage; // } // // public void setImage(String image) { // mImage = image; // } // // @Override // public String toString() { // return "Section{" + mId + ", '" + mTitle + "'}"; // } // } // Path: app/src/main/java/com/andremion/heroes/ui/character/CharacterContract.java import android.support.annotation.NonNull; import com.andremion.heroes.api.data.CharacterVO; import com.andremion.heroes.api.data.SectionVO; import java.util.List; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.character; public interface CharacterContract { interface View { void showAttribution(String attribution); void showCharacter(@NonNull CharacterVO character);
void showComics(@NonNull List<SectionVO> entries);
andremion/Villains-and-Heroes
app/src/main/java/com/andremion/heroes/ui/util/StringUtils.java
// Path: app/src/main/java/com/andremion/heroes/api/MarvelException.java // public class MarvelException extends Exception { // // private final int mCode; // // public MarvelException(int code, String message) { // super(message); // mCode = code; // } // // public int getCode() { // return mCode; // } // // }
import android.content.Context; import android.support.annotation.NonNull; import com.andremion.heroes.R; import com.andremion.heroes.api.MarvelException; import java.io.IOException;
/* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.util; public class StringUtils { private StringUtils() { } public static String getApiErrorMessage(@NonNull Context context, @NonNull Throwable e) { if (e instanceof IOException) { return context.getString(R.string.connection_error);
// Path: app/src/main/java/com/andremion/heroes/api/MarvelException.java // public class MarvelException extends Exception { // // private final int mCode; // // public MarvelException(int code, String message) { // super(message); // mCode = code; // } // // public int getCode() { // return mCode; // } // // } // Path: app/src/main/java/com/andremion/heroes/ui/util/StringUtils.java import android.content.Context; import android.support.annotation.NonNull; import com.andremion.heroes.R; import com.andremion.heroes.api.MarvelException; import java.io.IOException; /* * Copyright (c) 2017. André Mion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andremion.heroes.ui.util; public class StringUtils { private StringUtils() { } public static String getApiErrorMessage(@NonNull Context context, @NonNull Throwable e) { if (e instanceof IOException) { return context.getString(R.string.connection_error);
} else if (e instanceof MarvelException) {
rquast/swingsane
src/main/java/com/swingsane/util/Misc.java
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import java.awt.Component; import java.lang.reflect.Method; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import com.swingsane.i18n.Localizer;
package com.swingsane.util; /** * @author Roland Quast (rquast@formreturn.com) * */ public final class Misc { public static void openURL(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class<?> fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url }); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); } else { // assume Unix or Linux String[] browsers = { "chromium-browser", "google-chrome", "google-chrome-stable", "chrome", "/opt/google/chrome/chrome", "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; String browser = null; for (int count = 0; (count < browsers.length) && (browser == null); count++) { if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) { browser = browsers[count]; } } if (browser == null) {
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/util/Misc.java import java.awt.Component; import java.lang.reflect.Method; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import com.swingsane.i18n.Localizer; package com.swingsane.util; /** * @author Roland Quast (rquast@formreturn.com) * */ public final class Misc { public static void openURL(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class<?> fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url }); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); } else { // assume Unix or Linux String[] browsers = { "chromium-browser", "google-chrome", "google-chrome-stable", "chrome", "/opt/google/chrome/chrome", "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; String browser = null; for (int count = 0; (count < browsers.length) && (browser == null); count++) { if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) { browser = browsers[count]; } } if (browser == null) {
throw new Exception(Localizer.localize("LaunchWebBrowserNotFound"));
rquast/swingsane
src/main/java/com/swingsane/business/image/transform/IImageTransform.java
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // }
import java.io.File; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults;
package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public interface IImageTransform { void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; File getOutputImageFile(); File getSourceImageFile();
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // } // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java import java.io.File; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults; package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public interface IImageTransform { void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; File getOutputImageFile(); File getSourceImageFile();
ITransformSettingsPanel getTransformSettingsPanel();
rquast/swingsane
src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer;
package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel {
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer; package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel {
private BinarizeTransform transform;
rquast/swingsane
src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer;
package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { private BinarizeTransform transform; private JSpinner luminanceSpinner; public BinarizeTransformSettingsPanel() { initComponents(); } @Override
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer; package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { private BinarizeTransform transform; private JSpinner luminanceSpinner; public BinarizeTransformSettingsPanel() { initComponents(); } @Override
public final IImageTransform getTransform() {
rquast/swingsane
src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer;
package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { private BinarizeTransform transform; private JSpinner luminanceSpinner; public BinarizeTransformSettingsPanel() { initComponents(); } @Override public final IImageTransform getTransform() { return transform; } private void initComponents() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 32, 0 }; gridBagLayout.rowHeights = new int[] { 24, 0 }; gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); JPanel containerPanel = new JPanel();
// Path: src/main/java/com/swingsane/business/image/transform/BinarizeTransform.java // public class BinarizeTransform implements IImageTransform { // // private int luminanceThreshold; // // private File sourceImageFile; // private File outputImageFile; // // private static final ImageTransformType imageTransformType = ImageTransformType.BINARIZE; // // @Override // public void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception { // luminanceThreshold = preferredDefaultsImpl.getDefaultLuminanceThreshold(); // } // // public final int getLuminanceThreshold() { // return luminanceThreshold; // } // // @Override // public final File getOutputImageFile() { // return outputImageFile; // } // // @Override // public final File getSourceImageFile() { // return sourceImageFile; // } // // @Override // public final ITransformSettingsPanel getTransformSettingsPanel() { // BinarizeTransformSettingsPanel transformSettingsPanel = new BinarizeTransformSettingsPanel(); // transformSettingsPanel.setTransform(this); // return transformSettingsPanel; // } // // public final void setLuminanceThreshold(int luminanceThreshold) { // this.luminanceThreshold = luminanceThreshold; // } // // @Override // public final void setOutputImageFile(File outputImageFile) { // this.outputImageFile = outputImageFile; // } // // @Override // public final void setSourceImageFile(File sourceImageFile) { // this.sourceImageFile = sourceImageFile; // } // // @Override // public final String toString() { // return imageTransformType.toString(); // } // // @Override // public final void transform() throws IOException { // BufferedImage bufferedImage = ImageIO.read(sourceImageFile); // ImageIO.write(ImageBinarize.binarizeImage(bufferedImage, luminanceThreshold, false), "PNG", // outputImageFile); // } // // } // // Path: src/main/java/com/swingsane/business/image/transform/IImageTransform.java // public interface IImageTransform { // // void configure(IPreferredDefaults preferredDefaultsImpl) throws Exception; // // File getOutputImageFile(); // // File getSourceImageFile(); // // ITransformSettingsPanel getTransformSettingsPanel(); // // void setOutputImageFile(File outputImageFile); // // void setSourceImageFile(File sourceImageFile); // // @Override // String toString(); // // void transform() throws Exception; // // } // // Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/gui/panel/BinarizeTransformSettingsPanel.java import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.swingsane.business.image.transform.BinarizeTransform; import com.swingsane.business.image.transform.IImageTransform; import com.swingsane.i18n.Localizer; package com.swingsane.gui.panel; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class BinarizeTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { private BinarizeTransform transform; private JSpinner luminanceSpinner; public BinarizeTransformSettingsPanel() { initComponents(); } @Override public final IImageTransform getTransform() { return transform; } private void initComponents() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 32, 0 }; gridBagLayout.rowHeights = new int[] { 24, 0 }; gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; setLayout(gridBagLayout); JPanel containerPanel = new JPanel();
containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer
rquast/swingsane
src/main/java/com/swingsane/preferences/ISwingSanePreferences.java
// Path: src/main/java/com/swingsane/preferences/model/ApplicationPreferences.java // @XStreamAlias("applicationPreferences") // public class ApplicationPreferences { // // private ArrayList<Scanner> scannerList; // // private HashMap<String, Login> saneLogins; // // private SaneServiceIdentity saneServiceIdentity; // // public final HashMap<String, Login> getSaneLogins() { // if (saneLogins == null) { // saneLogins = new HashMap<String, Login>(); // } // return saneLogins; // } // // public final SaneServiceIdentity getSaneServiceIdentity() { // if (saneServiceIdentity == null) { // saneServiceIdentity = new SaneServiceIdentity(); // } // return saneServiceIdentity; // } // // public final ArrayList<Scanner> getScannerList() { // if (scannerList == null) { // scannerList = new ArrayList<Scanner>(); // } // return scannerList; // } // // public final void setSaneService(SaneServiceIdentity saneService) { // saneServiceIdentity = saneService; // } // // }
import java.io.File; import com.swingsane.preferences.model.ApplicationPreferences;
package com.swingsane.preferences; public interface ISwingSanePreferences extends BasePreferences { void cleanUp();
// Path: src/main/java/com/swingsane/preferences/model/ApplicationPreferences.java // @XStreamAlias("applicationPreferences") // public class ApplicationPreferences { // // private ArrayList<Scanner> scannerList; // // private HashMap<String, Login> saneLogins; // // private SaneServiceIdentity saneServiceIdentity; // // public final HashMap<String, Login> getSaneLogins() { // if (saneLogins == null) { // saneLogins = new HashMap<String, Login>(); // } // return saneLogins; // } // // public final SaneServiceIdentity getSaneServiceIdentity() { // if (saneServiceIdentity == null) { // saneServiceIdentity = new SaneServiceIdentity(); // } // return saneServiceIdentity; // } // // public final ArrayList<Scanner> getScannerList() { // if (scannerList == null) { // scannerList = new ArrayList<Scanner>(); // } // return scannerList; // } // // public final void setSaneService(SaneServiceIdentity saneService) { // saneServiceIdentity = saneService; // } // // } // Path: src/main/java/com/swingsane/preferences/ISwingSanePreferences.java import java.io.File; import com.swingsane.preferences.model.ApplicationPreferences; package com.swingsane.preferences; public interface ISwingSanePreferences extends BasePreferences { void cleanUp();
ApplicationPreferences getApplicationPreferences();
rquast/swingsane
src/main/java/com/swingsane/business/discovery/DiscoveryEvent.java
// Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // }
import java.util.ArrayList; import java.util.EventObject; import com.swingsane.preferences.model.Scanner;
package com.swingsane.business.discovery; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class DiscoveryEvent extends EventObject {
// Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // } // Path: src/main/java/com/swingsane/business/discovery/DiscoveryEvent.java import java.util.ArrayList; import java.util.EventObject; import com.swingsane.preferences.model.Scanner; package com.swingsane.business.discovery; /** * @author Roland Quast (roland@formreturn.com) * */ @SuppressWarnings("serial") public class DiscoveryEvent extends EventObject {
private ArrayList<Scanner> discoveredScanners;
rquast/swingsane
src/main/java/com/swingsane/business/image/transform/RotateTransform.java
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults;
package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // } // Path: src/main/java/com/swingsane/business/image/transform/RotateTransform.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults; package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override
public void configure(IPreferredDefaults preferredDefaultsImpl) {
rquast/swingsane
src/main/java/com/swingsane/business/image/transform/RotateTransform.java
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults;
package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override public void configure(IPreferredDefaults preferredDefaultsImpl) { rotation = preferredDefaultsImpl.getDefaultRotation(); } @Override public final File getOutputImageFile() { return outputImageFile; } public final Rotation getRotation() { return rotation; } @Override public final File getSourceImageFile() { return sourceImageFile; } @Override
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // } // Path: src/main/java/com/swingsane/business/image/transform/RotateTransform.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults; package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override public void configure(IPreferredDefaults preferredDefaultsImpl) { rotation = preferredDefaultsImpl.getDefaultRotation(); } @Override public final File getOutputImageFile() { return outputImageFile; } public final Rotation getRotation() { return rotation; } @Override public final File getSourceImageFile() { return sourceImageFile; } @Override
public final ITransformSettingsPanel getTransformSettingsPanel() {
rquast/swingsane
src/main/java/com/swingsane/business/image/transform/RotateTransform.java
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults;
package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override public void configure(IPreferredDefaults preferredDefaultsImpl) { rotation = preferredDefaultsImpl.getDefaultRotation(); } @Override public final File getOutputImageFile() { return outputImageFile; } public final Rotation getRotation() { return rotation; } @Override public final File getSourceImageFile() { return sourceImageFile; } @Override public final ITransformSettingsPanel getTransformSettingsPanel() {
// Path: src/main/java/com/swingsane/gui/panel/ITransformSettingsPanel.java // public interface ITransformSettingsPanel { // // IImageTransform getTransform(); // // void restoreSettings(); // // void setTransform(IImageTransform transform); // // } // // Path: src/main/java/com/swingsane/gui/panel/RotateTransformSettingsPanel.java // @SuppressWarnings("serial") // public class RotateTransformSettingsPanel extends JPanel implements ITransformSettingsPanel { // // private JComboBox<Rotation> rotationComboBox; // // private RotateTransform transform; // // public RotateTransformSettingsPanel() { // initComponents(); // } // // @Override // public final IImageTransform getTransform() { // return transform; // } // // private void initComponents() { // GridBagLayout gridBagLayout = new GridBagLayout(); // gridBagLayout.columnWidths = new int[] { 32, 0 }; // gridBagLayout.rowHeights = new int[] { 24, 0 }; // gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // setLayout(gridBagLayout); // // JPanel containerPanel = new JPanel(); // containerPanel.setBorder(new CompoundBorder(new TitledBorder(Localizer // .localize("RotationSettingsBorderTitle")), new EmptyBorder(5, 5, 5, 5))); // GridBagConstraints gbc_containerPanel = new GridBagConstraints(); // gbc_containerPanel.fill = GridBagConstraints.HORIZONTAL; // gbc_containerPanel.anchor = GridBagConstraints.NORTH; // gbc_containerPanel.gridx = 0; // gbc_containerPanel.gridy = 0; // add(containerPanel, gbc_containerPanel); // GridBagLayout gbl_containerPanel = new GridBagLayout(); // gbl_containerPanel.columnWidths = new int[] { 0, 0 }; // gbl_containerPanel.rowHeights = new int[] { 24, 0 }; // gbl_containerPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; // gbl_containerPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; // containerPanel.setLayout(gbl_containerPanel); // // rotationComboBox = new JComboBox<Rotation>(); // rotationComboBox.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rotationSelectionActionPerformed(e); // } // }); // rotationComboBox.setFont(UIManager.getFont("ComboBox.font")); // rotationComboBox.setModel(new DefaultComboBoxModel<Rotation>(new Rotation[] { Rotation.CW_90, // Rotation.CW_180, Rotation.CW_270 })); // GridBagConstraints gbc_rotationComboBox = new GridBagConstraints(); // gbc_rotationComboBox.anchor = GridBagConstraints.NORTH; // gbc_rotationComboBox.gridx = 0; // gbc_rotationComboBox.gridy = 0; // containerPanel.add(rotationComboBox, gbc_rotationComboBox); // } // // @Override // public final void restoreSettings() { // rotationComboBox.setSelectedItem(transform.getRotation()); // } // // private void rotationSelectionActionPerformed(ActionEvent e) { // transform.setRotation((Rotation) rotationComboBox.getSelectedItem()); // } // // @Override // public final void setTransform(IImageTransform transform) { // this.transform = (RotateTransform) transform; // restoreSettings(); // } // // } // // Path: src/main/java/com/swingsane/preferences/IPreferredDefaults.java // public interface IPreferredDefaults { // // public enum ColorMode { // BLACK_AND_WHITE, COLOR, GRAYSCALE // } // // public enum Source { // AUTOMATIC_DOCUMENT_FEEDER, FLATBED // } // // int DEFAULT_RESOLUTION = 300; // // Rotation DEFAULT_ROTATION = Rotation.CW_90; // // int DEFAULT_LUMINANCE_THRESHOLD = 165; // // double DEFAULT_DESKEW_THRESHOLD = 2.0d; // // ColorMode getColor(); // // double getDefaultDeskewThreshold(); // // int getDefaultLuminanceThreshold(); // // Rotation getDefaultRotation(); // // int getResolution(); // // void setColor(ColorMode color); // // void setResolution(int resolution); // // void update(Scanner scanner); // // } // Path: src/main/java/com/swingsane/business/image/transform/RotateTransform.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.imgscalr.Scalr; import org.imgscalr.Scalr.Rotation; import com.swingsane.gui.panel.ITransformSettingsPanel; import com.swingsane.gui.panel.RotateTransformSettingsPanel; import com.swingsane.preferences.IPreferredDefaults; package com.swingsane.business.image.transform; /** * @author Roland Quast (roland@formreturn.com) * */ public class RotateTransform implements IImageTransform { private Rotation rotation; private File sourceImageFile; private File outputImageFile; private static final ImageTransformType imageTransformType = ImageTransformType.ROTATE; @Override public void configure(IPreferredDefaults preferredDefaultsImpl) { rotation = preferredDefaultsImpl.getDefaultRotation(); } @Override public final File getOutputImageFile() { return outputImageFile; } public final Rotation getRotation() { return rotation; } @Override public final File getSourceImageFile() { return sourceImageFile; } @Override public final ITransformSettingsPanel getTransformSettingsPanel() {
RotateTransformSettingsPanel transformSettingsPanel = new RotateTransformSettingsPanel();
rquast/swingsane
src/main/java/com/swingsane/business/scanning/IScanService.java
// Path: src/main/java/com/swingsane/preferences/model/SaneServiceIdentity.java // @XStreamAlias("saneServiceIdentity") // public class SaneServiceIdentity { // // private String serviceName = DiscoveryJob.SANE_SERVICE_NAME + ""; // // public final String getServiceName() { // if (serviceName == null) { // serviceName = DiscoveryJob.SANE_SERVICE_NAME + ""; // } // return serviceName; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // } // // Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // }
import java.io.IOException; import javax.jmdns.ServiceInfo; import au.com.southsky.jfreesane.SaneDevice; import au.com.southsky.jfreesane.SaneException; import au.com.southsky.jfreesane.SanePasswordProvider; import com.swingsane.preferences.model.SaneServiceIdentity; import com.swingsane.preferences.model.Scanner;
package com.swingsane.business.scanning; /** * @author Roland Quast (roland@formreturn.com) * */ public interface IScanService { void configure(SaneDevice saneDevice, Scanner scanner) throws IOException; Scanner create(SaneDevice saneDevice, ServiceInfo serviceInfo, String hostAddress) throws IOException, SaneException; Scanner create(SaneDevice saneDevice, String hostAddress, int portNumber, String description) throws IOException, SaneException; SanePasswordProvider getPasswordProvider();
// Path: src/main/java/com/swingsane/preferences/model/SaneServiceIdentity.java // @XStreamAlias("saneServiceIdentity") // public class SaneServiceIdentity { // // private String serviceName = DiscoveryJob.SANE_SERVICE_NAME + ""; // // public final String getServiceName() { // if (serviceName == null) { // serviceName = DiscoveryJob.SANE_SERVICE_NAME + ""; // } // return serviceName; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // } // // Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // } // Path: src/main/java/com/swingsane/business/scanning/IScanService.java import java.io.IOException; import javax.jmdns.ServiceInfo; import au.com.southsky.jfreesane.SaneDevice; import au.com.southsky.jfreesane.SaneException; import au.com.southsky.jfreesane.SanePasswordProvider; import com.swingsane.preferences.model.SaneServiceIdentity; import com.swingsane.preferences.model.Scanner; package com.swingsane.business.scanning; /** * @author Roland Quast (roland@formreturn.com) * */ public interface IScanService { void configure(SaneDevice saneDevice, Scanner scanner) throws IOException; Scanner create(SaneDevice saneDevice, ServiceInfo serviceInfo, String hostAddress) throws IOException, SaneException; Scanner create(SaneDevice saneDevice, String hostAddress, int portNumber, String description) throws IOException, SaneException; SanePasswordProvider getPasswordProvider();
SaneServiceIdentity getSaneServiceIdentity();
rquast/swingsane
src/main/java/com/swingsane/business/image/transform/ImageTransformType.java
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import com.swingsane.i18n.Localizer;
package com.swingsane.business.image.transform; public enum ImageTransformType { DESKEW, BINARIZE, ROTATE, CROP; @Override public String toString() { switch (this) { case DESKEW:
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/business/image/transform/ImageTransformType.java import com.swingsane.i18n.Localizer; package com.swingsane.business.image.transform; public enum ImageTransformType { DESKEW, BINARIZE, ROTATE, CROP; @Override public String toString() { switch (this) { case DESKEW:
return Localizer.localize("DeskewTransformName");
rquast/swingsane
src/main/java/com/swingsane/gui/dialog/LoginDialog.java
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // }
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import com.swingsane.i18n.Localizer;
private JTextField resourceTextField; public LoginDialog(Component parent) { initComponents(); pack(); setLocationRelativeTo(parent); } private void cancelButtonActionPerformed(ActionEvent e) { dispose(); } public final int getDialogResult() { return dialogResult; } public final String getPassword() { return new String(passwordField.getPassword()); } public final String getResource() { return resourceTextField.getText(); } public final String getUsername() { return usernameTextField.getText(); } private void initComponents() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// Path: src/main/java/com/swingsane/i18n/Localizer.java // public final class Localizer { // // /** // * Returns the current locale. // * // * @return the current locale // */ // public static Locale getCurrentLocale() { // if (currentLocale == null) { // setCurrentLocale(Locale.getDefault()); // } // return currentLocale; // } // // /** // * Returns a translation for the specified key in the current locale. // * // * @param key // * a translation key listed in the messages resource file // * @return a translation for the specified key in the current locale // */ // public static String localize(String key) { // try { // return BUNDLE.getString(key); // } catch (Exception ex) { // LOG.warn(ex.getLocalizedMessage(), ex); // LOG.warn("Missing translation: " + key); // return key; // } // } // // /** // * Sets the current locale and attempts to load the messages resource file for the locale. // * // * @param currentLocale // * a locale that has a messages resource // */ // public static void setCurrentLocale(Locale currentLocale) { // Localizer.currentLocale = currentLocale; // try { // ResourceBundle.getBundle(MESSAGES_RESOURCE, currentLocale); // } catch (Exception ex) { // ResourceBundle.getBundle(MESSAGES_RESOURCE, DEFAULT_LOCALE); // currentLocale = DEFAULT_LOCALE; // } // } // // private static final String MESSAGES_RESOURCE = "com.swingsane.i18n.messages"; // // private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; // // private static Locale currentLocale = DEFAULT_LOCALE; // // private static final Logger LOG = Logger.getLogger(Localizer.class); // // private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, // getCurrentLocale()); // // private Localizer() { // } // // } // Path: src/main/java/com/swingsane/gui/dialog/LoginDialog.java import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import com.swingsane.i18n.Localizer; private JTextField resourceTextField; public LoginDialog(Component parent) { initComponents(); pack(); setLocationRelativeTo(parent); } private void cancelButtonActionPerformed(ActionEvent e) { dispose(); } public final int getDialogResult() { return dialogResult; } public final String getPassword() { return new String(passwordField.getPassword()); } public final String getResource() { return resourceTextField.getText(); } public final String getUsername() { return usernameTextField.getText(); } private void initComponents() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setTitle(Localizer.localize("LoginDialogTitle"));
rquast/swingsane
src/test/java/com/swingsane/preferences/device/ScannerPreferencesTest.java
// Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.swingsane.preferences.model.Scanner;
package com.swingsane.preferences.device; public class ScannerPreferencesTest { private static final String DEFAULT_SANE_SERVICE_NAME = "saned"; private static final int DEFAULT_SANE_PORT = 6566; private static final String MOCK_REMOTE_ADDRESS = "192.168.1.169"; private static final String MOCK_SCANNER_MODEL = "GT-S50"; private static final String MOCK_VENDOR = "Epson"; private static final String MOCK_NAME = "epkowa:interpreter:002:008"; @Test public void testGetSetModel() throws Exception {
// Path: src/main/java/com/swingsane/preferences/model/Scanner.java // @XStreamAlias("scanner") // public class Scanner extends ScannerOptions { // // private String guid; // private String description; // private String serviceName; // private String remoteAddress; // private int remotePortNumber; // private String vendor; // private String model; // private String name; // private String type; // private int pagesToScan; // private boolean usingCustomOptions; // private String batchPrefix = Localizer.localize("ScanFileNamePrefix") + "_" // + Localizer.localize("TimeStampToken") + "_" + Localizer.localize("PageNumberToken") + "_" // + Localizer.localize("PageCountToken"); // // public Scanner() { // setGuid((new RandomGUID()).toString()); // } // // public final String getBatchPrefix() { // return batchPrefix; // } // // public final String getDescription() { // return description; // } // // public final String getGuid() { // return guid; // } // // public final String getModel() { // return model; // } // // public final String getName() { // return name; // } // // public final int getPagesToScan() { // return pagesToScan; // } // // public final String getRemoteAddress() { // return remoteAddress; // } // // public final int getRemotePortNumber() { // return remotePortNumber; // } // // public final String getServiceName() { // return serviceName; // } // // public final String getType() { // return type; // } // // public final String getVendor() { // return vendor; // } // // public final boolean isUsingCustomOptions() { // return usingCustomOptions; // } // // public final void setBatchPrefix(String batchPrefix) { // this.batchPrefix = batchPrefix; // } // // public final void setDescription(String description) { // this.description = description; // } // // public void setGuid(String guid) { // this.guid = guid; // } // // public final void setModel(String model) { // this.model = model; // } // // public final void setName(String name) { // this.name = name; // } // // public final void setPagesToScan(int pagesToScan) { // this.pagesToScan = pagesToScan; // } // // public final void setRemoteAddress(String remoteAddress) { // this.remoteAddress = remoteAddress; // } // // public final void setRemotePortNumber(int remotePortNumber) { // this.remotePortNumber = remotePortNumber; // } // // public final void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public final void setType(String type) { // this.type = type; // } // // public final void setUsingCustomOptions(boolean usingCustomOptions) { // this.usingCustomOptions = usingCustomOptions; // } // // public final void setVendor(String vendor) { // this.vendor = vendor; // } // // } // Path: src/test/java/com/swingsane/preferences/device/ScannerPreferencesTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.swingsane.preferences.model.Scanner; package com.swingsane.preferences.device; public class ScannerPreferencesTest { private static final String DEFAULT_SANE_SERVICE_NAME = "saned"; private static final int DEFAULT_SANE_PORT = 6566; private static final String MOCK_REMOTE_ADDRESS = "192.168.1.169"; private static final String MOCK_SCANNER_MODEL = "GT-S50"; private static final String MOCK_VENDOR = "Epson"; private static final String MOCK_NAME = "epkowa:interpreter:002:008"; @Test public void testGetSetModel() throws Exception {
Scanner scannerPreferences = new Scanner();