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 |
|---|---|---|---|---|---|---|
palominolabs/benchpress | examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator | HbaseAsyncConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads, |
palominolabs/benchpress | examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator
HbaseAsyncConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator
HbaseAsyncConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | @JsonProperty("keyGen") KeyGen keyGen, @JsonProperty("valueGen") ValueGen valueGen, |
palominolabs/benchpress | examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator
HbaseAsyncConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase-async/src/main/java/com/palominolabs/benchpress/example/multidb/hbaseasync/HbaseAsyncConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbaseasync;
@Immutable
class HbaseAsyncConfig extends TaskConfigBase {
private final String zkQuorum;
private final String table;
private final String columnFamily;
private final String qualifier;
@JsonCreator
HbaseAsyncConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | @JsonProperty("keyGen") KeyGen keyGen, @JsonProperty("valueGen") ValueGen valueGen, |
palominolabs/benchpress | controller-core/src/main/java/com/palominolabs/benchpress/worker/WorkerControl.java | // Path: job/src/main/java/com/palominolabs/benchpress/job/json/JobSlice.java
// @Immutable
// public final class JobSlice {
// private final UUID jobId;
// private final int sliceId;
// private final Task task;
// private final String progressUrl;
// private final String finishedUrl;
//
// @JsonCreator
// public JobSlice(@JsonProperty("jobId") UUID jobId, @JsonProperty("sliceId") int sliceId,
// @JsonProperty("task") Task task, @JsonProperty("progressUrl") String progressUrl,
// @JsonProperty("finishedUrl") String finishedUrl) {
// this.jobId = jobId;
// this.sliceId = sliceId;
// this.task = task;
// this.progressUrl = progressUrl;
// this.finishedUrl = finishedUrl;
// }
//
// @JsonProperty("jobId")
// public UUID getJobId() {
// return jobId;
// }
//
// @JsonProperty("sliceId")
// public int getSliceId() {
// return sliceId;
// }
//
// @JsonProperty("task")
// public Task getTask() {
// return task;
// }
//
// @JsonProperty("progressUrl")
// public String getProgressUrl() {
// return progressUrl;
// }
//
// @JsonProperty("finishedUrl")
// public String getFinishedUrl() {
// return finishedUrl;
// }
// }
| import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.ning.http.client.AsyncHttpClient;
import com.palominolabs.benchpress.job.json.JobSlice;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | if (released) {
logger.info("Successfully released lock of worker <" + metadata.getWorkerId() + ">");
} else {
logger.warn("Releasing lock of worker <" + metadata.getWorkerId() + "> failed");
}
return released;
}
/**
* @return true if the worker is locked
*/
public boolean isLocked() {
return getLockStatus().isLocked();
}
/**
* @return the controller that has this worker locked, null if the worker is not locked
*/
public UUID locker() {
return getLockStatus().getControllerId();
}
/**
* Submit a job to this worker.
*
* @param jobId The job that this slice is part of
* @param jobSlice The slice fot the worker to do
* @return true if the slice was successfully submitted
*/ | // Path: job/src/main/java/com/palominolabs/benchpress/job/json/JobSlice.java
// @Immutable
// public final class JobSlice {
// private final UUID jobId;
// private final int sliceId;
// private final Task task;
// private final String progressUrl;
// private final String finishedUrl;
//
// @JsonCreator
// public JobSlice(@JsonProperty("jobId") UUID jobId, @JsonProperty("sliceId") int sliceId,
// @JsonProperty("task") Task task, @JsonProperty("progressUrl") String progressUrl,
// @JsonProperty("finishedUrl") String finishedUrl) {
// this.jobId = jobId;
// this.sliceId = sliceId;
// this.task = task;
// this.progressUrl = progressUrl;
// this.finishedUrl = finishedUrl;
// }
//
// @JsonProperty("jobId")
// public UUID getJobId() {
// return jobId;
// }
//
// @JsonProperty("sliceId")
// public int getSliceId() {
// return sliceId;
// }
//
// @JsonProperty("task")
// public Task getTask() {
// return task;
// }
//
// @JsonProperty("progressUrl")
// public String getProgressUrl() {
// return progressUrl;
// }
//
// @JsonProperty("finishedUrl")
// public String getFinishedUrl() {
// return finishedUrl;
// }
// }
// Path: controller-core/src/main/java/com/palominolabs/benchpress/worker/WorkerControl.java
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.ning.http.client.AsyncHttpClient;
import com.palominolabs.benchpress.job.json.JobSlice;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (released) {
logger.info("Successfully released lock of worker <" + metadata.getWorkerId() + ">");
} else {
logger.warn("Releasing lock of worker <" + metadata.getWorkerId() + "> failed");
}
return released;
}
/**
* @return true if the worker is locked
*/
public boolean isLocked() {
return getLockStatus().isLocked();
}
/**
* @return the controller that has this worker locked, null if the worker is not locked
*/
public UUID locker() {
return getLockStatus().getControllerId();
}
/**
* Submit a job to this worker.
*
* @param jobId The job that this slice is part of
* @param jobSlice The slice fot the worker to do
* @return true if the slice was successfully submitted
*/ | public boolean submitSlice(UUID jobId, JobSlice jobSlice) { |
palominolabs/benchpress | examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/DefaultKeyGeneratorFactoriesModule.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactoryFactory extends Identifiable {
// KeyGeneratorFactory getKeyGeneratorFactory(Configuration c);
// }
| import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactory; | package com.palominolabs.benchpress.example.multidb.key;
public final class DefaultKeyGeneratorFactoriesModule extends AbstractModule {
@Override
protected void configure() { | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactoryFactory extends Identifiable {
// KeyGeneratorFactory getKeyGeneratorFactory(Configuration c);
// }
// Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/DefaultKeyGeneratorFactoriesModule.java
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactory;
package com.palominolabs.benchpress.example.multidb.key;
public final class DefaultKeyGeneratorFactoriesModule extends AbstractModule {
@Override
protected void configure() { | Multibinder<KeyGeneratorFactoryFactory> binder = |
palominolabs/benchpress | examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/DefaultValueGeneratorFactoryFactoriesModule.java | // Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactory.java
// @ThreadSafe
// public interface ValueGeneratorFactoryFactory extends Identifiable {
//
// @Nonnull
// ValueGeneratorFactory getFactory(Configuration c);
// }
| import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactory; | package com.palominolabs.benchpress.example.multidb.value;
public final class DefaultValueGeneratorFactoryFactoriesModule extends AbstractModule{
@Override
protected void configure() { | // Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactory.java
// @ThreadSafe
// public interface ValueGeneratorFactoryFactory extends Identifiable {
//
// @Nonnull
// ValueGeneratorFactory getFactory(Configuration c);
// }
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/DefaultValueGeneratorFactoryFactoriesModule.java
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactory;
package com.palominolabs.benchpress.example.multidb.value;
public final class DefaultValueGeneratorFactoryFactoriesModule extends AbstractModule{
@Override
protected void configure() { | Multibinder<ValueGeneratorFactoryFactory> binder = |
palominolabs/benchpress | integration-test/src/test/java/com/palominolabs/benchpress/task/simplehttp/SimpleHttpTaskModule.java | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin; | package com.palominolabs.benchpress.task.simplehttp;
public final class SimpleHttpTaskModule extends AbstractModule {
@Override
protected void configure() { | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: integration-test/src/test/java/com/palominolabs/benchpress/task/simplehttp/SimpleHttpTaskModule.java
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
package com.palominolabs.benchpress.task.simplehttp;
public final class SimpleHttpTaskModule extends AbstractModule {
@Override
protected void configure() { | Multibinder.newSetBinder(binder(), JobTypePlugin.class).addBinding().to(SimpleHttpJobTypePlugin.class); |
palominolabs/benchpress | examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator | HBaseConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads, |
palominolabs/benchpress | examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator
HBaseConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator
HBaseConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | @JsonProperty("keyGen") KeyGen keyGen, @JsonProperty("valueGen") ValueGen valueGen, |
palominolabs/benchpress | examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable; | package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator
HBaseConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGen.java
// @Immutable
// public final class KeyGen {
// private final Map<String, Object> config;
//
// @JsonProperty("type")
// public final String keyGenType;
//
// @JsonCreator
// public KeyGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String keyGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.keyGenType = keyGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskConfigBase.java
// @Immutable
// public abstract class TaskConfigBase {
//
// private final TaskOperation taskOperation;
//
// private final int numThreads;
//
// private final int numQuanta;
//
// private final int batchSize;
//
// private final KeyGen keyGen;
//
// private final ValueGen valueGen;
//
// protected TaskConfigBase(TaskOperation taskOperation, int numThreads, int numQuanta, int batchSize, KeyGen keyGen,
// ValueGen valueGen) {
// this.taskOperation = taskOperation;
// this.numThreads = numThreads;
// this.numQuanta = numQuanta;
// this.batchSize = batchSize;
// this.keyGen = keyGen;
// this.valueGen = valueGen;
// }
//
// public int getBatchSize() {
// return batchSize;
// }
//
// public KeyGen getKeyGen() {
// return keyGen;
// }
//
// public int getNumQuanta() {
// return numQuanta;
// }
//
// public int getNumThreads() {
// return numThreads;
// }
//
// public TaskOperation getTaskOperation() {
// return taskOperation;
// }
//
// public ValueGen getValueGen() {
// return valueGen;
// }
//
// /**
// * @param newQuanta the new quanta to use
// * @return a copy of this with a different quanta
// */
// public abstract TaskConfigBase withNewQuanta(int newQuanta);
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGen.java
// @Immutable
// public final class ValueGen {
// private final String valueGenType;
//
// private final Map<String, Object> config;
//
// @JsonCreator
// public ValueGen(@JsonProperty("config") Map<String, Object> config, @JsonProperty("type") String valueGenType) {
// this.config = config == null ? null : new ImmutableMap.Builder<String, Object>().putAll(config).build();
// this.valueGenType = valueGenType;
// }
//
// @JsonProperty("config")
// public Map<String, Object> getJsonConfig() {
// return config;
// }
//
// @JsonProperty("type")
// public String getValueGenType() {
// return valueGenType;
// }
//
// /**
// * @return dev-friendly version of config
// */
// public Configuration getConfig() {
// return new MapConfiguration(config);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
// Path: examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HBaseConfig.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.palominolabs.benchpress.example.multidb.key.KeyGen;
import com.palominolabs.benchpress.example.multidb.task.TaskConfigBase;
import com.palominolabs.benchpress.example.multidb.value.ValueGen;
import com.palominolabs.benchpress.job.task.TaskOperation;
import javax.annotation.concurrent.Immutable;
package com.palominolabs.benchpress.example.multidb.hbase;
@Immutable
class HBaseConfig extends TaskConfigBase {
private final String zkQuorum;
private final int zkPort;
private final String table;
private final String columnFamily;
private final String qualifier;
private final boolean autoFlush;
private final Long writeBufferSize;
@JsonCreator
HBaseConfig(@JsonProperty("op") TaskOperation taskOperation, @JsonProperty("threads") int numThreads,
@JsonProperty("quanta") int numQuanta, @JsonProperty("batchSize") int batchSize, | @JsonProperty("keyGen") KeyGen keyGen, @JsonProperty("valueGen") ValueGen valueGen, |
palominolabs/benchpress | job/src/main/java/com/palominolabs/benchpress/job/task/TaskFactory.java | // Path: task-reporting/src/main/java/com/palominolabs/benchpress/task/reporting/ScopedProgressClient.java
// public class ScopedProgressClient {
//
// private final UUID jobId;
//
// private final int sliceId;
//
// private final String jobFinishedUrl;
// private final String jobProgressUrl;
// private final TaskProgressClient client;
//
// public ScopedProgressClient(UUID jobId, int sliceId, String jobFinishedUrl, String jobProgressUrl, TaskProgressClient client) {
// this.jobId = jobId;
// this.sliceId = sliceId;
// this.jobFinishedUrl = jobFinishedUrl;
// this.jobProgressUrl = jobProgressUrl;
// this.client = client;
// }
//
// public void reportFinished(Duration duration) {
// client.reportFinished(jobId, sliceId, duration, jobFinishedUrl);
// }
//
// public void reportProgress(JsonNode data) {
// client.reportProgress(jobId, sliceId, data, jobProgressUrl);
// }
// }
| import com.palominolabs.benchpress.task.reporting.ScopedProgressClient;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID; | package com.palominolabs.benchpress.job.task;
/**
* A TaskFactory creates the runnables that actually do the work. Used to create the runnables for one individual
* slice.
*/
@NotThreadSafe
public interface TaskFactory {
/**
* @param jobId job id
* @param sliceId the slice of the overall job that these tasks are part of
* @param workerId the worker that these tasks are running in
* @param progressClient client the workers can use to hand any notable data back to the controller
* @return runnables
* @throws IOException if task creation fails
*/
@Nonnull
Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId, | // Path: task-reporting/src/main/java/com/palominolabs/benchpress/task/reporting/ScopedProgressClient.java
// public class ScopedProgressClient {
//
// private final UUID jobId;
//
// private final int sliceId;
//
// private final String jobFinishedUrl;
// private final String jobProgressUrl;
// private final TaskProgressClient client;
//
// public ScopedProgressClient(UUID jobId, int sliceId, String jobFinishedUrl, String jobProgressUrl, TaskProgressClient client) {
// this.jobId = jobId;
// this.sliceId = sliceId;
// this.jobFinishedUrl = jobFinishedUrl;
// this.jobProgressUrl = jobProgressUrl;
// this.client = client;
// }
//
// public void reportFinished(Duration duration) {
// client.reportFinished(jobId, sliceId, duration, jobFinishedUrl);
// }
//
// public void reportProgress(JsonNode data) {
// client.reportProgress(jobId, sliceId, data, jobProgressUrl);
// }
// }
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskFactory.java
import com.palominolabs.benchpress.task.reporting.ScopedProgressClient;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
package com.palominolabs.benchpress.job.task;
/**
* A TaskFactory creates the runnables that actually do the work. Used to create the runnables for one individual
* slice.
*/
@NotThreadSafe
public interface TaskFactory {
/**
* @param jobId job id
* @param sliceId the slice of the overall job that these tasks are part of
* @param workerId the worker that these tasks are running in
* @param progressClient client the workers can use to hand any notable data back to the controller
* @return runnables
* @throws IOException if task creation fails
*/
@Nonnull
Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId, | @Nonnull ScopedProgressClient progressClient) throws |
palominolabs/benchpress | controller-core/src/main/java/com/palominolabs/benchpress/controller/ControllerJerseyApp.java | // Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/http/ControllerJobResource.java
// @Path("controller/job")
// @Singleton
// @Produces(MediaType.APPLICATION_JSON)
// public final class ControllerJobResource {
// private JobFarmer jobFarmer;
//
// @Inject
// ControllerJobResource(JobFarmer jobFarmer) {
// this.jobFarmer = jobFarmer;
// }
//
// /**
// * @param task The workload to start
// * @return 202 and the Job object as JSON, 412 on failure
// */
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// public Response submit(Task task) {
// UUID jobId = UUID.randomUUID();
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.submitJob(new Job(task, jobId));
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @GET
// @Produces(MediaType.TEXT_HTML)
// public Response list() {
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("<html>\n<body>\n");
//
// stringBuilder.append("<ul>\n");
// Set<UUID> jobIds = jobFarmer.getJobIds();
// for (UUID jobId : jobIds) {
// stringBuilder.append("<li><a href='/job/").append(jobId).append("'>").append(jobId).append("</a></li>\n");
// }
// stringBuilder.append("</ul>\n");
//
// stringBuilder.append("</html>");
// return Response.status(Response.Status.OK).entity(stringBuilder.toString()).build();
// }
//
// @POST
// @Path("{jobId}/report/finished")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportFinished(@PathParam("jobId") UUID jobId, SliceFinishedReport sliceFinishedReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceFinishedReport(jobId, sliceFinishedReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @POST
// @Path("{jobId}/report/progress")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportProgress(@PathParam("jobId") UUID jobId, SliceProgressReport sliceProgressReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceProgressReport(jobId, sliceProgressReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// /**
// * Get status of a job
// *
// * @param jobId The job to get status of
// * @return 200 and a Job object
// */
// @GET
// @Path("{jobId}")
// public JobStatusResponse get(@PathParam("jobId") UUID jobId) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.getJobStatus(jobId);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/JerseyResourceConfigBase.java
// public class JerseyResourceConfigBase extends ResourceConfig {
//
// /**
// * @param objectMapperContextResolver The {@link ObjectMapperContextResolver} to use for Jackson/Jersey integration,
// * typically available with an {@link com.palominolabs.benchpress.ipc.Ipc}
// * binding annotation.
// */
// public JerseyResourceConfigBase(ObjectMapperContextResolver objectMapperContextResolver) {
// register(JacksonFeature.class);
// register(objectMapperContextResolver);
//
// property(CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
// property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
// property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, true);
// property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/ObjectMapperContextResolver.java
// public final class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
// private final ObjectMapper objectMapper;
//
// ObjectMapperContextResolver(ObjectMapper objectMapper) {
// this.objectMapper = objectMapper;
// }
//
// @Override
// public ObjectMapper getContext(Class<?> type) {
// return objectMapper;
// }
// }
| import com.google.inject.Inject;
import com.palominolabs.benchpress.controller.http.ControllerJobResource;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.jersey.JerseyResourceConfigBase;
import com.palominolabs.benchpress.jersey.ObjectMapperContextResolver; | package com.palominolabs.benchpress.controller;
public class ControllerJerseyApp extends JerseyResourceConfigBase {
@Inject | // Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/http/ControllerJobResource.java
// @Path("controller/job")
// @Singleton
// @Produces(MediaType.APPLICATION_JSON)
// public final class ControllerJobResource {
// private JobFarmer jobFarmer;
//
// @Inject
// ControllerJobResource(JobFarmer jobFarmer) {
// this.jobFarmer = jobFarmer;
// }
//
// /**
// * @param task The workload to start
// * @return 202 and the Job object as JSON, 412 on failure
// */
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// public Response submit(Task task) {
// UUID jobId = UUID.randomUUID();
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.submitJob(new Job(task, jobId));
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @GET
// @Produces(MediaType.TEXT_HTML)
// public Response list() {
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("<html>\n<body>\n");
//
// stringBuilder.append("<ul>\n");
// Set<UUID> jobIds = jobFarmer.getJobIds();
// for (UUID jobId : jobIds) {
// stringBuilder.append("<li><a href='/job/").append(jobId).append("'>").append(jobId).append("</a></li>\n");
// }
// stringBuilder.append("</ul>\n");
//
// stringBuilder.append("</html>");
// return Response.status(Response.Status.OK).entity(stringBuilder.toString()).build();
// }
//
// @POST
// @Path("{jobId}/report/finished")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportFinished(@PathParam("jobId") UUID jobId, SliceFinishedReport sliceFinishedReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceFinishedReport(jobId, sliceFinishedReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @POST
// @Path("{jobId}/report/progress")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportProgress(@PathParam("jobId") UUID jobId, SliceProgressReport sliceProgressReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceProgressReport(jobId, sliceProgressReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// /**
// * Get status of a job
// *
// * @param jobId The job to get status of
// * @return 200 and a Job object
// */
// @GET
// @Path("{jobId}")
// public JobStatusResponse get(@PathParam("jobId") UUID jobId) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.getJobStatus(jobId);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/JerseyResourceConfigBase.java
// public class JerseyResourceConfigBase extends ResourceConfig {
//
// /**
// * @param objectMapperContextResolver The {@link ObjectMapperContextResolver} to use for Jackson/Jersey integration,
// * typically available with an {@link com.palominolabs.benchpress.ipc.Ipc}
// * binding annotation.
// */
// public JerseyResourceConfigBase(ObjectMapperContextResolver objectMapperContextResolver) {
// register(JacksonFeature.class);
// register(objectMapperContextResolver);
//
// property(CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
// property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
// property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, true);
// property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/ObjectMapperContextResolver.java
// public final class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
// private final ObjectMapper objectMapper;
//
// ObjectMapperContextResolver(ObjectMapper objectMapper) {
// this.objectMapper = objectMapper;
// }
//
// @Override
// public ObjectMapper getContext(Class<?> type) {
// return objectMapper;
// }
// }
// Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/ControllerJerseyApp.java
import com.google.inject.Inject;
import com.palominolabs.benchpress.controller.http.ControllerJobResource;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.jersey.JerseyResourceConfigBase;
import com.palominolabs.benchpress.jersey.ObjectMapperContextResolver;
package com.palominolabs.benchpress.controller;
public class ControllerJerseyApp extends JerseyResourceConfigBase {
@Inject | ControllerJerseyApp(@Ipc ObjectMapperContextResolver objectMapperContextResolver) { |
palominolabs/benchpress | controller-core/src/main/java/com/palominolabs/benchpress/controller/ControllerJerseyApp.java | // Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/http/ControllerJobResource.java
// @Path("controller/job")
// @Singleton
// @Produces(MediaType.APPLICATION_JSON)
// public final class ControllerJobResource {
// private JobFarmer jobFarmer;
//
// @Inject
// ControllerJobResource(JobFarmer jobFarmer) {
// this.jobFarmer = jobFarmer;
// }
//
// /**
// * @param task The workload to start
// * @return 202 and the Job object as JSON, 412 on failure
// */
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// public Response submit(Task task) {
// UUID jobId = UUID.randomUUID();
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.submitJob(new Job(task, jobId));
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @GET
// @Produces(MediaType.TEXT_HTML)
// public Response list() {
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("<html>\n<body>\n");
//
// stringBuilder.append("<ul>\n");
// Set<UUID> jobIds = jobFarmer.getJobIds();
// for (UUID jobId : jobIds) {
// stringBuilder.append("<li><a href='/job/").append(jobId).append("'>").append(jobId).append("</a></li>\n");
// }
// stringBuilder.append("</ul>\n");
//
// stringBuilder.append("</html>");
// return Response.status(Response.Status.OK).entity(stringBuilder.toString()).build();
// }
//
// @POST
// @Path("{jobId}/report/finished")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportFinished(@PathParam("jobId") UUID jobId, SliceFinishedReport sliceFinishedReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceFinishedReport(jobId, sliceFinishedReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @POST
// @Path("{jobId}/report/progress")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportProgress(@PathParam("jobId") UUID jobId, SliceProgressReport sliceProgressReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceProgressReport(jobId, sliceProgressReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// /**
// * Get status of a job
// *
// * @param jobId The job to get status of
// * @return 200 and a Job object
// */
// @GET
// @Path("{jobId}")
// public JobStatusResponse get(@PathParam("jobId") UUID jobId) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.getJobStatus(jobId);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/JerseyResourceConfigBase.java
// public class JerseyResourceConfigBase extends ResourceConfig {
//
// /**
// * @param objectMapperContextResolver The {@link ObjectMapperContextResolver} to use for Jackson/Jersey integration,
// * typically available with an {@link com.palominolabs.benchpress.ipc.Ipc}
// * binding annotation.
// */
// public JerseyResourceConfigBase(ObjectMapperContextResolver objectMapperContextResolver) {
// register(JacksonFeature.class);
// register(objectMapperContextResolver);
//
// property(CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
// property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
// property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, true);
// property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/ObjectMapperContextResolver.java
// public final class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
// private final ObjectMapper objectMapper;
//
// ObjectMapperContextResolver(ObjectMapper objectMapper) {
// this.objectMapper = objectMapper;
// }
//
// @Override
// public ObjectMapper getContext(Class<?> type) {
// return objectMapper;
// }
// }
| import com.google.inject.Inject;
import com.palominolabs.benchpress.controller.http.ControllerJobResource;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.jersey.JerseyResourceConfigBase;
import com.palominolabs.benchpress.jersey.ObjectMapperContextResolver; | package com.palominolabs.benchpress.controller;
public class ControllerJerseyApp extends JerseyResourceConfigBase {
@Inject
ControllerJerseyApp(@Ipc ObjectMapperContextResolver objectMapperContextResolver) {
super(objectMapperContextResolver);
| // Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/http/ControllerJobResource.java
// @Path("controller/job")
// @Singleton
// @Produces(MediaType.APPLICATION_JSON)
// public final class ControllerJobResource {
// private JobFarmer jobFarmer;
//
// @Inject
// ControllerJobResource(JobFarmer jobFarmer) {
// this.jobFarmer = jobFarmer;
// }
//
// /**
// * @param task The workload to start
// * @return 202 and the Job object as JSON, 412 on failure
// */
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// public Response submit(Task task) {
// UUID jobId = UUID.randomUUID();
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.submitJob(new Job(task, jobId));
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @GET
// @Produces(MediaType.TEXT_HTML)
// public Response list() {
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("<html>\n<body>\n");
//
// stringBuilder.append("<ul>\n");
// Set<UUID> jobIds = jobFarmer.getJobIds();
// for (UUID jobId : jobIds) {
// stringBuilder.append("<li><a href='/job/").append(jobId).append("'>").append(jobId).append("</a></li>\n");
// }
// stringBuilder.append("</ul>\n");
//
// stringBuilder.append("</html>");
// return Response.status(Response.Status.OK).entity(stringBuilder.toString()).build();
// }
//
// @POST
// @Path("{jobId}/report/finished")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportFinished(@PathParam("jobId") UUID jobId, SliceFinishedReport sliceFinishedReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceFinishedReport(jobId, sliceFinishedReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// @POST
// @Path("{jobId}/report/progress")
// @Consumes(MediaType.APPLICATION_JSON)
// public Response reportProgress(@PathParam("jobId") UUID jobId, SliceProgressReport sliceProgressReport) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.handleSliceProgressReport(jobId, sliceProgressReport);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
//
// /**
// * Get status of a job
// *
// * @param jobId The job to get status of
// * @return 200 and a Job object
// */
// @GET
// @Path("{jobId}")
// public JobStatusResponse get(@PathParam("jobId") UUID jobId) {
// MDC.put(MdcKeys.JOB_ID, jobId.toString());
//
// try {
// return jobFarmer.getJobStatus(jobId);
// } finally {
// MDC.remove(MdcKeys.JOB_ID);
// }
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/JerseyResourceConfigBase.java
// public class JerseyResourceConfigBase extends ResourceConfig {
//
// /**
// * @param objectMapperContextResolver The {@link ObjectMapperContextResolver} to use for Jackson/Jersey integration,
// * typically available with an {@link com.palominolabs.benchpress.ipc.Ipc}
// * binding annotation.
// */
// public JerseyResourceConfigBase(ObjectMapperContextResolver objectMapperContextResolver) {
// register(JacksonFeature.class);
// register(objectMapperContextResolver);
//
// property(CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
// property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
// property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, true);
// property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, true);
// }
// }
//
// Path: jersey-support/src/main/java/com/palominolabs/benchpress/jersey/ObjectMapperContextResolver.java
// public final class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
// private final ObjectMapper objectMapper;
//
// ObjectMapperContextResolver(ObjectMapper objectMapper) {
// this.objectMapper = objectMapper;
// }
//
// @Override
// public ObjectMapper getContext(Class<?> type) {
// return objectMapper;
// }
// }
// Path: controller-core/src/main/java/com/palominolabs/benchpress/controller/ControllerJerseyApp.java
import com.google.inject.Inject;
import com.palominolabs.benchpress.controller.http.ControllerJobResource;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.jersey.JerseyResourceConfigBase;
import com.palominolabs.benchpress.jersey.ObjectMapperContextResolver;
package com.palominolabs.benchpress.controller;
public class ControllerJerseyApp extends JerseyResourceConfigBase {
@Inject
ControllerJerseyApp(@Ipc ObjectMapperContextResolver objectMapperContextResolver) {
super(objectMapperContextResolver);
| register(ControllerJobResource.class); |
palominolabs/benchpress | examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskFactoryBase.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactory {
// /**
// * Should be called by each worker thread.
// *
// * @return a KeyGenerator
// */
// KeyGenerator getKeyGenerator();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactory.java
// @NotThreadSafe
// public interface ValueGeneratorFactory {
// ValueGenerator getValueGenerator();
// }
| import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory;
import com.palominolabs.benchpress.job.task.TaskOperation;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory; | package com.palominolabs.benchpress.example.multidb.task;
/**
* Convenience base class for the default task factories.
*/
public abstract class TaskFactoryBase {
protected final ValueGeneratorFactory valueGeneratorFactory; | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactory {
// /**
// * Should be called by each worker thread.
// *
// * @return a KeyGenerator
// */
// KeyGenerator getKeyGenerator();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactory.java
// @NotThreadSafe
// public interface ValueGeneratorFactory {
// ValueGenerator getValueGenerator();
// }
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskFactoryBase.java
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory;
import com.palominolabs.benchpress.job.task.TaskOperation;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory;
package com.palominolabs.benchpress.example.multidb.task;
/**
* Convenience base class for the default task factories.
*/
public abstract class TaskFactoryBase {
protected final ValueGeneratorFactory valueGeneratorFactory; | protected final KeyGeneratorFactory keyGeneratorFactory; |
palominolabs/benchpress | examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskFactoryBase.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactory {
// /**
// * Should be called by each worker thread.
// *
// * @return a KeyGenerator
// */
// KeyGenerator getKeyGenerator();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactory.java
// @NotThreadSafe
// public interface ValueGeneratorFactory {
// ValueGenerator getValueGenerator();
// }
| import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory;
import com.palominolabs.benchpress.job.task.TaskOperation;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory; | package com.palominolabs.benchpress.example.multidb.task;
/**
* Convenience base class for the default task factories.
*/
public abstract class TaskFactoryBase {
protected final ValueGeneratorFactory valueGeneratorFactory;
protected final KeyGeneratorFactory keyGeneratorFactory; | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactory.java
// @ThreadSafe
// public interface KeyGeneratorFactory {
// /**
// * Should be called by each worker thread.
// *
// * @return a KeyGenerator
// */
// KeyGenerator getKeyGenerator();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/TaskOperation.java
// public enum TaskOperation {
// /** A write operation */
// WRITE,
// /** A read operation */
// READ
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactory.java
// @NotThreadSafe
// public interface ValueGeneratorFactory {
// ValueGenerator getValueGenerator();
// }
// Path: examples/multi-db/job-default-base/src/main/java/com/palominolabs/benchpress/example/multidb/task/TaskFactoryBase.java
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory;
import com.palominolabs.benchpress.job.task.TaskOperation;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory;
package com.palominolabs.benchpress.example.multidb.task;
/**
* Convenience base class for the default task factories.
*/
public abstract class TaskFactoryBase {
protected final ValueGeneratorFactory valueGeneratorFactory;
protected final KeyGeneratorFactory keyGeneratorFactory; | protected final TaskOperation taskOperation; |
palominolabs/benchpress | examples/multi-db/mongodb/src/main/java/com/palominolabs/benchpress/example/multidb/mongodb/MongoDbModule.java | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin; | package com.palominolabs.benchpress.example.multidb.mongodb;
public final class MongoDbModule extends AbstractModule {
@Override
protected void configure() { | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/mongodb/src/main/java/com/palominolabs/benchpress/example/multidb/mongodb/MongoDbModule.java
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
package com.palominolabs.benchpress.example.multidb.mongodb;
public final class MongoDbModule extends AbstractModule {
@Override
protected void configure() { | Multibinder.newSetBinder(binder(), JobTypePlugin.class).addBinding().to(MongoDbJobTypePlugin.class); |
palominolabs/benchpress | examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HbaseModule.java | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin; | package com.palominolabs.benchpress.example.multidb.hbase;
public final class HbaseModule extends AbstractModule {
@Override
protected void configure() { | // Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/hbase/src/main/java/com/palominolabs/benchpress/example/multidb/hbase/HbaseModule.java
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
package com.palominolabs.benchpress.example.multidb.hbase;
public final class HbaseModule extends AbstractModule {
@Override
protected void configure() { | Multibinder.newSetBinder(binder(), JobTypePlugin.class).addBinding().to(HbaseJobTypePlugin.class); |
palominolabs/benchpress | zookeeper/src/main/java/com/palominolabs/benchpress/curator/CuratorModule.java | // Path: zookeeper/src/main/java/com/palominolabs/benchpress/config/ZookeeperConfig.java
// public interface ZookeeperConfig {
// @Config("benchpress.zookeeper.client.connection-string")
// @Default("127.0.0.1:2281")
// String getConnectionString();
//
// @Config("benchpress.zookeeper.path")
// @Default("/benchpress")
// String getBasePath();
//
// @Config("benchpress.zookeeper.worker.servicename")
// @Default("worker")
// String getWorkerServiceName();
// }
//
// Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/WorkerMetadata.java
// @Immutable
// public final class WorkerMetadata {
//
// @JsonProperty("workerId")
// private final UUID workerId;
//
// @JsonProperty("listenAddress")
// private final String listenAddress;
//
// @JsonProperty("listenPort")
// private final int listenPort;
//
// @JsonCreator
// public WorkerMetadata(@JsonProperty("workerId") UUID workerId, @JsonProperty("listenAddress") String listenAddress,
// @JsonProperty("listenPort") int listenPort) {
// this.workerId = workerId;
// this.listenAddress = listenAddress;
// this.listenPort = listenPort;
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// public String getListenAddress() {
// return listenAddress;
// }
//
// public int getListenPort() {
// return listenPort;
// }
//
// public String toString() {
// return workerId.toString() + " (" + listenAddress + ":" + listenPort + ")";
// }
// }
| import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.config.ZookeeperConfig;
import com.palominolabs.benchpress.worker.WorkerMetadata;
import com.palominolabs.config.ConfigModule;
import java.io.IOException;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider; | package com.palominolabs.benchpress.curator;
/**
* If using CuratorModule, make sure to inject CuratorLifecycleHook and run CuratorLifecycleHook.start().
*/
public final class CuratorModule extends AbstractModule {
@Override
protected void configure() { | // Path: zookeeper/src/main/java/com/palominolabs/benchpress/config/ZookeeperConfig.java
// public interface ZookeeperConfig {
// @Config("benchpress.zookeeper.client.connection-string")
// @Default("127.0.0.1:2281")
// String getConnectionString();
//
// @Config("benchpress.zookeeper.path")
// @Default("/benchpress")
// String getBasePath();
//
// @Config("benchpress.zookeeper.worker.servicename")
// @Default("worker")
// String getWorkerServiceName();
// }
//
// Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/WorkerMetadata.java
// @Immutable
// public final class WorkerMetadata {
//
// @JsonProperty("workerId")
// private final UUID workerId;
//
// @JsonProperty("listenAddress")
// private final String listenAddress;
//
// @JsonProperty("listenPort")
// private final int listenPort;
//
// @JsonCreator
// public WorkerMetadata(@JsonProperty("workerId") UUID workerId, @JsonProperty("listenAddress") String listenAddress,
// @JsonProperty("listenPort") int listenPort) {
// this.workerId = workerId;
// this.listenAddress = listenAddress;
// this.listenPort = listenPort;
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// public String getListenAddress() {
// return listenAddress;
// }
//
// public int getListenPort() {
// return listenPort;
// }
//
// public String toString() {
// return workerId.toString() + " (" + listenAddress + ":" + listenPort + ")";
// }
// }
// Path: zookeeper/src/main/java/com/palominolabs/benchpress/curator/CuratorModule.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.config.ZookeeperConfig;
import com.palominolabs.benchpress.worker.WorkerMetadata;
import com.palominolabs.config.ConfigModule;
import java.io.IOException;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider;
package com.palominolabs.benchpress.curator;
/**
* If using CuratorModule, make sure to inject CuratorLifecycleHook and run CuratorLifecycleHook.start().
*/
public final class CuratorModule extends AbstractModule {
@Override
protected void configure() { | ConfigModule.bindConfigBean(binder(), ZookeeperConfig.class); |
palominolabs/benchpress | zookeeper/src/main/java/com/palominolabs/benchpress/curator/CuratorModule.java | // Path: zookeeper/src/main/java/com/palominolabs/benchpress/config/ZookeeperConfig.java
// public interface ZookeeperConfig {
// @Config("benchpress.zookeeper.client.connection-string")
// @Default("127.0.0.1:2281")
// String getConnectionString();
//
// @Config("benchpress.zookeeper.path")
// @Default("/benchpress")
// String getBasePath();
//
// @Config("benchpress.zookeeper.worker.servicename")
// @Default("worker")
// String getWorkerServiceName();
// }
//
// Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/WorkerMetadata.java
// @Immutable
// public final class WorkerMetadata {
//
// @JsonProperty("workerId")
// private final UUID workerId;
//
// @JsonProperty("listenAddress")
// private final String listenAddress;
//
// @JsonProperty("listenPort")
// private final int listenPort;
//
// @JsonCreator
// public WorkerMetadata(@JsonProperty("workerId") UUID workerId, @JsonProperty("listenAddress") String listenAddress,
// @JsonProperty("listenPort") int listenPort) {
// this.workerId = workerId;
// this.listenAddress = listenAddress;
// this.listenPort = listenPort;
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// public String getListenAddress() {
// return listenAddress;
// }
//
// public int getListenPort() {
// return listenPort;
// }
//
// public String toString() {
// return workerId.toString() + " (" + listenAddress + ":" + listenPort + ")";
// }
// }
| import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.config.ZookeeperConfig;
import com.palominolabs.benchpress.worker.WorkerMetadata;
import com.palominolabs.config.ConfigModule;
import java.io.IOException;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider; | package com.palominolabs.benchpress.curator;
/**
* If using CuratorModule, make sure to inject CuratorLifecycleHook and run CuratorLifecycleHook.start().
*/
public final class CuratorModule extends AbstractModule {
@Override
protected void configure() {
ConfigModule.bindConfigBean(binder(), ZookeeperConfig.class);
bind(CuratorLifecycleHook.class);
ObjectMapper objectMapper = new ObjectMapper();
bind(InstanceSerializerFactory.class)
.toInstance(new InstanceSerializerFactory(objectMapper.reader(), objectMapper.writer()));
}
@Provides
@Singleton
public CuratorFramework getCuratorFramework(ZookeeperConfig zookeeperConfig) {
return CuratorFrameworkFactory.builder()
.connectionTimeoutMs(1000)
.retryPolicy(new ExponentialBackoffRetry(1000, 10))
.connectString(zookeeperConfig.getConnectionString())
.build();
}
@Provides
@Singleton | // Path: zookeeper/src/main/java/com/palominolabs/benchpress/config/ZookeeperConfig.java
// public interface ZookeeperConfig {
// @Config("benchpress.zookeeper.client.connection-string")
// @Default("127.0.0.1:2281")
// String getConnectionString();
//
// @Config("benchpress.zookeeper.path")
// @Default("/benchpress")
// String getBasePath();
//
// @Config("benchpress.zookeeper.worker.servicename")
// @Default("worker")
// String getWorkerServiceName();
// }
//
// Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/WorkerMetadata.java
// @Immutable
// public final class WorkerMetadata {
//
// @JsonProperty("workerId")
// private final UUID workerId;
//
// @JsonProperty("listenAddress")
// private final String listenAddress;
//
// @JsonProperty("listenPort")
// private final int listenPort;
//
// @JsonCreator
// public WorkerMetadata(@JsonProperty("workerId") UUID workerId, @JsonProperty("listenAddress") String listenAddress,
// @JsonProperty("listenPort") int listenPort) {
// this.workerId = workerId;
// this.listenAddress = listenAddress;
// this.listenPort = listenPort;
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// public String getListenAddress() {
// return listenAddress;
// }
//
// public int getListenPort() {
// return listenPort;
// }
//
// public String toString() {
// return workerId.toString() + " (" + listenAddress + ":" + listenPort + ")";
// }
// }
// Path: zookeeper/src/main/java/com/palominolabs/benchpress/curator/CuratorModule.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.config.ZookeeperConfig;
import com.palominolabs.benchpress.worker.WorkerMetadata;
import com.palominolabs.config.ConfigModule;
import java.io.IOException;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider;
package com.palominolabs.benchpress.curator;
/**
* If using CuratorModule, make sure to inject CuratorLifecycleHook and run CuratorLifecycleHook.start().
*/
public final class CuratorModule extends AbstractModule {
@Override
protected void configure() {
ConfigModule.bindConfigBean(binder(), ZookeeperConfig.class);
bind(CuratorLifecycleHook.class);
ObjectMapper objectMapper = new ObjectMapper();
bind(InstanceSerializerFactory.class)
.toInstance(new InstanceSerializerFactory(objectMapper.reader(), objectMapper.writer()));
}
@Provides
@Singleton
public CuratorFramework getCuratorFramework(ZookeeperConfig zookeeperConfig) {
return CuratorFrameworkFactory.builder()
.connectionTimeoutMs(1000)
.retryPolicy(new ExponentialBackoffRetry(1000, 10))
.connectString(zookeeperConfig.getConnectionString())
.build();
}
@Provides
@Singleton | public ServiceDiscovery<WorkerMetadata> getServiceDiscovery(ZookeeperConfig zookeeperConfig, |
palominolabs/benchpress | worker-core/src/main/java/com/palominolabs/benchpress/worker/http/WorkerControlResource.java | // Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/LockStatus.java
// @Immutable
// public class LockStatus {
// @JsonProperty("locked")
// private final boolean locked;
//
// @JsonProperty("controllerId")
// private final UUID controllerId;
//
// @JsonCreator
// public LockStatus(@JsonProperty("locked") boolean locked, @JsonProperty("controllerId") UUID controllerId) {
// this.locked = locked;
// this.controllerId = controllerId;
// }
//
// public boolean isLocked() {
// return locked;
// }
//
// public UUID getControllerId() {
// return controllerId;
// }
// }
//
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/WorkerAdvertiser.java
// @Singleton
// @ThreadSafe
// public final class WorkerAdvertiser {
// private static final Logger logger = LoggerFactory.getLogger(WorkerAdvertiser.class);
//
// private final ZookeeperConfig zookeeperConfig;
//
// private final UUID workerId = UUID.randomUUID();
//
// private final ServiceDiscovery<WorkerMetadata> serviceDiscovery;
// @GuardedBy("this")
// private String listenAddress;
//
// @GuardedBy("this")
// private int listenPort;
//
// @Inject
// WorkerAdvertiser(ZookeeperConfig zookeeperConfig, ServiceDiscovery<WorkerMetadata> serviceDiscovery) {
// this.zookeeperConfig = zookeeperConfig;
// this.serviceDiscovery = serviceDiscovery;
// }
//
// /**
// * This must be called before other methods are used.
// *
// * @param address address this worker is listening on
// * @param port port this worker is listening on
// */
// public synchronized void initListenInfo(@Nonnull String address, int port) {
// if (listenAddress != null) {
// throw new IllegalStateException("Already initialized");
// }
// this.listenAddress = address;
// this.listenPort = port;
// }
//
// public synchronized void advertiseAvailability() {
// checkInitialized();
// logger.info("Advertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.registerService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public synchronized void deAdvertiseAvailability() {
// checkInitialized();
// logger.info("Deadvertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.unregisterService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// private ServiceInstance<WorkerMetadata> getServiceInstance() throws Exception {
// WorkerMetadata workerMetadata = new WorkerMetadata(workerId, listenAddress, listenPort);
// return ServiceInstance.<WorkerMetadata>builder()
// .name(zookeeperConfig.getWorkerServiceName())
// .address(listenAddress)
// .port(listenPort)
// .id(workerId.toString())
// .payload(workerMetadata)
// .build();
// }
//
// private void checkInitialized() {
// if (listenAddress == null) {
// throw new IllegalStateException("Not initialized");
// }
// }
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.worker.LockStatus;
import com.palominolabs.benchpress.worker.WorkerAdvertiser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.UUID; | package com.palominolabs.benchpress.worker.http;
@Path("worker/control")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public final class WorkerControlResource {
private static final Logger logger = LoggerFactory.getLogger(WorkerControlResource.class);
@GuardedBy("this")
private boolean locked = false;
@GuardedBy("this")
@Nullable
private UUID lockingControllerId = null;
| // Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/LockStatus.java
// @Immutable
// public class LockStatus {
// @JsonProperty("locked")
// private final boolean locked;
//
// @JsonProperty("controllerId")
// private final UUID controllerId;
//
// @JsonCreator
// public LockStatus(@JsonProperty("locked") boolean locked, @JsonProperty("controllerId") UUID controllerId) {
// this.locked = locked;
// this.controllerId = controllerId;
// }
//
// public boolean isLocked() {
// return locked;
// }
//
// public UUID getControllerId() {
// return controllerId;
// }
// }
//
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/WorkerAdvertiser.java
// @Singleton
// @ThreadSafe
// public final class WorkerAdvertiser {
// private static final Logger logger = LoggerFactory.getLogger(WorkerAdvertiser.class);
//
// private final ZookeeperConfig zookeeperConfig;
//
// private final UUID workerId = UUID.randomUUID();
//
// private final ServiceDiscovery<WorkerMetadata> serviceDiscovery;
// @GuardedBy("this")
// private String listenAddress;
//
// @GuardedBy("this")
// private int listenPort;
//
// @Inject
// WorkerAdvertiser(ZookeeperConfig zookeeperConfig, ServiceDiscovery<WorkerMetadata> serviceDiscovery) {
// this.zookeeperConfig = zookeeperConfig;
// this.serviceDiscovery = serviceDiscovery;
// }
//
// /**
// * This must be called before other methods are used.
// *
// * @param address address this worker is listening on
// * @param port port this worker is listening on
// */
// public synchronized void initListenInfo(@Nonnull String address, int port) {
// if (listenAddress != null) {
// throw new IllegalStateException("Already initialized");
// }
// this.listenAddress = address;
// this.listenPort = port;
// }
//
// public synchronized void advertiseAvailability() {
// checkInitialized();
// logger.info("Advertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.registerService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public synchronized void deAdvertiseAvailability() {
// checkInitialized();
// logger.info("Deadvertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.unregisterService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// private ServiceInstance<WorkerMetadata> getServiceInstance() throws Exception {
// WorkerMetadata workerMetadata = new WorkerMetadata(workerId, listenAddress, listenPort);
// return ServiceInstance.<WorkerMetadata>builder()
// .name(zookeeperConfig.getWorkerServiceName())
// .address(listenAddress)
// .port(listenPort)
// .id(workerId.toString())
// .payload(workerMetadata)
// .build();
// }
//
// private void checkInitialized() {
// if (listenAddress == null) {
// throw new IllegalStateException("Not initialized");
// }
// }
// }
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/http/WorkerControlResource.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.worker.LockStatus;
import com.palominolabs.benchpress.worker.WorkerAdvertiser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.UUID;
package com.palominolabs.benchpress.worker.http;
@Path("worker/control")
@Singleton
@Produces(MediaType.APPLICATION_JSON)
public final class WorkerControlResource {
private static final Logger logger = LoggerFactory.getLogger(WorkerControlResource.class);
@GuardedBy("this")
private boolean locked = false;
@GuardedBy("this")
@Nullable
private UUID lockingControllerId = null;
| private final WorkerAdvertiser workerAdvertiser; |
palominolabs/benchpress | worker-core/src/main/java/com/palominolabs/benchpress/worker/http/WorkerControlResource.java | // Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/LockStatus.java
// @Immutable
// public class LockStatus {
// @JsonProperty("locked")
// private final boolean locked;
//
// @JsonProperty("controllerId")
// private final UUID controllerId;
//
// @JsonCreator
// public LockStatus(@JsonProperty("locked") boolean locked, @JsonProperty("controllerId") UUID controllerId) {
// this.locked = locked;
// this.controllerId = controllerId;
// }
//
// public boolean isLocked() {
// return locked;
// }
//
// public UUID getControllerId() {
// return controllerId;
// }
// }
//
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/WorkerAdvertiser.java
// @Singleton
// @ThreadSafe
// public final class WorkerAdvertiser {
// private static final Logger logger = LoggerFactory.getLogger(WorkerAdvertiser.class);
//
// private final ZookeeperConfig zookeeperConfig;
//
// private final UUID workerId = UUID.randomUUID();
//
// private final ServiceDiscovery<WorkerMetadata> serviceDiscovery;
// @GuardedBy("this")
// private String listenAddress;
//
// @GuardedBy("this")
// private int listenPort;
//
// @Inject
// WorkerAdvertiser(ZookeeperConfig zookeeperConfig, ServiceDiscovery<WorkerMetadata> serviceDiscovery) {
// this.zookeeperConfig = zookeeperConfig;
// this.serviceDiscovery = serviceDiscovery;
// }
//
// /**
// * This must be called before other methods are used.
// *
// * @param address address this worker is listening on
// * @param port port this worker is listening on
// */
// public synchronized void initListenInfo(@Nonnull String address, int port) {
// if (listenAddress != null) {
// throw new IllegalStateException("Already initialized");
// }
// this.listenAddress = address;
// this.listenPort = port;
// }
//
// public synchronized void advertiseAvailability() {
// checkInitialized();
// logger.info("Advertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.registerService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public synchronized void deAdvertiseAvailability() {
// checkInitialized();
// logger.info("Deadvertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.unregisterService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// private ServiceInstance<WorkerMetadata> getServiceInstance() throws Exception {
// WorkerMetadata workerMetadata = new WorkerMetadata(workerId, listenAddress, listenPort);
// return ServiceInstance.<WorkerMetadata>builder()
// .name(zookeeperConfig.getWorkerServiceName())
// .address(listenAddress)
// .port(listenPort)
// .id(workerId.toString())
// .payload(workerMetadata)
// .build();
// }
//
// private void checkInitialized() {
// if (listenAddress == null) {
// throw new IllegalStateException("Not initialized");
// }
// }
// }
| import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.worker.LockStatus;
import com.palominolabs.benchpress.worker.WorkerAdvertiser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.UUID; | @Path("releaseLock/{controllerId}")
public synchronized Response releaseLock(@PathParam("controllerId") UUID controllerId) {
synchronized (this) {
Response response = expectLockStatus(true);
if (response != null) {
return response;
}
if (!controllerId.equals(lockingControllerId)) {
logger.info(
"Attempt to unlock with controllerId <" + controllerId + "> but locked by <" + lockingControllerId +
">");
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
logger.info("controllerId <" + controllerId + "> released lock");
lockingControllerId = null;
locked = false;
}
workerAdvertiser.advertiseAvailability();
return Response.noContent().build();
}
/**
* @return the JSON LockStatus object
*/
@GET
@Path("lockStatus") | // Path: worker-data/src/main/java/com/palominolabs/benchpress/worker/LockStatus.java
// @Immutable
// public class LockStatus {
// @JsonProperty("locked")
// private final boolean locked;
//
// @JsonProperty("controllerId")
// private final UUID controllerId;
//
// @JsonCreator
// public LockStatus(@JsonProperty("locked") boolean locked, @JsonProperty("controllerId") UUID controllerId) {
// this.locked = locked;
// this.controllerId = controllerId;
// }
//
// public boolean isLocked() {
// return locked;
// }
//
// public UUID getControllerId() {
// return controllerId;
// }
// }
//
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/WorkerAdvertiser.java
// @Singleton
// @ThreadSafe
// public final class WorkerAdvertiser {
// private static final Logger logger = LoggerFactory.getLogger(WorkerAdvertiser.class);
//
// private final ZookeeperConfig zookeeperConfig;
//
// private final UUID workerId = UUID.randomUUID();
//
// private final ServiceDiscovery<WorkerMetadata> serviceDiscovery;
// @GuardedBy("this")
// private String listenAddress;
//
// @GuardedBy("this")
// private int listenPort;
//
// @Inject
// WorkerAdvertiser(ZookeeperConfig zookeeperConfig, ServiceDiscovery<WorkerMetadata> serviceDiscovery) {
// this.zookeeperConfig = zookeeperConfig;
// this.serviceDiscovery = serviceDiscovery;
// }
//
// /**
// * This must be called before other methods are used.
// *
// * @param address address this worker is listening on
// * @param port port this worker is listening on
// */
// public synchronized void initListenInfo(@Nonnull String address, int port) {
// if (listenAddress != null) {
// throw new IllegalStateException("Already initialized");
// }
// this.listenAddress = address;
// this.listenPort = port;
// }
//
// public synchronized void advertiseAvailability() {
// checkInitialized();
// logger.info("Advertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.registerService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public synchronized void deAdvertiseAvailability() {
// checkInitialized();
// logger.info("Deadvertising availability at <" + listenAddress + ":" + listenPort + ">");
//
// try {
// serviceDiscovery.unregisterService(getServiceInstance());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public UUID getWorkerId() {
// return workerId;
// }
//
// private ServiceInstance<WorkerMetadata> getServiceInstance() throws Exception {
// WorkerMetadata workerMetadata = new WorkerMetadata(workerId, listenAddress, listenPort);
// return ServiceInstance.<WorkerMetadata>builder()
// .name(zookeeperConfig.getWorkerServiceName())
// .address(listenAddress)
// .port(listenPort)
// .id(workerId.toString())
// .payload(workerMetadata)
// .build();
// }
//
// private void checkInitialized() {
// if (listenAddress == null) {
// throw new IllegalStateException("Not initialized");
// }
// }
// }
// Path: worker-core/src/main/java/com/palominolabs/benchpress/worker/http/WorkerControlResource.java
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.worker.LockStatus;
import com.palominolabs.benchpress.worker.WorkerAdvertiser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.UUID;
@Path("releaseLock/{controllerId}")
public synchronized Response releaseLock(@PathParam("controllerId") UUID controllerId) {
synchronized (this) {
Response response = expectLockStatus(true);
if (response != null) {
return response;
}
if (!controllerId.equals(lockingControllerId)) {
logger.info(
"Attempt to unlock with controllerId <" + controllerId + "> but locked by <" + lockingControllerId +
">");
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
logger.info("controllerId <" + controllerId + "> released lock");
lockingControllerId = null;
locked = false;
}
workerAdvertiser.advertiseAvailability();
return Response.noContent().build();
}
/**
* @return the JSON LockStatus object
*/
@GET
@Path("lockStatus") | public synchronized LockStatus getLockStatus() { |
palominolabs/benchpress | examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull; | package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
| // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull;
package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
| private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry; |
palominolabs/benchpress | examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull; | package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry; | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull;
package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry; | private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry; |
palominolabs/benchpress | examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull; | package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull;
package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override | public ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException { |
palominolabs/benchpress | examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull; | package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override
public ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException {
return new CassandraComponentFactory(keyGeneratorFactoryFactoryRegistry, valueGeneratorFactoryFactoryRegistry,
getConfig(objectReader, configNode));
}
@Nonnull
@Override | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull;
package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override
public ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException {
return new CassandraComponentFactory(keyGeneratorFactoryFactoryRegistry, valueGeneratorFactoryFactoryRegistry,
getConfig(objectReader, configNode));
}
@Nonnull
@Override | public ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, |
palominolabs/benchpress | examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull; | package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override
public ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException {
return new CassandraComponentFactory(keyGeneratorFactoryFactoryRegistry, valueGeneratorFactoryFactoryRegistry,
getConfig(objectReader, configNode));
}
@Nonnull
@Override
public ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader,
JsonNode configNode) throws IOException {
final CassandraConfig cassandraConfig = getConfig(objectReader, configNode);
return new ControllerComponentFactory() {
@Nonnull
@Override | // Path: examples/multi-db/key-gen/src/main/java/com/palominolabs/benchpress/example/multidb/key/KeyGeneratorFactoryFactoryRegistry.java
// public final class KeyGeneratorFactoryFactoryRegistry extends IdRegistry<KeyGeneratorFactoryFactory> {
//
// @Inject
// KeyGeneratorFactoryFactoryRegistry(Set<KeyGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: examples/multi-db/value-gen/src/main/java/com/palominolabs/benchpress/example/multidb/value/ValueGeneratorFactoryFactoryRegistry.java
// public final class ValueGeneratorFactoryFactoryRegistry extends IdRegistry<ValueGeneratorFactoryFactory> {
//
// @Inject
// ValueGeneratorFactoryFactoryRegistry(Set<ValueGeneratorFactoryFactory> instances) {
// super(instances);
// }
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ComponentFactory.java
// public interface ComponentFactory {
// /**
// * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.
// *
// * @return a configured task factory
// */
// @Nonnull
// TaskFactory getTaskFactory();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/ControllerComponentFactory.java
// public interface ControllerComponentFactory {
//
// @Nonnull
// JobSlicer getJobSlicer();
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobSlicer.java
// public interface JobSlicer {
//
// /**
// * Split this job into slices, one for each worker.
// *
// * @param jobId the job id being sliced
// * @param workers The number of slices to create
// * @param progressUrl The URL to send progress reports to
// * @param finishedUrl The URL to send finished report to
// * @param objectReader objectReader configured like objectWriter
// * @param objectWriter objectWriter to use to serialize slice task config
// * @return List of the slices
// * @throws IOException if slicing fails
// */
// @Nonnull
// List<Task> slice(UUID jobId, int workers, String progressUrl, String finishedUrl,
// ObjectReader objectReader, ObjectWriter objectWriter) throws IOException;
// }
//
// Path: job/src/main/java/com/palominolabs/benchpress/job/task/JobTypePlugin.java
// public interface JobTypePlugin extends Identifiable {
// /**
// * Get the components that are used by workers.
// *
// * Encapsulates the logic that reads implementation-specific config information from the task json. This way, a
// * ComponentFactory is fully ready to use and never needs to access its configuration json again.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the task as split up by the JobSlicer
// * @return a configured ComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException;
//
// /**
// * Get the components that are used by the controller.
// *
// * @param objectReader the ObjectReader to use to deserialize configNode
// * @param configNode the config node for the job
// * @return a configured ControllerComponentFactory
// * @throws IOException if config parsing fails
// */
// @Nonnull
// ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader, JsonNode configNode) throws
// IOException;
// }
// Path: examples/multi-db/cassandra/src/main/java/com/palominolabs/benchpress/example/multidb/cassandra/CassandraJobTypePlugin.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactoryFactoryRegistry;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.ControllerComponentFactory;
import com.palominolabs.benchpress.job.task.JobSlicer;
import com.palominolabs.benchpress.job.task.JobTypePlugin;
import java.io.IOException;
import javax.annotation.Nonnull;
package com.palominolabs.benchpress.example.multidb.cassandra;
final class CassandraJobTypePlugin implements JobTypePlugin {
static final String TASK_TYPE = "CASSANDRA";
private final KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry;
private final ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry;
@Inject
CassandraJobTypePlugin(KeyGeneratorFactoryFactoryRegistry keyGeneratorFactoryFactoryRegistry,
ValueGeneratorFactoryFactoryRegistry valueGeneratorFactoryFactoryRegistry) {
this.keyGeneratorFactoryFactoryRegistry = keyGeneratorFactoryFactoryRegistry;
this.valueGeneratorFactoryFactoryRegistry = valueGeneratorFactoryFactoryRegistry;
}
@Nonnull
@Override
public ComponentFactory getComponentFactory(ObjectReader objectReader, JsonNode configNode) throws IOException {
return new CassandraComponentFactory(keyGeneratorFactoryFactoryRegistry, valueGeneratorFactoryFactoryRegistry,
getConfig(objectReader, configNode));
}
@Nonnull
@Override
public ControllerComponentFactory getControllerComponentFactory(ObjectReader objectReader,
JsonNode configNode) throws IOException {
final CassandraConfig cassandraConfig = getConfig(objectReader, configNode);
return new ControllerComponentFactory() {
@Nonnull
@Override | public JobSlicer getJobSlicer() { |
Phonbopit/30-android-libraries-in-30-days | app/src/main/java-gen/com/devahoy/learn30androidlibraries/DaoSession.java | // Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/Player.java
// public class Player {
//
// private Long id;
// private String name;
// private String club;
//
// public Player() {
// }
//
// public Player(Long id) {
// this.id = id;
// }
//
// public Player(Long id, String name, String club) {
// this.id = id;
// this.name = name;
// this.club = club;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getClub() {
// return club;
// }
//
// public void setClub(String club) {
// this.club = club;
// }
//
// }
//
// Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/PlayerDao.java
// public class PlayerDao extends AbstractDao<Player, Long> {
//
// public static final String TABLENAME = "PLAYER";
//
// /**
// * Properties of entity Player.<br/>
// * Can be used for QueryBuilder and for referencing column names.
// */
// public static class Properties {
// public final static Property Id = new Property(0, Long.class, "id", true, "_id");
// public final static Property Name = new Property(1, String.class, "name", false, "NAME");
// public final static Property Club = new Property(2, String.class, "club", false, "CLUB");
// };
//
//
// public PlayerDao(DaoConfig config) {
// super(config);
// }
//
// public PlayerDao(DaoConfig config, DaoSession daoSession) {
// super(config, daoSession);
// }
//
// /** Creates the underlying database table. */
// public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
// String constraint = ifNotExists? "IF NOT EXISTS ": "";
// db.execSQL("CREATE TABLE " + constraint + "'PLAYER' (" + //
// "'_id' INTEGER PRIMARY KEY ," + // 0: id
// "'NAME' TEXT," + // 1: name
// "'CLUB' TEXT);"); // 2: club
// }
//
// /** Drops the underlying database table. */
// public static void dropTable(SQLiteDatabase db, boolean ifExists) {
// String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'PLAYER'";
// db.execSQL(sql);
// }
//
// /** @inheritdoc */
// @Override
// protected void bindValues(SQLiteStatement stmt, Player entity) {
// stmt.clearBindings();
//
// Long id = entity.getId();
// if (id != null) {
// stmt.bindLong(1, id);
// }
//
// String name = entity.getName();
// if (name != null) {
// stmt.bindString(2, name);
// }
//
// String club = entity.getClub();
// if (club != null) {
// stmt.bindString(3, club);
// }
// }
//
// /** @inheritdoc */
// @Override
// public Long readKey(Cursor cursor, int offset) {
// return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
// }
//
// /** @inheritdoc */
// @Override
// public Player readEntity(Cursor cursor, int offset) {
// Player entity = new Player( //
// cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
// cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
// cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // club
// );
// return entity;
// }
//
// /** @inheritdoc */
// @Override
// public void readEntity(Cursor cursor, Player entity, int offset) {
// entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
// entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
// entity.setClub(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
// }
//
// /** @inheritdoc */
// @Override
// protected Long updateKeyAfterInsert(Player entity, long rowId) {
// entity.setId(rowId);
// return rowId;
// }
//
// /** @inheritdoc */
// @Override
// public Long getKey(Player entity) {
// if(entity != null) {
// return entity.getId();
// } else {
// return null;
// }
// }
//
// /** @inheritdoc */
// @Override
// protected boolean isEntityUpdateable() {
// return true;
// }
//
// }
| import android.database.sqlite.SQLiteDatabase;
import java.util.Map;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;
import com.devahoy.learn30androidlibraries.Player;
import com.devahoy.learn30androidlibraries.PlayerDao;
| package com.devahoy.learn30androidlibraries;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see de.greenrobot.dao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig playerDaoConfig;
| // Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/Player.java
// public class Player {
//
// private Long id;
// private String name;
// private String club;
//
// public Player() {
// }
//
// public Player(Long id) {
// this.id = id;
// }
//
// public Player(Long id, String name, String club) {
// this.id = id;
// this.name = name;
// this.club = club;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getClub() {
// return club;
// }
//
// public void setClub(String club) {
// this.club = club;
// }
//
// }
//
// Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/PlayerDao.java
// public class PlayerDao extends AbstractDao<Player, Long> {
//
// public static final String TABLENAME = "PLAYER";
//
// /**
// * Properties of entity Player.<br/>
// * Can be used for QueryBuilder and for referencing column names.
// */
// public static class Properties {
// public final static Property Id = new Property(0, Long.class, "id", true, "_id");
// public final static Property Name = new Property(1, String.class, "name", false, "NAME");
// public final static Property Club = new Property(2, String.class, "club", false, "CLUB");
// };
//
//
// public PlayerDao(DaoConfig config) {
// super(config);
// }
//
// public PlayerDao(DaoConfig config, DaoSession daoSession) {
// super(config, daoSession);
// }
//
// /** Creates the underlying database table. */
// public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
// String constraint = ifNotExists? "IF NOT EXISTS ": "";
// db.execSQL("CREATE TABLE " + constraint + "'PLAYER' (" + //
// "'_id' INTEGER PRIMARY KEY ," + // 0: id
// "'NAME' TEXT," + // 1: name
// "'CLUB' TEXT);"); // 2: club
// }
//
// /** Drops the underlying database table. */
// public static void dropTable(SQLiteDatabase db, boolean ifExists) {
// String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'PLAYER'";
// db.execSQL(sql);
// }
//
// /** @inheritdoc */
// @Override
// protected void bindValues(SQLiteStatement stmt, Player entity) {
// stmt.clearBindings();
//
// Long id = entity.getId();
// if (id != null) {
// stmt.bindLong(1, id);
// }
//
// String name = entity.getName();
// if (name != null) {
// stmt.bindString(2, name);
// }
//
// String club = entity.getClub();
// if (club != null) {
// stmt.bindString(3, club);
// }
// }
//
// /** @inheritdoc */
// @Override
// public Long readKey(Cursor cursor, int offset) {
// return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
// }
//
// /** @inheritdoc */
// @Override
// public Player readEntity(Cursor cursor, int offset) {
// Player entity = new Player( //
// cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
// cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
// cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // club
// );
// return entity;
// }
//
// /** @inheritdoc */
// @Override
// public void readEntity(Cursor cursor, Player entity, int offset) {
// entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
// entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
// entity.setClub(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
// }
//
// /** @inheritdoc */
// @Override
// protected Long updateKeyAfterInsert(Player entity, long rowId) {
// entity.setId(rowId);
// return rowId;
// }
//
// /** @inheritdoc */
// @Override
// public Long getKey(Player entity) {
// if(entity != null) {
// return entity.getId();
// } else {
// return null;
// }
// }
//
// /** @inheritdoc */
// @Override
// protected boolean isEntityUpdateable() {
// return true;
// }
//
// }
// Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/DaoSession.java
import android.database.sqlite.SQLiteDatabase;
import java.util.Map;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;
import com.devahoy.learn30androidlibraries.Player;
import com.devahoy.learn30androidlibraries.PlayerDao;
package com.devahoy.learn30androidlibraries;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see de.greenrobot.dao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig playerDaoConfig;
| private final PlayerDao playerDao;
|
Phonbopit/30-android-libraries-in-30-days | app/src/main/java-gen/com/devahoy/learn30androidlibraries/DaoMaster.java | // Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/PlayerDao.java
// public class PlayerDao extends AbstractDao<Player, Long> {
//
// public static final String TABLENAME = "PLAYER";
//
// /**
// * Properties of entity Player.<br/>
// * Can be used for QueryBuilder and for referencing column names.
// */
// public static class Properties {
// public final static Property Id = new Property(0, Long.class, "id", true, "_id");
// public final static Property Name = new Property(1, String.class, "name", false, "NAME");
// public final static Property Club = new Property(2, String.class, "club", false, "CLUB");
// };
//
//
// public PlayerDao(DaoConfig config) {
// super(config);
// }
//
// public PlayerDao(DaoConfig config, DaoSession daoSession) {
// super(config, daoSession);
// }
//
// /** Creates the underlying database table. */
// public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
// String constraint = ifNotExists? "IF NOT EXISTS ": "";
// db.execSQL("CREATE TABLE " + constraint + "'PLAYER' (" + //
// "'_id' INTEGER PRIMARY KEY ," + // 0: id
// "'NAME' TEXT," + // 1: name
// "'CLUB' TEXT);"); // 2: club
// }
//
// /** Drops the underlying database table. */
// public static void dropTable(SQLiteDatabase db, boolean ifExists) {
// String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'PLAYER'";
// db.execSQL(sql);
// }
//
// /** @inheritdoc */
// @Override
// protected void bindValues(SQLiteStatement stmt, Player entity) {
// stmt.clearBindings();
//
// Long id = entity.getId();
// if (id != null) {
// stmt.bindLong(1, id);
// }
//
// String name = entity.getName();
// if (name != null) {
// stmt.bindString(2, name);
// }
//
// String club = entity.getClub();
// if (club != null) {
// stmt.bindString(3, club);
// }
// }
//
// /** @inheritdoc */
// @Override
// public Long readKey(Cursor cursor, int offset) {
// return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
// }
//
// /** @inheritdoc */
// @Override
// public Player readEntity(Cursor cursor, int offset) {
// Player entity = new Player( //
// cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
// cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
// cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // club
// );
// return entity;
// }
//
// /** @inheritdoc */
// @Override
// public void readEntity(Cursor cursor, Player entity, int offset) {
// entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
// entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
// entity.setClub(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
// }
//
// /** @inheritdoc */
// @Override
// protected Long updateKeyAfterInsert(Player entity, long rowId) {
// entity.setId(rowId);
// return rowId;
// }
//
// /** @inheritdoc */
// @Override
// public Long getKey(Player entity) {
// if(entity != null) {
// return entity.getId();
// } else {
// return null;
// }
// }
//
// /** @inheritdoc */
// @Override
// protected boolean isEntityUpdateable() {
// return true;
// }
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import de.greenrobot.dao.AbstractDaoMaster;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import com.devahoy.learn30androidlibraries.PlayerDao;
| package com.devahoy.learn30androidlibraries;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
| // Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/PlayerDao.java
// public class PlayerDao extends AbstractDao<Player, Long> {
//
// public static final String TABLENAME = "PLAYER";
//
// /**
// * Properties of entity Player.<br/>
// * Can be used for QueryBuilder and for referencing column names.
// */
// public static class Properties {
// public final static Property Id = new Property(0, Long.class, "id", true, "_id");
// public final static Property Name = new Property(1, String.class, "name", false, "NAME");
// public final static Property Club = new Property(2, String.class, "club", false, "CLUB");
// };
//
//
// public PlayerDao(DaoConfig config) {
// super(config);
// }
//
// public PlayerDao(DaoConfig config, DaoSession daoSession) {
// super(config, daoSession);
// }
//
// /** Creates the underlying database table. */
// public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
// String constraint = ifNotExists? "IF NOT EXISTS ": "";
// db.execSQL("CREATE TABLE " + constraint + "'PLAYER' (" + //
// "'_id' INTEGER PRIMARY KEY ," + // 0: id
// "'NAME' TEXT," + // 1: name
// "'CLUB' TEXT);"); // 2: club
// }
//
// /** Drops the underlying database table. */
// public static void dropTable(SQLiteDatabase db, boolean ifExists) {
// String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'PLAYER'";
// db.execSQL(sql);
// }
//
// /** @inheritdoc */
// @Override
// protected void bindValues(SQLiteStatement stmt, Player entity) {
// stmt.clearBindings();
//
// Long id = entity.getId();
// if (id != null) {
// stmt.bindLong(1, id);
// }
//
// String name = entity.getName();
// if (name != null) {
// stmt.bindString(2, name);
// }
//
// String club = entity.getClub();
// if (club != null) {
// stmt.bindString(3, club);
// }
// }
//
// /** @inheritdoc */
// @Override
// public Long readKey(Cursor cursor, int offset) {
// return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
// }
//
// /** @inheritdoc */
// @Override
// public Player readEntity(Cursor cursor, int offset) {
// Player entity = new Player( //
// cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
// cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
// cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // club
// );
// return entity;
// }
//
// /** @inheritdoc */
// @Override
// public void readEntity(Cursor cursor, Player entity, int offset) {
// entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
// entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
// entity.setClub(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
// }
//
// /** @inheritdoc */
// @Override
// protected Long updateKeyAfterInsert(Player entity, long rowId) {
// entity.setId(rowId);
// return rowId;
// }
//
// /** @inheritdoc */
// @Override
// public Long getKey(Player entity) {
// if(entity != null) {
// return entity.getId();
// } else {
// return null;
// }
// }
//
// /** @inheritdoc */
// @Override
// protected boolean isEntityUpdateable() {
// return true;
// }
//
// }
// Path: app/src/main/java-gen/com/devahoy/learn30androidlibraries/DaoMaster.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import de.greenrobot.dao.AbstractDaoMaster;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import com.devahoy.learn30androidlibraries.PlayerDao;
package com.devahoy.learn30androidlibraries;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
| PlayerDao.createTable(db, ifNotExists);
|
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/util/MediaScannerUtils.java | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import org.openintents.filemanager.files.FileHolder;
import java.io.File;
import java.util.List; | package org.openintents.filemanager.util;
public abstract class MediaScannerUtils {
/**
* Request a MediaScanner scan for a single file.
*/
public static void informFileAdded(Context c, File f) {
if (f == null)
return;
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(f));
c.sendBroadcast(intent);
}
/**
* Request a MediaScanner scan for multiple files.
*/
public static void informFilesAdded(Context c, File[] files) {
// NOTE: it seemed like overkill having to create a Helper class to
// avoid VerifyError on 1.6 so that we can use MediaScannerConnection.scanFile()
// Therefore we just iterate through files and use the compatible-with-every-version broadcast.
for (int i = 0; i < files.length; i++)
informFileAdded(c, files[i]);
}
/**
* Request a MediaScanner scan for multiple files.
*/ | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/util/MediaScannerUtils.java
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import org.openintents.filemanager.files.FileHolder;
import java.io.File;
import java.util.List;
package org.openintents.filemanager.util;
public abstract class MediaScannerUtils {
/**
* Request a MediaScanner scan for a single file.
*/
public static void informFileAdded(Context c, File f) {
if (f == null)
return;
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(f));
c.sendBroadcast(intent);
}
/**
* Request a MediaScanner scan for multiple files.
*/
public static void informFilesAdded(Context c, File[] files) {
// NOTE: it seemed like overkill having to create a Helper class to
// avoid VerifyError on 1.6 so that we can use MediaScannerConnection.scanFile()
// Therefore we just iterate through files and use the compatible-with-every-version broadcast.
for (int i = 0; i < files.length; i++)
informFileAdded(c, files[i]);
}
/**
* Request a MediaScanner scan for multiple files.
*/ | public static void informFilesAdded(Context c, List<FileHolder> files) { |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListFragment.java | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkListActionHandler.java
// public class BookmarkListActionHandler {
// private BookmarkListActionHandler() {
// }
//
// /**
// * Offers a centralized bookmark action execution component.
// *
// * @param item The MenuItem selected.
// * @param list The list to act upon.
// */
// public static void handleItemSelection(MenuItem item, ListView list) {
//
// // Single selection
// if (ListViewMethodHelper.listView_getCheckedItemCount(list) == 1) {
//
// // Get id of selected bookmark.
// long id = -1;
// if (item.getMenuInfo() instanceof AdapterContextMenuInfo)
// id = list.getAdapter().getItemId(((AdapterContextMenuInfo) item.getMenuInfo()).position);
// id = ListViewMethodHelper.listView_getCheckedItemIds(list)[0];
//
// // Handle selection
// switch (item.getItemId()) {
// case R.id.menu_delete:
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(id)});
// break;
// }
// // Multiple selection
// } else {
// switch (item.getItemId()) {
// case R.id.menu_delete:
// long[] ids = ListViewMethodHelper.listView_getCheckedItemIds(list);
// for (int i = 0; i < ids.length; i++) {
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(ids[i])});
// }
// break;
// }
// }
//
// ((BookmarkListAdapter) list.getAdapter()).notifyDataSetChanged();
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkMultiChoiceModeHelper.java
// public class BookmarkMultiChoiceModeHelper {
//
// private BookmarkMultiChoiceModeHelper() {
// }
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void listView_setMultiChoiceModeListener(final ListView list, final Context context) {
// list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
//
// @Override
// public boolean onPrepareActionMode(android.view.ActionMode mode,
// Menu menu) {
// return false;
// }
//
// @Override
// public void onDestroyActionMode(android.view.ActionMode mode) {
// }
//
// @Override
// public boolean onCreateActionMode(android.view.ActionMode mode,
// Menu menu) {
// mode.getMenuInflater().inflate(R.menu.bookmarks, menu);
// return true;
// }
//
// @Override
// public boolean onActionItemClicked(android.view.ActionMode mode,
// MenuItem item) {
// BookmarkListActionHandler.handleItemSelection(item, list);
// mode.finish();
// return true;
// }
//
// @Override
// public void onItemCheckedStateChanged(android.view.ActionMode mode,
// int position, long id, boolean checked) {
// mode.setTitle(list.getCheckedItemCount() + " " + context.getResources().getString(R.string.selected));
// }
// });
// }
// }
| import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.ListFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.compatibility.BookmarkListActionHandler;
import org.openintents.filemanager.compatibility.BookmarkMultiChoiceModeHelper; | package org.openintents.filemanager.bookmarks;
/**
* @author George Venios
*/
public class BookmarkListFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new BookmarkListAdapter((FragmentActivity) getActivity()));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set list properties
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
((BookmarkListAdapter) getListAdapter()).setScrolling(false);
} else
((BookmarkListAdapter) getListAdapter()).setScrolling(true);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
getListView().requestFocus();
getListView().requestFocusFromTouch();
setEmptyText(getString(R.string.bookmark_empty));
// Handle item selection.
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkListActionHandler.java
// public class BookmarkListActionHandler {
// private BookmarkListActionHandler() {
// }
//
// /**
// * Offers a centralized bookmark action execution component.
// *
// * @param item The MenuItem selected.
// * @param list The list to act upon.
// */
// public static void handleItemSelection(MenuItem item, ListView list) {
//
// // Single selection
// if (ListViewMethodHelper.listView_getCheckedItemCount(list) == 1) {
//
// // Get id of selected bookmark.
// long id = -1;
// if (item.getMenuInfo() instanceof AdapterContextMenuInfo)
// id = list.getAdapter().getItemId(((AdapterContextMenuInfo) item.getMenuInfo()).position);
// id = ListViewMethodHelper.listView_getCheckedItemIds(list)[0];
//
// // Handle selection
// switch (item.getItemId()) {
// case R.id.menu_delete:
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(id)});
// break;
// }
// // Multiple selection
// } else {
// switch (item.getItemId()) {
// case R.id.menu_delete:
// long[] ids = ListViewMethodHelper.listView_getCheckedItemIds(list);
// for (int i = 0; i < ids.length; i++) {
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(ids[i])});
// }
// break;
// }
// }
//
// ((BookmarkListAdapter) list.getAdapter()).notifyDataSetChanged();
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkMultiChoiceModeHelper.java
// public class BookmarkMultiChoiceModeHelper {
//
// private BookmarkMultiChoiceModeHelper() {
// }
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void listView_setMultiChoiceModeListener(final ListView list, final Context context) {
// list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
//
// @Override
// public boolean onPrepareActionMode(android.view.ActionMode mode,
// Menu menu) {
// return false;
// }
//
// @Override
// public void onDestroyActionMode(android.view.ActionMode mode) {
// }
//
// @Override
// public boolean onCreateActionMode(android.view.ActionMode mode,
// Menu menu) {
// mode.getMenuInflater().inflate(R.menu.bookmarks, menu);
// return true;
// }
//
// @Override
// public boolean onActionItemClicked(android.view.ActionMode mode,
// MenuItem item) {
// BookmarkListActionHandler.handleItemSelection(item, list);
// mode.finish();
// return true;
// }
//
// @Override
// public void onItemCheckedStateChanged(android.view.ActionMode mode,
// int position, long id, boolean checked) {
// mode.setTitle(list.getCheckedItemCount() + " " + context.getResources().getString(R.string.selected));
// }
// });
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListFragment.java
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.ListFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.compatibility.BookmarkListActionHandler;
import org.openintents.filemanager.compatibility.BookmarkMultiChoiceModeHelper;
package org.openintents.filemanager.bookmarks;
/**
* @author George Venios
*/
public class BookmarkListFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new BookmarkListAdapter((FragmentActivity) getActivity()));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set list properties
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
((BookmarkListAdapter) getListAdapter()).setScrolling(false);
} else
((BookmarkListAdapter) getListAdapter()).setScrolling(true);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
getListView().requestFocus();
getListView().requestFocusFromTouch();
setEmptyText(getString(R.string.bookmark_empty));
// Handle item selection.
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); | BookmarkMultiChoiceModeHelper.listView_setMultiChoiceModeListener(getListView(), getActivity()); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListFragment.java | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkListActionHandler.java
// public class BookmarkListActionHandler {
// private BookmarkListActionHandler() {
// }
//
// /**
// * Offers a centralized bookmark action execution component.
// *
// * @param item The MenuItem selected.
// * @param list The list to act upon.
// */
// public static void handleItemSelection(MenuItem item, ListView list) {
//
// // Single selection
// if (ListViewMethodHelper.listView_getCheckedItemCount(list) == 1) {
//
// // Get id of selected bookmark.
// long id = -1;
// if (item.getMenuInfo() instanceof AdapterContextMenuInfo)
// id = list.getAdapter().getItemId(((AdapterContextMenuInfo) item.getMenuInfo()).position);
// id = ListViewMethodHelper.listView_getCheckedItemIds(list)[0];
//
// // Handle selection
// switch (item.getItemId()) {
// case R.id.menu_delete:
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(id)});
// break;
// }
// // Multiple selection
// } else {
// switch (item.getItemId()) {
// case R.id.menu_delete:
// long[] ids = ListViewMethodHelper.listView_getCheckedItemIds(list);
// for (int i = 0; i < ids.length; i++) {
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(ids[i])});
// }
// break;
// }
// }
//
// ((BookmarkListAdapter) list.getAdapter()).notifyDataSetChanged();
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkMultiChoiceModeHelper.java
// public class BookmarkMultiChoiceModeHelper {
//
// private BookmarkMultiChoiceModeHelper() {
// }
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void listView_setMultiChoiceModeListener(final ListView list, final Context context) {
// list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
//
// @Override
// public boolean onPrepareActionMode(android.view.ActionMode mode,
// Menu menu) {
// return false;
// }
//
// @Override
// public void onDestroyActionMode(android.view.ActionMode mode) {
// }
//
// @Override
// public boolean onCreateActionMode(android.view.ActionMode mode,
// Menu menu) {
// mode.getMenuInflater().inflate(R.menu.bookmarks, menu);
// return true;
// }
//
// @Override
// public boolean onActionItemClicked(android.view.ActionMode mode,
// MenuItem item) {
// BookmarkListActionHandler.handleItemSelection(item, list);
// mode.finish();
// return true;
// }
//
// @Override
// public void onItemCheckedStateChanged(android.view.ActionMode mode,
// int position, long id, boolean checked) {
// mode.setTitle(list.getCheckedItemCount() + " " + context.getResources().getString(R.string.selected));
// }
// });
// }
// }
| import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.ListFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.compatibility.BookmarkListActionHandler;
import org.openintents.filemanager.compatibility.BookmarkMultiChoiceModeHelper; | public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set list properties
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
((BookmarkListAdapter) getListAdapter()).setScrolling(false);
} else
((BookmarkListAdapter) getListAdapter()).setScrolling(true);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
getListView().requestFocus();
getListView().requestFocusFromTouch();
setEmptyText(getString(R.string.bookmark_empty));
// Handle item selection.
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
BookmarkMultiChoiceModeHelper.listView_setMultiChoiceModeListener(getListView(), getActivity());
}
@Override
public boolean onContextItemSelected(MenuItem item) { | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkListActionHandler.java
// public class BookmarkListActionHandler {
// private BookmarkListActionHandler() {
// }
//
// /**
// * Offers a centralized bookmark action execution component.
// *
// * @param item The MenuItem selected.
// * @param list The list to act upon.
// */
// public static void handleItemSelection(MenuItem item, ListView list) {
//
// // Single selection
// if (ListViewMethodHelper.listView_getCheckedItemCount(list) == 1) {
//
// // Get id of selected bookmark.
// long id = -1;
// if (item.getMenuInfo() instanceof AdapterContextMenuInfo)
// id = list.getAdapter().getItemId(((AdapterContextMenuInfo) item.getMenuInfo()).position);
// id = ListViewMethodHelper.listView_getCheckedItemIds(list)[0];
//
// // Handle selection
// switch (item.getItemId()) {
// case R.id.menu_delete:
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(id)});
// break;
// }
// // Multiple selection
// } else {
// switch (item.getItemId()) {
// case R.id.menu_delete:
// long[] ids = ListViewMethodHelper.listView_getCheckedItemIds(list);
// for (int i = 0; i < ids.length; i++) {
// list.getContext().getContentResolver().delete(BookmarksProvider.CONTENT_URI, BookmarksProvider._ID + "=?", new String[]{Long.toString(ids[i])});
// }
// break;
// }
// }
//
// ((BookmarkListAdapter) list.getAdapter()).notifyDataSetChanged();
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/BookmarkMultiChoiceModeHelper.java
// public class BookmarkMultiChoiceModeHelper {
//
// private BookmarkMultiChoiceModeHelper() {
// }
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void listView_setMultiChoiceModeListener(final ListView list, final Context context) {
// list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
//
// @Override
// public boolean onPrepareActionMode(android.view.ActionMode mode,
// Menu menu) {
// return false;
// }
//
// @Override
// public void onDestroyActionMode(android.view.ActionMode mode) {
// }
//
// @Override
// public boolean onCreateActionMode(android.view.ActionMode mode,
// Menu menu) {
// mode.getMenuInflater().inflate(R.menu.bookmarks, menu);
// return true;
// }
//
// @Override
// public boolean onActionItemClicked(android.view.ActionMode mode,
// MenuItem item) {
// BookmarkListActionHandler.handleItemSelection(item, list);
// mode.finish();
// return true;
// }
//
// @Override
// public void onItemCheckedStateChanged(android.view.ActionMode mode,
// int position, long id, boolean checked) {
// mode.setTitle(list.getCheckedItemCount() + " " + context.getResources().getString(R.string.selected));
// }
// });
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListFragment.java
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.ListFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.compatibility.BookmarkListActionHandler;
import org.openintents.filemanager.compatibility.BookmarkMultiChoiceModeHelper;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set list properties
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
((BookmarkListAdapter) getListAdapter()).setScrolling(false);
} else
((BookmarkListAdapter) getListAdapter()).setScrolling(true);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
getListView().requestFocus();
getListView().requestFocusFromTouch();
setEmptyText(getString(R.string.bookmark_empty));
// Handle item selection.
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
BookmarkMultiChoiceModeHelper.listView_setMultiChoiceModeListener(getListView(), getActivity());
}
@Override
public boolean onContextItemSelected(MenuItem item) { | BookmarkListActionHandler.handleItemSelection(item, getListView()); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/FileHolderListAdapter.java | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/view/ViewHolder.java
// public class ViewHolder {
// public ImageView icon;
// public TextView primaryInfo;
// public TextView secondaryInfo;
// public TextView tertiaryInfo;
// }
| import android.content.Context;
import androidx.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.openintents.filemanager.files.FileHolder;
import org.openintents.filemanager.view.ViewHolder;
import java.util.List; | }
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* Creates a new list item view, along with it's ViewHolder set as a tag.
*
* @return The new view.
*/
protected View newView() {
View view = mInflater.inflate(mItemLayoutId, null);
| // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/view/ViewHolder.java
// public class ViewHolder {
// public ImageView icon;
// public TextView primaryInfo;
// public TextView secondaryInfo;
// public TextView tertiaryInfo;
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/FileHolderListAdapter.java
import android.content.Context;
import androidx.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.openintents.filemanager.files.FileHolder;
import org.openintents.filemanager.view.ViewHolder;
import java.util.List;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* Creates a new list item view, along with it's ViewHolder set as a tag.
*
* @return The new view.
*/
protected View newView() {
View view = mInflater.inflate(mItemLayoutId, null);
| ViewHolder holder = new ViewHolder(); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/util/CopyHelper.java | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
| import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | package org.openintents.filemanager.util;
/**
* This class helps simplify copying and moving of files and folders by providing a simple interface to the operations and handling the actual operation transparently.
*
* @author George Venios
*/
public class CopyHelper {
private static final int COPY_BUFFER_SIZE = 32 * 1024;
private Context mContext; | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/util/CopyHelper.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
package org.openintents.filemanager.util;
/**
* This class helps simplify copying and moving of files and folders by providing a simple interface to the operations and handling the actual operation transparently.
*
* @author George Venios
*/
public class CopyHelper {
private static final int COPY_BUFFER_SIZE = 32 * 1024;
private Context mContext; | private List<FileHolder> mClipboard; |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListActivity.java | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/HomeIconHelper.java
// public class HomeIconHelper {
// private HomeIconHelper() {
// }
//
// public static void activity_actionbar_setHomeButtonEnabled(Activity act) {
// act.getActionBar().setHomeButtonEnabled(true);
// }
//
// public static void activity_actionbar_setDisplayHomeAsUpEnabled(Activity act) {
// if (act != null && act.getActionBar() != null) {
// act.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Launch the home activity.
// *
// * @param act The currently displayed activity.
// */
// public static void showHome(Activity act) {
// Intent intent = new Intent(act, FileManagerActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// act.startActivity(intent);
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
| import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import org.openintents.filemanager.compatibility.HomeIconHelper;
import org.openintents.filemanager.util.UIUtils; | package org.openintents.filemanager.bookmarks;
public class BookmarkListActivity extends FragmentActivity {
public static final String KEY_RESULT_PATH = "path";
private static final String FRAGMENT_TAG = "Fragment";
@Override
protected void onCreate(Bundle savedInstanceState) { | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/HomeIconHelper.java
// public class HomeIconHelper {
// private HomeIconHelper() {
// }
//
// public static void activity_actionbar_setHomeButtonEnabled(Activity act) {
// act.getActionBar().setHomeButtonEnabled(true);
// }
//
// public static void activity_actionbar_setDisplayHomeAsUpEnabled(Activity act) {
// if (act != null && act.getActionBar() != null) {
// act.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Launch the home activity.
// *
// * @param act The currently displayed activity.
// */
// public static void showHome(Activity act) {
// Intent intent = new Intent(act, FileManagerActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// act.startActivity(intent);
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListActivity.java
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import org.openintents.filemanager.compatibility.HomeIconHelper;
import org.openintents.filemanager.util.UIUtils;
package org.openintents.filemanager.bookmarks;
public class BookmarkListActivity extends FragmentActivity {
public static final String KEY_RESULT_PATH = "path";
private static final String FRAGMENT_TAG = "Fragment";
@Override
protected void onCreate(Bundle savedInstanceState) { | UIUtils.setThemeFor(this); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListActivity.java | // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/HomeIconHelper.java
// public class HomeIconHelper {
// private HomeIconHelper() {
// }
//
// public static void activity_actionbar_setHomeButtonEnabled(Activity act) {
// act.getActionBar().setHomeButtonEnabled(true);
// }
//
// public static void activity_actionbar_setDisplayHomeAsUpEnabled(Activity act) {
// if (act != null && act.getActionBar() != null) {
// act.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Launch the home activity.
// *
// * @param act The currently displayed activity.
// */
// public static void showHome(Activity act) {
// Intent intent = new Intent(act, FileManagerActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// act.startActivity(intent);
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
| import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import org.openintents.filemanager.compatibility.HomeIconHelper;
import org.openintents.filemanager.util.UIUtils; | package org.openintents.filemanager.bookmarks;
public class BookmarkListActivity extends FragmentActivity {
public static final String KEY_RESULT_PATH = "path";
private static final String FRAGMENT_TAG = "Fragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
UIUtils.setThemeFor(this);
super.onCreate(savedInstanceState);
| // Path: FileManager/src/main/java/org/openintents/filemanager/compatibility/HomeIconHelper.java
// public class HomeIconHelper {
// private HomeIconHelper() {
// }
//
// public static void activity_actionbar_setHomeButtonEnabled(Activity act) {
// act.getActionBar().setHomeButtonEnabled(true);
// }
//
// public static void activity_actionbar_setDisplayHomeAsUpEnabled(Activity act) {
// if (act != null && act.getActionBar() != null) {
// act.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Launch the home activity.
// *
// * @param act The currently displayed activity.
// */
// public static void showHome(Activity act) {
// Intent intent = new Intent(act, FileManagerActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// act.startActivity(intent);
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/bookmarks/BookmarkListActivity.java
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.MenuItem;
import org.openintents.filemanager.compatibility.HomeIconHelper;
import org.openintents.filemanager.util.UIUtils;
package org.openintents.filemanager.bookmarks;
public class BookmarkListActivity extends FragmentActivity {
public static final String KEY_RESULT_PATH = "path";
private static final String FRAGMENT_TAG = "Fragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
UIUtils.setThemeFor(this);
super.onCreate(savedInstanceState);
| HomeIconHelper.activity_actionbar_setDisplayHomeAsUpEnabled(this); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/FileManagerProvider.java | // Path: FileManager/src/main/java/org/openintents/filemanager/util/MimeTypes.java
// public class MimeTypes {
//
// private static MimeTypes mimeTypes;
//
// private Map<String, String> mExtensionsToTypes = new HashMap<>();
// private Map<String, Integer> mTypesToIcons = new HashMap<>();
//
// public static MimeTypes getInstance() {
// if (mimeTypes == null) {
// throw new IllegalStateException("MimeTypes must be initialized with newInstance");
// }
// return mimeTypes;
// }
//
// /**
// * Use this instead of the default constructor to get a prefilled object.
// */
// public static void initInstance(Context c) {
// MimeTypeParser mtp = null;
// try {
// mtp = new MimeTypeParser(c, c.getPackageName());
// } catch (NameNotFoundException e) {
// // Should never happen
// }
//
// XmlResourceParser in = c.getResources().getXml(R.xml.mimetypes);
//
// try {
// mimeTypes = mtp.fromXmlResource(in);
// } catch (XmlPullParserException | IOException e) {
// e.printStackTrace();
// }
// }
//
// public void put(String extension, String type, int icon) {
// put(extension, type);
// mTypesToIcons.put(type, icon);
// }
//
// public void put(String extension, String type) {
// // Convert extensions to lower case letters for easier comparison
// extension = extension.toLowerCase(Locale.ROOT);
// mExtensionsToTypes.put(extension, type);
// }
//
// public String getMimeType(String filename) {
// String extension = FileUtils.getExtension(filename);
//
// // Let's check the official map first. Webkit has a nice extension-to-MIME map.
// // Be sure to remove the first character from the extension, which is the "." character.
// if (extension.length() > 0) {
// String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
//
// if (webkitMimeType != null) {
// // Found one. Let's take it!
// return webkitMimeType;
// }
// }
//
// // Convert extensions to lower case letters for easier comparison
// extension = extension.toLowerCase();
//
// String mimetype = mExtensionsToTypes.get(extension);
//
// if (mimetype == null) {
// mimetype = "*/*";
// }
//
// return mimetype;
// }
//
// public int getIcon(String mimetype) {
// Integer iconResId = mTypesToIcons.get(mimetype);
// if (iconResId == null)
// return 0; // Invalid identifier
// return iconResId;
// }
// }
| import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import org.openintents.filemanager.util.MimeTypes;
import java.io.File;
import java.io.FileNotFoundException;
| package org.openintents.filemanager;
public class FileManagerProvider extends ContentProvider {
public static final String FILE_PROVIDER_PREFIX = "content://org.openintents.filemanager";
public static final String AUTHORITY = "org.openintents.filemanager";
| // Path: FileManager/src/main/java/org/openintents/filemanager/util/MimeTypes.java
// public class MimeTypes {
//
// private static MimeTypes mimeTypes;
//
// private Map<String, String> mExtensionsToTypes = new HashMap<>();
// private Map<String, Integer> mTypesToIcons = new HashMap<>();
//
// public static MimeTypes getInstance() {
// if (mimeTypes == null) {
// throw new IllegalStateException("MimeTypes must be initialized with newInstance");
// }
// return mimeTypes;
// }
//
// /**
// * Use this instead of the default constructor to get a prefilled object.
// */
// public static void initInstance(Context c) {
// MimeTypeParser mtp = null;
// try {
// mtp = new MimeTypeParser(c, c.getPackageName());
// } catch (NameNotFoundException e) {
// // Should never happen
// }
//
// XmlResourceParser in = c.getResources().getXml(R.xml.mimetypes);
//
// try {
// mimeTypes = mtp.fromXmlResource(in);
// } catch (XmlPullParserException | IOException e) {
// e.printStackTrace();
// }
// }
//
// public void put(String extension, String type, int icon) {
// put(extension, type);
// mTypesToIcons.put(type, icon);
// }
//
// public void put(String extension, String type) {
// // Convert extensions to lower case letters for easier comparison
// extension = extension.toLowerCase(Locale.ROOT);
// mExtensionsToTypes.put(extension, type);
// }
//
// public String getMimeType(String filename) {
// String extension = FileUtils.getExtension(filename);
//
// // Let's check the official map first. Webkit has a nice extension-to-MIME map.
// // Be sure to remove the first character from the extension, which is the "." character.
// if (extension.length() > 0) {
// String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
//
// if (webkitMimeType != null) {
// // Found one. Let's take it!
// return webkitMimeType;
// }
// }
//
// // Convert extensions to lower case letters for easier comparison
// extension = extension.toLowerCase();
//
// String mimetype = mExtensionsToTypes.get(extension);
//
// if (mimetype == null) {
// mimetype = "*/*";
// }
//
// return mimetype;
// }
//
// public int getIcon(String mimetype) {
// Integer iconResId = mTypesToIcons.get(mimetype);
// if (iconResId == null)
// return 0; // Invalid identifier
// return iconResId;
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/FileManagerProvider.java
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import org.openintents.filemanager.util.MimeTypes;
import java.io.File;
import java.io.FileNotFoundException;
package org.openintents.filemanager;
public class FileManagerProvider extends ContentProvider {
public static final String FILE_PROVIDER_PREFIX = "content://org.openintents.filemanager";
public static final String AUTHORITY = "org.openintents.filemanager";
| private MimeTypes mMimeTypes;
|
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/search/SearchListAdapter.java | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/view/ViewHolder.java
// public class ViewHolder {
// public ImageView icon;
// public TextView primaryInfo;
// public TextView secondaryInfo;
// public TextView tertiaryInfo;
// }
| import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import org.openintents.filemanager.view.ViewHolder;
import java.io.File;
import java.util.HashMap; | package org.openintents.filemanager.search;
/**
* Simple adapter for displaying search results.
*
* @author George Venios
*/
public class SearchListAdapter extends CursorAdapter {
private HashMap<String, FileHolder> itemCache = new HashMap<>();
public SearchListAdapter(Context context, Cursor c) {
super(context, c, true);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
String path = cursor.getString(cursor.getColumnIndex(SearchResultsProvider.COLUMN_PATH));
FileHolder fHolder;
if ((fHolder = itemCache.get(path)) == null) {
fHolder = new FileHolder(new File(path));
itemCache.put(path, fHolder);
}
| // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
//
// Path: FileManager/src/main/java/org/openintents/filemanager/view/ViewHolder.java
// public class ViewHolder {
// public ImageView icon;
// public TextView primaryInfo;
// public TextView secondaryInfo;
// public TextView tertiaryInfo;
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/search/SearchListAdapter.java
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import org.openintents.filemanager.view.ViewHolder;
import java.io.File;
import java.util.HashMap;
package org.openintents.filemanager.search;
/**
* Simple adapter for displaying search results.
*
* @author George Venios
*/
public class SearchListAdapter extends CursorAdapter {
private HashMap<String, FileHolder> itemCache = new HashMap<>();
public SearchListAdapter(Context context, Cursor c) {
super(context, c, true);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
String path = cursor.getString(cursor.getColumnIndex(SearchResultsProvider.COLUMN_PATH));
FileHolder fHolder;
if ((fHolder = itemCache.get(path)) == null) {
fHolder = new FileHolder(new File(path));
itemCache.put(path, fHolder);
}
| ViewHolder h = (ViewHolder) view.getTag(); |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/util/CompressManager.java | // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
| import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
| package org.openintents.filemanager.util;
public class CompressManager {
/**
* TAG for log messages.
*/
private static final String TAG = "CompressManager";
private static final int BUFFER_SIZE = 1024;
private Context mContext;
private ProgressDialog progressDialog;
private int fileCount;
private String fileOut;
private OnCompressFinishedListener onCompressFinishedListener = null;
public CompressManager(Context context) {
mContext = context;
}
| // Path: FileManager/src/main/java/org/openintents/filemanager/files/FileHolder.java
// public class FileHolder implements Parcelable, Comparable<FileHolder> {
// public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {
// public FileHolder createFromParcel(Parcel in) {
// return new FileHolder(in);
// }
//
// public FileHolder[] newArray(int size) {
// return new FileHolder[size];
// }
// };
// private File mFile;
// private Drawable mIcon;
// private String mMimeType = "";
// private String mExtension;
// private Boolean mIsDirectory;
//
// public FileHolder(File f) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// }
//
// public FileHolder(File f, boolean isDirectory) {
// mFile = f;
// mExtension = parseExtension();
// mMimeType = MimeTypes.getInstance().getMimeType(f.getName());
// mIsDirectory = isDirectory;
// }
//
// /**
// * Fastest constructor as it takes everything ready.
// */
// public FileHolder(File f, String m, Drawable i, boolean isDirectory) {
// mFile = f;
// mIcon = i;
// mExtension = parseExtension();
// mMimeType = m;
// mIsDirectory = isDirectory;
// }
//
// public FileHolder(Parcel in) {
// mFile = new File(in.readString());
// mMimeType = in.readString();
// mExtension = in.readString();
// byte directoryFlag = in.readByte();
// if (directoryFlag == -1) {
// mIsDirectory = null;
// } else {
// mIsDirectory = (directoryFlag == 1);
// }
// }
//
// public File getFile() {
// return mFile;
// }
//
// /**
// * Gets the icon representation of this file. In case of loss through parcel-unparcel.
// *
// * @return The icon.
// */
// public Drawable getIcon() {
// return mIcon;
// }
//
// public void setIcon(Drawable icon) {
// mIcon = icon;
// }
//
// /**
// * Shorthand for getFile().getName().
// *
// * @return This file's name.
// */
// public String getName() {
// return mFile.getName();
// }
//
// /**
// * Get the contained file's extension.
// */
// public String getExtension() {
// return mExtension;
// }
//
// /**
// * @return The held item's mime type.
// */
// public String getMimeType() {
// return mMimeType;
// }
//
// public String getFormattedModificationDate(Context c) {
// DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);
// DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);
// Date date = new Date(mFile.lastModified());
// return dateFormat.format(date) + " " + timeFormat.format(date);
// }
//
// /**
// * @param recursive Whether to return size of the whole tree below this file (Directories only).
// */
// public String getFormattedSize(Context c, boolean recursive) {
// return Formatter.formatFileSize(c, getSizeInBytes(recursive));
// }
//
// private long getSizeInBytes(boolean recursive) {
// if (recursive && mFile.isDirectory())
// return FileUtils.folderSize(mFile);
// else
// return mFile.length();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mFile.getAbsolutePath());
// dest.writeString(mMimeType);
// dest.writeString(mExtension);
// dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));
// }
//
// @Override
// public int compareTo(FileHolder another) {
// return mFile.compareTo(another.getFile());
// }
//
// /**
// * Parse the extension from the filename of the mFile member.
// */
// private String parseExtension() {
// return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);
// }
//
// @Override
// public String toString() {
// return super.toString() + "-" + getName();
// }
//
// public Boolean isDirectory() {
// return mIsDirectory;
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/util/CompressManager.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.openintents.filemanager.R;
import org.openintents.filemanager.files.FileHolder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
package org.openintents.filemanager.util;
public class CompressManager {
/**
* TAG for log messages.
*/
private static final String TAG = "CompressManager";
private static final int BUFFER_SIZE = 1024;
private Context mContext;
private ProgressDialog progressDialog;
private int fileCount;
private String fileOut;
private OnCompressFinishedListener onCompressFinishedListener = null;
public CompressManager(Context context) {
mContext = context;
}
| public void compress(FileHolder f, String out) {
|
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/dialogs/OverwriteFileDialog.java | // Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import org.openintents.filemanager.R;
import org.openintents.filemanager.util.UIUtils; | package org.openintents.filemanager.dialogs;
public class OverwriteFileDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity()) | // Path: FileManager/src/main/java/org/openintents/filemanager/util/UIUtils.java
// public abstract class UIUtils {
//
// public static void setThemeFor(Activity act) {
// if (getDefaultSharedPreferences(act).getBoolean("usedarktheme", true)) {
// act.setTheme(R.style.Theme_Dark);
// } else {
// act.setTheme(R.style.Theme_Light_DarkTitle);
// }
// }
//
// public static boolean shouldDialogInverseBackground(Activity act) {
// return !getDefaultSharedPreferences(act).getBoolean("usedarktheme", true);
// }
// }
// Path: FileManager/src/main/java/org/openintents/filemanager/dialogs/OverwriteFileDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import org.openintents.filemanager.R;
import org.openintents.filemanager.util.UIUtils;
package org.openintents.filemanager.dialogs;
public class OverwriteFileDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity()) | .setInverseBackgroundForced(UIUtils.shouldDialogInverseBackground(getActivity())) |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalVersionType.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
| import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public enum JournalVersionType {
TIMESTAMP {
@Override | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalVersionType.java
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public enum JournalVersionType {
TIMESTAMP {
@Override | public RexNode incrementVersion(JdbcRelBuilder relBuilder, RexNode previousVersion) { |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/AbstractForcedRule.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRule.java
// public interface ForcedRule {
// RelNode apply(RelNode node, JdbcRelBuilderFactory relBuilderFactory);
// }
| import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.schema.Table;
import org.apache.calcite.adapter.jdbc.programs.ForcedRule; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public abstract class AbstractForcedRule implements ForcedRule {
private final LogicalTableModify.Operation operation;
protected AbstractForcedRule(Operation operation) {
this.operation = operation;
}
@Override | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRule.java
// public interface ForcedRule {
// RelNode apply(RelNode node, JdbcRelBuilderFactory relBuilderFactory);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/AbstractForcedRule.java
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.schema.Table;
import org.apache.calcite.adapter.jdbc.programs.ForcedRule;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public abstract class AbstractForcedRule implements ForcedRule {
private final LogicalTableModify.Operation operation;
protected AbstractForcedRule(Operation operation) {
this.operation = operation;
}
@Override | public RelNode apply(RelNode originalRel, JdbcRelBuilderFactory relBuilderFactory) { |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/test/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgramTest.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
| import org.mockito.Mockito;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgramTest {
private Context context;
private RelOptPlanner planner;
private RelTraitSet relTraitSet; | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
// Path: journalled-sql-rewriter/src/test/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgramTest.java
import org.mockito.Mockito;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgramTest {
private Context context;
private RelOptPlanner planner;
private RelTraitSet relTraitSet; | private JdbcRelBuilderFactoryFactory superFactory; |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/test/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgramTest.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
| import org.mockito.Mockito;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgramTest {
private Context context;
private RelOptPlanner planner;
private RelTraitSet relTraitSet;
private JdbcRelBuilderFactoryFactory superFactory; | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
// Path: journalled-sql-rewriter/src/test/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgramTest.java
import org.mockito.Mockito;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgramTest {
private Context context;
private RelOptPlanner planner;
private RelTraitSet relTraitSet;
private JdbcRelBuilderFactoryFactory superFactory; | private JdbcRelBuilderFactory miniFactory; |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledDeleteRule.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
| import java.util.ArrayList;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rex.RexNode; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public class JournalledDeleteRule extends AbstractForcedRule {
public JournalledDeleteRule() {
super(Operation.DELETE);
}
@Override
public RelNode doApply(LogicalTableModify tableModify, JournalledJdbcTable journalTable, | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledDeleteRule.java
import java.util.ArrayList;
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rex.RexNode;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
public class JournalledDeleteRule extends AbstractForcedRule {
public JournalledDeleteRule() {
super(Operation.DELETE);
}
@Override
public RelNode doApply(LogicalTableModify tableModify, JournalledJdbcTable journalTable, | JdbcRelBuilderFactory relBuilderFactory) { |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledJdbcTable.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
| import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import com.google.common.collect.ImmutableList;
import java.util.List; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
class JournalledJdbcTable extends JdbcTable {
private final JdbcTable journalTable;
private final JournalledJdbcSchema journalledJdbcSchema;
private final ImmutableList<String> keyColumnNames; | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledJdbcTable.java
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import com.google.common.collect.ImmutableList;
import java.util.List;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
class JournalledJdbcTable extends JdbcTable {
private final JdbcTable journalTable;
private final JournalledJdbcSchema journalledJdbcSchema;
private final ImmutableList<String> keyColumnNames; | JdbcRelBuilderFactory relBuilderFactory = new JdbcRelBuilder.Factory(null); |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledJdbcTable.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
| import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import com.google.common.collect.ImmutableList;
import java.util.List; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
class JournalledJdbcTable extends JdbcTable {
private final JdbcTable journalTable;
private final JournalledJdbcSchema journalledJdbcSchema;
private final ImmutableList<String> keyColumnNames; | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
// @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) // Public API
// public class JdbcRelBuilder extends RelBuilder {
// private JdbcRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
// super(context, cluster, relOptSchema);
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys
// ) {
// final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);
//
// // TODO
// // This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
// // HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
// // the entire partition - e.g. not setting BOUNDs at all --
// // Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
// // start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
// // syntax.
// List<RexFieldCollation> orderKeys = expressions.stream().map(
// rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());
//
// return makeOver(
// operator,
// expressions,
// partitionKeys,
// ImmutableList.copyOf(orderKeys),
// RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
// RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
// true,
// true,
// false
// );
// }
//
// public RexNode makeOver(
// SqlAggFunction operator,
// List<RexNode> expressions,
// List<RexNode> partitionKeys,
// ImmutableList<RexFieldCollation> orderKeys, // Calcite API is weird
// RexWindowBound lowerBound,
// RexWindowBound upperBound,
// boolean physical,
// boolean allowPartial,
// boolean nullWhenCountZero
// ) {
// List<RelDataType> types = new ArrayList<>(expressions.size());
// for (RexNode n : expressions) {
// types.add(n.getType());
// }
// return getRexBuilder().makeOver(
// operator.inferReturnType(getTypeFactory(), types),
// operator,
// expressions,
// partitionKeys,
// orderKeys,
// lowerBound,
// upperBound,
// physical,
// allowPartial,
// nullWhenCountZero
// );
// }
//
// public RexInputRef appendField(RexNode field) {
// List<RexNode> fields = new ArrayList<>();
// fields.addAll(fields());
// fields.add(field);
// project(fields);
// return field(fields.size() - 1);
// }
//
// // Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
// public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) {
// push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName));
// return this;
// }
//
// public JdbcRelBuilder insertCopying(
// LogicalTableModify original,
// Table table
// ) {
// List<String> name = JdbcTableUtils.getQualifiedName(original.getTable(), table);
//
// push(new LogicalTableModify(
// cluster,
// original.getTraitSet(),
// relOptSchema.getTableForMember(name),
// original.getCatalogReader(),
// peek(),
// TableModify.Operation.INSERT,
// null,
// null,
// original.isFlattened()
// ));
// return this;
// }
//
// public static class Factory implements JdbcRelBuilderFactory {
// private Context context;
//
// public Factory(Context context) {
// this.context = context;
// }
//
// @Override
// public JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema) {
// return new JdbcRelBuilder(context, cluster, schema);
// }
// }
//
// public static class FactoryFactory implements JdbcRelBuilderFactoryFactory {
// @Override
// public JdbcRelBuilderFactory create(Context context) {
// return new JdbcRelBuilder.Factory(context);
// }
// }
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JournalledJdbcTable.java
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import com.google.common.collect.ImmutableList;
import java.util.List;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc;
class JournalledJdbcTable extends JdbcTable {
private final JdbcTable journalTable;
private final JournalledJdbcSchema journalledJdbcSchema;
private final ImmutableList<String> keyColumnNames; | JdbcRelBuilderFactory relBuilderFactory = new JdbcRelBuilder.Factory(null); |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTableUtils.java
// @SuppressWarnings("WeakerAccess") // Public API
// public class JdbcTableUtils {
// private JdbcTableUtils() {
// throw new UnsupportedOperationException();
// }
//
// private static Object get(Class<?> clazz, Object object, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
// field.setAccessible(true);
// return field.get(object);
// }
// catch (NoSuchFieldException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// static JdbcTable getJdbcTable(RelNode originalRel) {
// return (JdbcTable) get(RelOptTableImpl.class, originalRel.getTable(), "table");
// }
//
// static String getCatalogName(JdbcTable table) {
// return (String) get(JdbcTable.class, table, "jdbcCatalogName");
// }
//
// static String getSchemaName(JdbcTable table) {
// return (String) get(JdbcTable.class, table, "jdbcSchemaName");
// }
//
// static String getTableName(JdbcTable table) {
// // tableName is: [catalog,] [schema,] table
// SqlIdentifier identifier = table.tableName();
// return identifier.names.get(identifier.names.size() - 1);
// }
//
// public static List<String> getQualifiedName(RelOptTable sibling, Table table) {
// if (!(table instanceof JdbcTable)) {
// throw new UnsupportedOperationException();
// }
//
// List<String> name = new ArrayList<>();
// if (sibling != null) {
// name.addAll(sibling.getQualifiedName());
// name.remove(name.size() - 1);
// }
// name.add(getTableName((JdbcTable) table));
// return name;
// }
//
// static RelNode toRel(RelOptCluster cluster, RelOptSchema relOptSchema, JdbcTable table, List<String> qualifiedName) {
// RelOptTable.ToRelContext toRelContext = new RelOptTable.ToRelContext() {
// @Override
// public RelOptCluster getCluster() {
// return cluster;
// }
//
// @Override
// public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) {
// throw new UnsupportedOperationException();
// }
// };
//
// return table.toRel(
// toRelContext,
// relOptSchema.getTableForMember(qualifiedName)
// );
// }
//
// public static RelNode toRel(RelOptCluster cluster, RelOptSchema relOptSchema, Table table, List<String> qualifiedName) {
// if (!(table instanceof JdbcTable)) {
// throw new UnsupportedOperationException();
// }
// return toRel(cluster, relOptSchema, (JdbcTable) table, qualifiedName);
// }
// }
| import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.calcite.adapter.jdbc.JdbcTableUtils;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptSchema;
import org.apache.calcite.rel.core.TableModify;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexFieldCollation;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexWindowBound;
import org.apache.calcite.schema.Table;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlWindow;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.tools.RelBuilder;
import com.google.common.collect.ImmutableList; | boolean nullWhenCountZero
) {
List<RelDataType> types = new ArrayList<>(expressions.size());
for (RexNode n : expressions) {
types.add(n.getType());
}
return getRexBuilder().makeOver(
operator.inferReturnType(getTypeFactory(), types),
operator,
expressions,
partitionKeys,
orderKeys,
lowerBound,
upperBound,
physical,
allowPartial,
nullWhenCountZero
);
}
public RexInputRef appendField(RexNode field) {
List<RexNode> fields = new ArrayList<>();
fields.addAll(fields());
fields.add(field);
project(fields);
return field(fields.size() - 1);
}
// Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) { | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/JdbcTableUtils.java
// @SuppressWarnings("WeakerAccess") // Public API
// public class JdbcTableUtils {
// private JdbcTableUtils() {
// throw new UnsupportedOperationException();
// }
//
// private static Object get(Class<?> clazz, Object object, String fieldName) {
// try {
// Field field = clazz.getDeclaredField(fieldName);
// field.setAccessible(true);
// return field.get(object);
// }
// catch (NoSuchFieldException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// static JdbcTable getJdbcTable(RelNode originalRel) {
// return (JdbcTable) get(RelOptTableImpl.class, originalRel.getTable(), "table");
// }
//
// static String getCatalogName(JdbcTable table) {
// return (String) get(JdbcTable.class, table, "jdbcCatalogName");
// }
//
// static String getSchemaName(JdbcTable table) {
// return (String) get(JdbcTable.class, table, "jdbcSchemaName");
// }
//
// static String getTableName(JdbcTable table) {
// // tableName is: [catalog,] [schema,] table
// SqlIdentifier identifier = table.tableName();
// return identifier.names.get(identifier.names.size() - 1);
// }
//
// public static List<String> getQualifiedName(RelOptTable sibling, Table table) {
// if (!(table instanceof JdbcTable)) {
// throw new UnsupportedOperationException();
// }
//
// List<String> name = new ArrayList<>();
// if (sibling != null) {
// name.addAll(sibling.getQualifiedName());
// name.remove(name.size() - 1);
// }
// name.add(getTableName((JdbcTable) table));
// return name;
// }
//
// static RelNode toRel(RelOptCluster cluster, RelOptSchema relOptSchema, JdbcTable table, List<String> qualifiedName) {
// RelOptTable.ToRelContext toRelContext = new RelOptTable.ToRelContext() {
// @Override
// public RelOptCluster getCluster() {
// return cluster;
// }
//
// @Override
// public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) {
// throw new UnsupportedOperationException();
// }
// };
//
// return table.toRel(
// toRelContext,
// relOptSchema.getTableForMember(qualifiedName)
// );
// }
//
// public static RelNode toRel(RelOptCluster cluster, RelOptSchema relOptSchema, Table table, List<String> qualifiedName) {
// if (!(table instanceof JdbcTable)) {
// throw new UnsupportedOperationException();
// }
// return toRel(cluster, relOptSchema, (JdbcTable) table, qualifiedName);
// }
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilder.java
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.calcite.adapter.jdbc.JdbcTableUtils;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptSchema;
import org.apache.calcite.rel.core.TableModify;
import org.apache.calcite.rel.logical.LogicalTableModify;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexFieldCollation;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexWindowBound;
import org.apache.calcite.schema.Table;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlWindow;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.tools.RelBuilder;
import com.google.common.collect.ImmutableList;
boolean nullWhenCountZero
) {
List<RelDataType> types = new ArrayList<>(expressions.size());
for (RexNode n : expressions) {
types.add(n.getType());
}
return getRexBuilder().makeOver(
operator.inferReturnType(getTypeFactory(), types),
operator,
expressions,
partitionKeys,
orderKeys,
lowerBound,
upperBound,
physical,
allowPartial,
nullWhenCountZero
);
}
public RexInputRef appendField(RexNode field) {
List<RexNode> fields = new ArrayList<>();
fields.addAll(fields());
fields.add(field);
project(fields);
return field(fields.size() - 1);
}
// Table MUST be a JdbcTable (cannot be type-safe since JdbcTable is package-private)
public JdbcRelBuilder scanJdbc(Table table, List<String> qualifiedName) { | push(JdbcTableUtils.toRel(cluster, relOptSchema, table, qualifiedName)); |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgram.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
| import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.apache.calcite.util.Litmus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgram implements Program {
private static final Logger logger = LoggerFactory.getLogger(ForcedRulesProgram.class);
| // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgram.java
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.apache.calcite.util.Litmus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgram implements Program {
private static final Logger logger = LoggerFactory.getLogger(ForcedRulesProgram.class);
| private final JdbcRelBuilderFactoryFactory relBuilderFactoryFactory; |
tzolov/calcite-sql-rewriter | journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgram.java | // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
| import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.apache.calcite.util.Litmus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgram implements Program {
private static final Logger logger = LoggerFactory.getLogger(ForcedRulesProgram.class);
private final JdbcRelBuilderFactoryFactory relBuilderFactoryFactory;
private final ForcedRule[] rules;
public ForcedRulesProgram(JdbcRelBuilderFactoryFactory relBuilderFactoryFactory, ForcedRule... rules) {
this.relBuilderFactoryFactory = relBuilderFactoryFactory;
this.rules = rules;
}
@Override
public RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> list1) {
logger.debug("Running forced rules on:\n" + RelOptUtil.toString(relNode));
return replace(relNode, rules, relBuilderFactoryFactory.create(relOptPlanner.getContext()));
}
| // Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactory.java
// public interface JdbcRelBuilderFactory extends RelBuilderFactory {
// JdbcRelBuilder create(RelOptCluster cluster, RelOptSchema schema);
// }
//
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/tools/JdbcRelBuilderFactoryFactory.java
// public interface JdbcRelBuilderFactoryFactory {
// JdbcRelBuilderFactory create(Context context);
// }
// Path: journalled-sql-rewriter/src/main/java/org/apache/calcite/adapter/jdbc/programs/ForcedRulesProgram.java
import java.util.List;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactoryFactory;
import org.apache.calcite.plan.RelOptLattice;
import org.apache.calcite.plan.RelOptMaterialization;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.tools.Program;
import org.apache.calcite.util.Litmus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2012-2014 the original author or authors.
*
* 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 org.apache.calcite.adapter.jdbc.programs;
public class ForcedRulesProgram implements Program {
private static final Logger logger = LoggerFactory.getLogger(ForcedRulesProgram.class);
private final JdbcRelBuilderFactoryFactory relBuilderFactoryFactory;
private final ForcedRule[] rules;
public ForcedRulesProgram(JdbcRelBuilderFactoryFactory relBuilderFactoryFactory, ForcedRule... rules) {
this.relBuilderFactoryFactory = relBuilderFactoryFactory;
this.rules = rules;
}
@Override
public RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> list1) {
logger.debug("Running forced rules on:\n" + RelOptUtil.toString(relNode));
return replace(relNode, rules, relBuilderFactoryFactory.create(relOptPlanner.getContext()));
}
| private RelNode replace(RelNode original, ForcedRule[] rules, JdbcRelBuilderFactory relBuilderFactory) { |
a-schild/nextcloud-java-api | src/test/java/org/aarboard/nextcloud/api/TestUserGroupAdmin.java | // Path: src/main/java/org/aarboard/nextcloud/api/provisioning/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class User
// {
// private String id;
// private boolean enabled;
// private String email;
// private String displayname;
// private String phone;
// private String address;
// private String website;
// private String twitter;
// private Quota quota;
// private List<String> groups;
//
// public String getId() {
// return id;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayname() {
// return displayname;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getTwitter() {
// return twitter;
// }
//
// public Quota getQuota() {
// return quota;
// }
//
// public List<String> getGroups() {
// return groups;
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/provisioning/UserData.java
// public enum UserData {
// EMAIL,
// QUOTA,
// DISPLAYNAME,
// PHONE,
// ADDRESS,
// WEBSITE,
// TWITTER,
// PASSWORD
// }
| import org.aarboard.nextcloud.api.provisioning.User;
import org.aarboard.nextcloud.api.provisioning.UserData;
import org.apache.commons.lang3.StringUtils;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.*;
| boolean result = _nc.createUser(TESTUSER+"Full", "aBcDeFg123456",
"Full Test User", "full@test.org", "5368709120000B", "de", Arrays.asList(TESTGROUP));
assertTrue(result);
}
}
@Test
public void t04_02_testCreateUserWithInvalidChar() {
System.out.println("createUserWithInvalidChar");
if (_nc != null) {
boolean result = _nc.createUser(TESTUSER_WITH_INVALID_CHAR, "aBcDeFg123456");
assertTrue(result);
}
}
@Test
public void t05_00_testGetUsers() {
System.out.println("getUsers");
if (_nc != null) {
Collection<String> result = _nc.getUsers();
assertNotNull(result);
assertTrue(result.contains(TESTUSER));
}
}
@Test
public void t05_01_testGetUsersDetails() {
System.out.println("getUsersDetails");
if (_nc != null)
{
| // Path: src/main/java/org/aarboard/nextcloud/api/provisioning/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class User
// {
// private String id;
// private boolean enabled;
// private String email;
// private String displayname;
// private String phone;
// private String address;
// private String website;
// private String twitter;
// private Quota quota;
// private List<String> groups;
//
// public String getId() {
// return id;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayname() {
// return displayname;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getTwitter() {
// return twitter;
// }
//
// public Quota getQuota() {
// return quota;
// }
//
// public List<String> getGroups() {
// return groups;
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/provisioning/UserData.java
// public enum UserData {
// EMAIL,
// QUOTA,
// DISPLAYNAME,
// PHONE,
// ADDRESS,
// WEBSITE,
// TWITTER,
// PASSWORD
// }
// Path: src/test/java/org/aarboard/nextcloud/api/TestUserGroupAdmin.java
import org.aarboard.nextcloud.api.provisioning.User;
import org.aarboard.nextcloud.api.provisioning.UserData;
import org.apache.commons.lang3.StringUtils;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.*;
boolean result = _nc.createUser(TESTUSER+"Full", "aBcDeFg123456",
"Full Test User", "full@test.org", "5368709120000B", "de", Arrays.asList(TESTGROUP));
assertTrue(result);
}
}
@Test
public void t04_02_testCreateUserWithInvalidChar() {
System.out.println("createUserWithInvalidChar");
if (_nc != null) {
boolean result = _nc.createUser(TESTUSER_WITH_INVALID_CHAR, "aBcDeFg123456");
assertTrue(result);
}
}
@Test
public void t05_00_testGetUsers() {
System.out.println("getUsers");
if (_nc != null) {
Collection<String> result = _nc.getUsers();
assertNotNull(result);
assertTrue(result.contains(TESTUSER));
}
}
@Test
public void t05_01_testGetUsersDetails() {
System.out.println("getUsersDetails");
if (_nc != null)
{
| Collection<User> result = _nc.getUsersDetails();
|
a-schild/nextcloud-java-api | src/test/java/org/aarboard/nextcloud/api/TestUserGroupAdmin.java | // Path: src/main/java/org/aarboard/nextcloud/api/provisioning/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class User
// {
// private String id;
// private boolean enabled;
// private String email;
// private String displayname;
// private String phone;
// private String address;
// private String website;
// private String twitter;
// private Quota quota;
// private List<String> groups;
//
// public String getId() {
// return id;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayname() {
// return displayname;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getTwitter() {
// return twitter;
// }
//
// public Quota getQuota() {
// return quota;
// }
//
// public List<String> getGroups() {
// return groups;
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/provisioning/UserData.java
// public enum UserData {
// EMAIL,
// QUOTA,
// DISPLAYNAME,
// PHONE,
// ADDRESS,
// WEBSITE,
// TWITTER,
// PASSWORD
// }
| import org.aarboard.nextcloud.api.provisioning.User;
import org.aarboard.nextcloud.api.provisioning.UserData;
import org.apache.commons.lang3.StringUtils;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.*;
| System.out.println("getUsers");
if (_nc != null) {
String search = TESTUSER;
int limit = 1;
int offset = -1;
Collection<String> result = _nc.getUsers(search, limit, offset);
assertNotNull(result);
assertTrue(result.contains(TESTUSER));
}
}
@Test
public void t06_01_testGetUsersDetails_3args() {
System.out.println("getUsersDetails");
if (_nc != null) {
int limit = 1;
int offset = -1;
Collection<User> result1 = _nc.getUsersDetails(TESTUSER, limit, offset);
assertNotNull(result1);
assertTrue(result1.stream().anyMatch(user -> TESTUSER.equals(user.getId())));
Collection<User> result2 = _nc.getUsersDetails(TESTUSER_WITH_INVALID_CHAR, limit, offset);
assertNotNull(result2);
assertTrue(result2.stream().anyMatch(user -> TESTUSER_WITH_INVALID_CHAR.equals(user.getId())));
}
}
@Test
public void t07_testEditUser() {
System.out.println("editUser");
if (_nc != null) {
| // Path: src/main/java/org/aarboard/nextcloud/api/provisioning/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class User
// {
// private String id;
// private boolean enabled;
// private String email;
// private String displayname;
// private String phone;
// private String address;
// private String website;
// private String twitter;
// private Quota quota;
// private List<String> groups;
//
// public String getId() {
// return id;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getDisplayname() {
// return displayname;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public String getWebsite() {
// return website;
// }
//
// public String getTwitter() {
// return twitter;
// }
//
// public Quota getQuota() {
// return quota;
// }
//
// public List<String> getGroups() {
// return groups;
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/provisioning/UserData.java
// public enum UserData {
// EMAIL,
// QUOTA,
// DISPLAYNAME,
// PHONE,
// ADDRESS,
// WEBSITE,
// TWITTER,
// PASSWORD
// }
// Path: src/test/java/org/aarboard/nextcloud/api/TestUserGroupAdmin.java
import org.aarboard.nextcloud.api.provisioning.User;
import org.aarboard.nextcloud.api.provisioning.UserData;
import org.apache.commons.lang3.StringUtils;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.*;
System.out.println("getUsers");
if (_nc != null) {
String search = TESTUSER;
int limit = 1;
int offset = -1;
Collection<String> result = _nc.getUsers(search, limit, offset);
assertNotNull(result);
assertTrue(result.contains(TESTUSER));
}
}
@Test
public void t06_01_testGetUsersDetails_3args() {
System.out.println("getUsersDetails");
if (_nc != null) {
int limit = 1;
int offset = -1;
Collection<User> result1 = _nc.getUsersDetails(TESTUSER, limit, offset);
assertNotNull(result1);
assertTrue(result1.stream().anyMatch(user -> TESTUSER.equals(user.getId())));
Collection<User> result2 = _nc.getUsersDetails(TESTUSER_WITH_INVALID_CHAR, limit, offset);
assertNotNull(result2);
assertTrue(result2.stream().anyMatch(user -> TESTUSER_WITH_INVALID_CHAR.equals(user.getId())));
}
}
@Test
public void t07_testEditUser() {
System.out.println("editUser");
if (_nc != null) {
| boolean result = _nc.editUser(TESTUSER, UserData.TWITTER, "test");
|
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/utils/XMLAnswerParser.java | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/ConnectorCommon.java
// public interface ResponseParser<R> {
// R parseResponse(Reader reader);
// }
| import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.utils.ConnectorCommon.ResponseParser;
| package org.aarboard.nextcloud.api.utils;
public class XMLAnswerParser<A extends XMLAnswer> implements ResponseParser<A>
{
private static final Map<String, XMLAnswerParser<? extends XMLAnswer>> PARSERS = new HashMap<>();
private final JAXBContext jAXBContext;
public XMLAnswerParser(Class<A> answerClass)
{
try {
jAXBContext = JAXBContext.newInstance(XMLAnswer.class, answerClass);
} catch (JAXBException e) {
| // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/ConnectorCommon.java
// public interface ResponseParser<R> {
// R parseResponse(Reader reader);
// }
// Path: src/main/java/org/aarboard/nextcloud/api/utils/XMLAnswerParser.java
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.utils.ConnectorCommon.ResponseParser;
package org.aarboard.nextcloud.api.utils;
public class XMLAnswerParser<A extends XMLAnswer> implements ResponseParser<A>
{
private static final Map<String, XMLAnswerParser<? extends XMLAnswer>> PARSERS = new HashMap<>();
private final JAXBContext jAXBContext;
public XMLAnswerParser(Class<A> answerClass)
{
try {
jAXBContext = JAXBContext.newInstance(XMLAnswer.class, answerClass);
} catch (JAXBException e) {
| throw new NextcloudApiException(e);
|
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/utils/JsonAnswerParser.java | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
| import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map; | package org.aarboard.nextcloud.api.utils;
public class JsonAnswerParser<A extends JsonAnswer> implements ConnectorCommon.ResponseParser<A> {
private static final Map<String, JsonAnswerParser<? extends JsonAnswer>> PARSERS = new HashMap<>();
private final ObjectReader objectReader;
private JsonAnswerParser(Class<A> answerClass) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
objectReader = objectMapper.readerFor(answerClass);
}
public static <A extends JsonAnswer> JsonAnswerParser<A> getInstance(Class<A> answerClass) {
@SuppressWarnings("unchecked")
JsonAnswerParser<A> parser = (JsonAnswerParser<A>) PARSERS.get(answerClass.getName());
if (parser == null) {
synchronized (PARSERS) {
if (parser == null) {
parser = new JsonAnswerParser<>(answerClass);
PARSERS.put(answerClass.getName(), parser);
}
}
}
return parser;
}
@Override
public A parseResponse(Reader reader) {
try (Reader response = reader) {
return objectReader.readValue(response);
} catch (IOException e) { | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/utils/JsonAnswerParser.java
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
package org.aarboard.nextcloud.api.utils;
public class JsonAnswerParser<A extends JsonAnswer> implements ConnectorCommon.ResponseParser<A> {
private static final Map<String, JsonAnswerParser<? extends JsonAnswer>> PARSERS = new HashMap<>();
private final ObjectReader objectReader;
private JsonAnswerParser(Class<A> answerClass) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
objectReader = objectMapper.readerFor(answerClass);
}
public static <A extends JsonAnswer> JsonAnswerParser<A> getInstance(Class<A> answerClass) {
@SuppressWarnings("unchecked")
JsonAnswerParser<A> parser = (JsonAnswerParser<A>) PARSERS.get(answerClass.getName());
if (parser == null) {
synchronized (PARSERS) {
if (parser == null) {
parser = new JsonAnswerParser<>(answerClass);
PARSERS.put(answerClass.getName(), parser);
}
}
}
return parser;
}
@Override
public A parseResponse(Reader reader) {
try (Reader response = reader) {
return objectReader.readValue(response);
} catch (IOException e) { | throw new NextcloudApiException(e); |
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/webdav/pathresolver/NextcloudVersion.java | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import org.aarboard.nextcloud.api.exception.NextcloudApiException; |
if (values.length > 2)
{
patch = values[2];
}
if (values.length > 3)
{
revision = values[3];
}
if (compatibleVersion > 14)
{
compatibleVersion = 20;
}
else
{
compatibleVersion = 14;
}
}
private void loadValues()
{
try (InputStream inStream = getClass().getResourceAsStream(MessageFormat.format(PROPERTIES_PATH_PATTERN, compatibleVersion.toString())))
{
configProperties.load(inStream);
}
catch (IOException ex)
{ | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/webdav/pathresolver/NextcloudVersion.java
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
if (values.length > 2)
{
patch = values[2];
}
if (values.length > 3)
{
revision = values[3];
}
if (compatibleVersion > 14)
{
compatibleVersion = 20;
}
else
{
compatibleVersion = 14;
}
}
private void loadValues()
{
try (InputStream inStream = getClass().getResourceAsStream(MessageFormat.format(PROPERTIES_PATH_PATTERN, compatibleVersion.toString())))
{
configProperties.load(inStream);
}
catch (IOException ex)
{ | throw new NextcloudApiException(ex); |
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/utils/NextcloudResponseHelper.java | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudOperationFailedException.java
// public class NextcloudOperationFailedException extends NextcloudApiException {
// private static final long serialVersionUID = 6382478664807826933L;
//
// public NextcloudOperationFailedException(int statuscode, String message) {
// super(String.format("Nextcloud API call failed with statuscode %d and message \"%s\"", statuscode, message));
// }
// }
| import java.util.concurrent.CompletableFuture;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.exception.NextcloudOperationFailedException; | package org.aarboard.nextcloud.api.utils;
public class NextcloudResponseHelper
{
public static final int NC_OK= 100; // Nextcloud OK message
private NextcloudResponseHelper() {
}
public static <A extends NextcloudResponse> A getAndCheckStatus(CompletableFuture<A> answer)
{
A wrappedAnswer = getAndWrapException(answer);
if(isStatusCodeOkay(wrappedAnswer))
{
return wrappedAnswer;
} | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudOperationFailedException.java
// public class NextcloudOperationFailedException extends NextcloudApiException {
// private static final long serialVersionUID = 6382478664807826933L;
//
// public NextcloudOperationFailedException(int statuscode, String message) {
// super(String.format("Nextcloud API call failed with statuscode %d and message \"%s\"", statuscode, message));
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/utils/NextcloudResponseHelper.java
import java.util.concurrent.CompletableFuture;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.exception.NextcloudOperationFailedException;
package org.aarboard.nextcloud.api.utils;
public class NextcloudResponseHelper
{
public static final int NC_OK= 100; // Nextcloud OK message
private NextcloudResponseHelper() {
}
public static <A extends NextcloudResponse> A getAndCheckStatus(CompletableFuture<A> answer)
{
A wrappedAnswer = getAndWrapException(answer);
if(isStatusCodeOkay(wrappedAnswer))
{
return wrappedAnswer;
} | throw new NextcloudOperationFailedException(wrappedAnswer.getStatusCode(), wrappedAnswer.getMessage()); |
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/utils/NextcloudResponseHelper.java | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudOperationFailedException.java
// public class NextcloudOperationFailedException extends NextcloudApiException {
// private static final long serialVersionUID = 6382478664807826933L;
//
// public NextcloudOperationFailedException(int statuscode, String message) {
// super(String.format("Nextcloud API call failed with statuscode %d and message \"%s\"", statuscode, message));
// }
// }
| import java.util.concurrent.CompletableFuture;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.exception.NextcloudOperationFailedException; | package org.aarboard.nextcloud.api.utils;
public class NextcloudResponseHelper
{
public static final int NC_OK= 100; // Nextcloud OK message
private NextcloudResponseHelper() {
}
public static <A extends NextcloudResponse> A getAndCheckStatus(CompletableFuture<A> answer)
{
A wrappedAnswer = getAndWrapException(answer);
if(isStatusCodeOkay(wrappedAnswer))
{
return wrappedAnswer;
}
throw new NextcloudOperationFailedException(wrappedAnswer.getStatusCode(), wrappedAnswer.getMessage());
}
public static <A extends NextcloudResponse> boolean isStatusCodeOkay(CompletableFuture<A> answer)
{
return isStatusCodeOkay(getAndWrapException(answer));
}
public static boolean isStatusCodeOkay(NextcloudResponse answer)
{
return answer.getStatusCode() == NC_OK;
}
public static <A> A getAndWrapException(CompletableFuture<A> answer)
{
try {
return answer.get();
} catch (Exception e) { | // Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudApiException.java
// public class NextcloudApiException extends RuntimeException {
// private static final long serialVersionUID = 8088239559973590632L;
//
// public NextcloudApiException(Throwable cause) {
// super(cause);
// }
//
// public NextcloudApiException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/exception/NextcloudOperationFailedException.java
// public class NextcloudOperationFailedException extends NextcloudApiException {
// private static final long serialVersionUID = 6382478664807826933L;
//
// public NextcloudOperationFailedException(int statuscode, String message) {
// super(String.format("Nextcloud API call failed with statuscode %d and message \"%s\"", statuscode, message));
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/utils/NextcloudResponseHelper.java
import java.util.concurrent.CompletableFuture;
import org.aarboard.nextcloud.api.exception.NextcloudApiException;
import org.aarboard.nextcloud.api.exception.NextcloudOperationFailedException;
package org.aarboard.nextcloud.api.utils;
public class NextcloudResponseHelper
{
public static final int NC_OK= 100; // Nextcloud OK message
private NextcloudResponseHelper() {
}
public static <A extends NextcloudResponse> A getAndCheckStatus(CompletableFuture<A> answer)
{
A wrappedAnswer = getAndWrapException(answer);
if(isStatusCodeOkay(wrappedAnswer))
{
return wrappedAnswer;
}
throw new NextcloudOperationFailedException(wrappedAnswer.getStatusCode(), wrappedAnswer.getMessage());
}
public static <A extends NextcloudResponse> boolean isStatusCodeOkay(CompletableFuture<A> answer)
{
return isStatusCodeOkay(getAndWrapException(answer));
}
public static boolean isStatusCodeOkay(NextcloudResponse answer)
{
return answer.getStatusCode() == NC_OK;
}
public static <A> A getAndWrapException(CompletableFuture<A> answer)
{
try {
return answer.get();
} catch (Exception e) { | throw new NextcloudApiException(e); |
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/filesharing/Share.java | // Path: src/main/java/org/aarboard/nextcloud/api/utils/InstantXmlAdapter.java
// public class InstantXmlAdapter extends XmlAdapter<Long, Instant>
// {
// @Override
// public Long marshal(Instant instant)
// {
// return instant.getEpochSecond();
// }
//
// @Override
// public Instant unmarshal(Long time)
// {
// return Instant.ofEpochSecond(time);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/LocalDateXmlAdapter.java
// public class LocalDateXmlAdapter extends XmlAdapter<String, LocalDate>
// {
// @Override
// public String marshal(LocalDate date)
// {
// return date.toString();
// }
//
// @Override
// public LocalDate unmarshal(String date)
// {
// return LocalDate.parse(date.substring(0, 10));
// }
// }
| import java.time.Instant;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.aarboard.nextcloud.api.utils.InstantXmlAdapter;
import org.aarboard.nextcloud.api.utils.LocalDateXmlAdapter; | /*
* Copyright (C) 2017 a.schild
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.aarboard.nextcloud.api.filesharing;
/**
*
* @author a.schild
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class Share
{
private int id;
@XmlElement(name = "share_type")
private ShareType shareType;
@XmlElement(name = "uid_owner")
private String ownerId;
@XmlElement(name = "displayname_owner")
private String ownerDisplayName;
@XmlElement(name = "permissions")
@XmlJavaTypeAdapter(SharePermissionsAdapter.class)
private SharePermissions sharePermissions;
@XmlElement(name = "uid_file_owner")
private String fileOwnerId;
@XmlElement(name = "displayname_file_owner")
private String fileOwnerDisplayName;
private String path;
@XmlElement(name = "item_type")
private ItemType itemType;
@XmlElement(name = "file_target")
private String fileTarget;
@XmlElement(name = "share_with")
private String shareWithId;
@XmlElement(name = "share_with_displayname")
private String shareWithDisplayName;
private String token;
@XmlElement(name = "stime") | // Path: src/main/java/org/aarboard/nextcloud/api/utils/InstantXmlAdapter.java
// public class InstantXmlAdapter extends XmlAdapter<Long, Instant>
// {
// @Override
// public Long marshal(Instant instant)
// {
// return instant.getEpochSecond();
// }
//
// @Override
// public Instant unmarshal(Long time)
// {
// return Instant.ofEpochSecond(time);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/LocalDateXmlAdapter.java
// public class LocalDateXmlAdapter extends XmlAdapter<String, LocalDate>
// {
// @Override
// public String marshal(LocalDate date)
// {
// return date.toString();
// }
//
// @Override
// public LocalDate unmarshal(String date)
// {
// return LocalDate.parse(date.substring(0, 10));
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/filesharing/Share.java
import java.time.Instant;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.aarboard.nextcloud.api.utils.InstantXmlAdapter;
import org.aarboard.nextcloud.api.utils.LocalDateXmlAdapter;
/*
* Copyright (C) 2017 a.schild
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.aarboard.nextcloud.api.filesharing;
/**
*
* @author a.schild
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class Share
{
private int id;
@XmlElement(name = "share_type")
private ShareType shareType;
@XmlElement(name = "uid_owner")
private String ownerId;
@XmlElement(name = "displayname_owner")
private String ownerDisplayName;
@XmlElement(name = "permissions")
@XmlJavaTypeAdapter(SharePermissionsAdapter.class)
private SharePermissions sharePermissions;
@XmlElement(name = "uid_file_owner")
private String fileOwnerId;
@XmlElement(name = "displayname_file_owner")
private String fileOwnerDisplayName;
private String path;
@XmlElement(name = "item_type")
private ItemType itemType;
@XmlElement(name = "file_target")
private String fileTarget;
@XmlElement(name = "share_with")
private String shareWithId;
@XmlElement(name = "share_with_displayname")
private String shareWithDisplayName;
private String token;
@XmlElement(name = "stime") | @XmlJavaTypeAdapter(InstantXmlAdapter.class) |
a-schild/nextcloud-java-api | src/main/java/org/aarboard/nextcloud/api/filesharing/Share.java | // Path: src/main/java/org/aarboard/nextcloud/api/utils/InstantXmlAdapter.java
// public class InstantXmlAdapter extends XmlAdapter<Long, Instant>
// {
// @Override
// public Long marshal(Instant instant)
// {
// return instant.getEpochSecond();
// }
//
// @Override
// public Instant unmarshal(Long time)
// {
// return Instant.ofEpochSecond(time);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/LocalDateXmlAdapter.java
// public class LocalDateXmlAdapter extends XmlAdapter<String, LocalDate>
// {
// @Override
// public String marshal(LocalDate date)
// {
// return date.toString();
// }
//
// @Override
// public LocalDate unmarshal(String date)
// {
// return LocalDate.parse(date.substring(0, 10));
// }
// }
| import java.time.Instant;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.aarboard.nextcloud.api.utils.InstantXmlAdapter;
import org.aarboard.nextcloud.api.utils.LocalDateXmlAdapter; | @XmlAccessorType(XmlAccessType.FIELD)
public class Share
{
private int id;
@XmlElement(name = "share_type")
private ShareType shareType;
@XmlElement(name = "uid_owner")
private String ownerId;
@XmlElement(name = "displayname_owner")
private String ownerDisplayName;
@XmlElement(name = "permissions")
@XmlJavaTypeAdapter(SharePermissionsAdapter.class)
private SharePermissions sharePermissions;
@XmlElement(name = "uid_file_owner")
private String fileOwnerId;
@XmlElement(name = "displayname_file_owner")
private String fileOwnerDisplayName;
private String path;
@XmlElement(name = "item_type")
private ItemType itemType;
@XmlElement(name = "file_target")
private String fileTarget;
@XmlElement(name = "share_with")
private String shareWithId;
@XmlElement(name = "share_with_displayname")
private String shareWithDisplayName;
private String token;
@XmlElement(name = "stime")
@XmlJavaTypeAdapter(InstantXmlAdapter.class)
private Instant shareTime; | // Path: src/main/java/org/aarboard/nextcloud/api/utils/InstantXmlAdapter.java
// public class InstantXmlAdapter extends XmlAdapter<Long, Instant>
// {
// @Override
// public Long marshal(Instant instant)
// {
// return instant.getEpochSecond();
// }
//
// @Override
// public Instant unmarshal(Long time)
// {
// return Instant.ofEpochSecond(time);
// }
// }
//
// Path: src/main/java/org/aarboard/nextcloud/api/utils/LocalDateXmlAdapter.java
// public class LocalDateXmlAdapter extends XmlAdapter<String, LocalDate>
// {
// @Override
// public String marshal(LocalDate date)
// {
// return date.toString();
// }
//
// @Override
// public LocalDate unmarshal(String date)
// {
// return LocalDate.parse(date.substring(0, 10));
// }
// }
// Path: src/main/java/org/aarboard/nextcloud/api/filesharing/Share.java
import java.time.Instant;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.aarboard.nextcloud.api.utils.InstantXmlAdapter;
import org.aarboard.nextcloud.api.utils.LocalDateXmlAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
public class Share
{
private int id;
@XmlElement(name = "share_type")
private ShareType shareType;
@XmlElement(name = "uid_owner")
private String ownerId;
@XmlElement(name = "displayname_owner")
private String ownerDisplayName;
@XmlElement(name = "permissions")
@XmlJavaTypeAdapter(SharePermissionsAdapter.class)
private SharePermissions sharePermissions;
@XmlElement(name = "uid_file_owner")
private String fileOwnerId;
@XmlElement(name = "displayname_file_owner")
private String fileOwnerDisplayName;
private String path;
@XmlElement(name = "item_type")
private ItemType itemType;
@XmlElement(name = "file_target")
private String fileTarget;
@XmlElement(name = "share_with")
private String shareWithId;
@XmlElement(name = "share_with_displayname")
private String shareWithDisplayName;
private String token;
@XmlElement(name = "stime")
@XmlJavaTypeAdapter(InstantXmlAdapter.class)
private Instant shareTime; | @XmlJavaTypeAdapter(LocalDateXmlAdapter.class) |
Jardo-51/user_module | core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
| /*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule;
@RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
private static final long ONE_DAY = 86400000L;
// password = 'password'
private static final String STORED_PASSWORD_HASH = "C0794DCF71360C8A6302C49B3228CBCFFC8CD07BBC55250EAC7D2C599B9AE2BD";
private static final String STORED_PASSWORD_SALT = "7886788CB39BF33C856EF18206A81CE4B498DC5A1A4199ABC0CB0FB686EAB008";
private static final String HASH_ENCODING = "UTF-16";
@Spy
private UserManagementProperties properties = new UserManagementPropertiesImpl();
@Mock
private EmailSender emailSender;
@Mock
private UserDatabaseModel databaseModel;
@Mock
private SessionModel sessionModel;
@InjectMocks
private UserManager userManager;
private final String inetAddress;
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
// Path: core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
/*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule;
@RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
private static final long ONE_DAY = 86400000L;
// password = 'password'
private static final String STORED_PASSWORD_HASH = "C0794DCF71360C8A6302C49B3228CBCFFC8CD07BBC55250EAC7D2C599B9AE2BD";
private static final String STORED_PASSWORD_SALT = "7886788CB39BF33C856EF18206A81CE4B498DC5A1A4199ABC0CB0FB686EAB008";
private static final String HASH_ENCODING = "UTF-16";
@Spy
private UserManagementProperties properties = new UserManagementPropertiesImpl();
@Mock
private EmailSender emailSender;
@Mock
private UserDatabaseModel databaseModel;
@Mock
private SessionModel sessionModel;
@InjectMocks
private UserManager userManager;
private final String inetAddress;
| private final UserPassword storedPassword;
|
Jardo-51/user_module | core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
| ResultCode result = userManager.confirmRegistration("john@example.com", storedUser.getRegistrationControlCode());
Assert.assertEquals(ResultCode.NO_SUCH_USER, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testConfirmRegistrationInvalidControlCode() {
Mockito.when(databaseModel.getUserByEmail("john@example.com")).thenReturn(userWithUnfinishedRegistration);
String invalidControlCode = "d9d8172ffa4e21f955e8ad125f9dbc32";
ResultCode result = userManager.confirmRegistration("john@example.com", invalidControlCode);
Assert.assertEquals(ResultCode.INVALID_REGISTRATION_CONTROL_CODE, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testConfirmRegistrationAlreadyConfirmed() {
Mockito.when(databaseModel.getUserByEmail("john@example.com")).thenReturn(storedUser);
ResultCode result = userManager.confirmRegistration("john@example.com", storedUser.getRegistrationControlCode());
Assert.assertEquals(ResultCode.REGISTRATION_ALREADY_CONFIRMED, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testCreatePasswordResetToken() {
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
// Path: core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
ResultCode result = userManager.confirmRegistration("john@example.com", storedUser.getRegistrationControlCode());
Assert.assertEquals(ResultCode.NO_SUCH_USER, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testConfirmRegistrationInvalidControlCode() {
Mockito.when(databaseModel.getUserByEmail("john@example.com")).thenReturn(userWithUnfinishedRegistration);
String invalidControlCode = "d9d8172ffa4e21f955e8ad125f9dbc32";
ResultCode result = userManager.confirmRegistration("john@example.com", invalidControlCode);
Assert.assertEquals(ResultCode.INVALID_REGISTRATION_CONTROL_CODE, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testConfirmRegistrationAlreadyConfirmed() {
Mockito.when(databaseModel.getUserByEmail("john@example.com")).thenReturn(storedUser);
ResultCode result = userManager.confirmRegistration("john@example.com", storedUser.getRegistrationControlCode());
Assert.assertEquals(ResultCode.REGISTRATION_ALREADY_CONFIRMED, result);
Mockito.verify(databaseModel, Mockito.never()).confirmUserRegistration("john@example.com");
}
@Test
public void testCreatePasswordResetToken() {
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
| Mockito.when(databaseModel.addPasswordResetToken(Mockito.any(PasswordResetToken.class))).thenReturn(true);
|
Jardo-51/user_module | core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
|
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
Mockito.verify(sessionModel).setCurrentUser(userCaptor.capture());
Assert.assertSame(storedUser, userCaptor.getValue());
Mockito.verify(databaseModel, Mockito.never()).makeLogInRecord(Mockito.anyInt(), Mockito.anyBoolean(), Mockito.anyString());
Mockito.verify(databaseModel, Mockito.never()).cancelAllPasswordResetTokens(Mockito.anyInt());
}
@Test
public void testLogInWithUserName() {
Mockito.when(databaseModel.getUserByName("john")).thenReturn(storedUser);
ResultCode result = userManager.logIn("john", "password", inetAddress);
Assert.assertEquals(ResultCode.OK, result);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
Mockito.verify(sessionModel).setCurrentUser(userCaptor.capture());
Assert.assertSame(storedUser, userCaptor.getValue());
ArgumentCaptor<String> ipCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(databaseModel).makeLogInRecord(Mockito.eq(1), Mockito.eq(true), ipCaptor.capture());
Assert.assertSame(inetAddress, ipCaptor.getValue());
Mockito.verify(databaseModel).cancelAllPasswordResetTokens(1);
}
@Test
public void testLoginOrRegisterWithSocialAccount_existingUser() {
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
// Path: core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
Mockito.verify(sessionModel).setCurrentUser(userCaptor.capture());
Assert.assertSame(storedUser, userCaptor.getValue());
Mockito.verify(databaseModel, Mockito.never()).makeLogInRecord(Mockito.anyInt(), Mockito.anyBoolean(), Mockito.anyString());
Mockito.verify(databaseModel, Mockito.never()).cancelAllPasswordResetTokens(Mockito.anyInt());
}
@Test
public void testLogInWithUserName() {
Mockito.when(databaseModel.getUserByName("john")).thenReturn(storedUser);
ResultCode result = userManager.logIn("john", "password", inetAddress);
Assert.assertEquals(ResultCode.OK, result);
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
Mockito.verify(sessionModel).setCurrentUser(userCaptor.capture());
Assert.assertSame(storedUser, userCaptor.getValue());
ArgumentCaptor<String> ipCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(databaseModel).makeLogInRecord(Mockito.eq(1), Mockito.eq(true), ipCaptor.capture());
Assert.assertSame(inetAddress, ipCaptor.getValue());
Mockito.verify(databaseModel).cancelAllPasswordResetTokens(1);
}
@Test
public void testLoginOrRegisterWithSocialAccount_existingUser() {
| SocialAccountDetails details = new SocialAccountDetails("FB", "usr1", "User 1", "usr1@test.com");
|
Jardo-51/user_module | core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
| public void testResetPasswordTokenExpired() {
long now = new Date().getTime();
PasswordResetToken token = new PasswordResetToken(1, "a4d21f702e44af5d0ce7228dae878672", new Date(now - ONE_DAY));
Mockito.when(databaseModel.getNewestPasswordResetToken("john@example.com")).thenReturn(token);
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
Mockito.when(databaseModel.setUserPassword(Mockito.eq(1), Mockito.notNull(UserPassword.class))).thenReturn(true);
ResultCode result = userManager.resetPassword("john@example.com", token.getKey(), "new_password");
Assert.assertEquals(ResultCode.NO_VALID_PASSWORD_RESET_TOKEN, result);
Mockito.verify(databaseModel, Mockito.never()).setUserPassword(Mockito.eq(1), Mockito.any(UserPassword.class));
}
@Test
public void testResetPasswordWrongTokenKey() {
PasswordResetToken token = new PasswordResetToken(1, "a4d21f702e44af5d0ce7228dae878672", new Date());
Mockito.when(databaseModel.getNewestPasswordResetToken("john@example.com")).thenReturn(token);
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
Mockito.when(databaseModel.setUserPassword(Mockito.eq(1), Mockito.notNull(UserPassword.class))).thenReturn(true);
ResultCode result = userManager.resetPassword("john@example.com", "4ea15b4ed08e48a6d766e976a4387fd2", "new_password");
Assert.assertEquals(ResultCode.NO_VALID_PASSWORD_RESET_TOKEN, result);
Mockito.verify(databaseModel, Mockito.never()).setUserPassword(Mockito.eq(1), Mockito.any(UserPassword.class));
}
@Test
public void testSendTestingEmail() {
Mockito.when(emailSender.sendLostPasswordEmail(Mockito.eq("john@example.com"), Mockito.notNull(String.class))).thenReturn(true);
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
// Path: core/src/test/java/com/jardoapps/usermodule/UserManagerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
public void testResetPasswordTokenExpired() {
long now = new Date().getTime();
PasswordResetToken token = new PasswordResetToken(1, "a4d21f702e44af5d0ce7228dae878672", new Date(now - ONE_DAY));
Mockito.when(databaseModel.getNewestPasswordResetToken("john@example.com")).thenReturn(token);
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
Mockito.when(databaseModel.setUserPassword(Mockito.eq(1), Mockito.notNull(UserPassword.class))).thenReturn(true);
ResultCode result = userManager.resetPassword("john@example.com", token.getKey(), "new_password");
Assert.assertEquals(ResultCode.NO_VALID_PASSWORD_RESET_TOKEN, result);
Mockito.verify(databaseModel, Mockito.never()).setUserPassword(Mockito.eq(1), Mockito.any(UserPassword.class));
}
@Test
public void testResetPasswordWrongTokenKey() {
PasswordResetToken token = new PasswordResetToken(1, "a4d21f702e44af5d0ce7228dae878672", new Date());
Mockito.when(databaseModel.getNewestPasswordResetToken("john@example.com")).thenReturn(token);
Mockito.when(databaseModel.getUserIdByEmail("john@example.com")).thenReturn(1);
Mockito.when(databaseModel.setUserPassword(Mockito.eq(1), Mockito.notNull(UserPassword.class))).thenReturn(true);
ResultCode result = userManager.resetPassword("john@example.com", "4ea15b4ed08e48a6d766e976a4387fd2", "new_password");
Assert.assertEquals(ResultCode.NO_VALID_PASSWORD_RESET_TOKEN, result);
Mockito.verify(databaseModel, Mockito.never()).setUserPassword(Mockito.eq(1), Mockito.any(UserPassword.class));
}
@Test
public void testSendTestingEmail() {
Mockito.when(emailSender.sendLostPasswordEmail(Mockito.eq("john@example.com"), Mockito.notNull(String.class))).thenReturn(true);
| boolean result = userManager.sendTestingEmail(EmailType.LOST_PASSWORD, "john@example.com");
|
Jardo-51/user_module | jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/UserEntity.java | // Path: core/src/main/java/com/jardoapps/usermodule/User.java
// public class User {
//
// private final int id;
//
// private final String name;
//
// private final String email;
//
// private final String registrationControlCode;
//
// private final boolean registrationConfirmed;
//
// private final UserPassword password;
//
// private int rank;
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getRegistrationControlCode() {
// return registrationControlCode;
// }
//
// public boolean isRegistrationConfirmed() {
// return registrationConfirmed;
// }
//
// public UserPassword getPassword() {
// return password;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public User withId(int newId) {
// return new User(newId, name, email, registrationControlCode, registrationConfirmed, password, rank);
// }
//
// public User(int id, String name, String email, String registrationControlCode, boolean registrationConfirmed, UserPassword password, int rank) {
// this.id = id;
// this.name = name;
// this.email = email;
// this.registrationControlCode = registrationControlCode;
// this.registrationConfirmed = registrationConfirmed;
// this.password = password;
// this.rank = rank;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
| import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.jardoapps.usermodule.User;
import com.jardoapps.usermodule.containers.UserPassword;
| /*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule.jpa.entities;
/**
* An entity class for representing registered users.
* <p>
* This class is a part of this library's public API.
*
* @author Jaroslav Brtiš
*
*/
@Entity
@Table(name = "um_user")
public class UserEntity {
@Id
@Column(name = "id")
@SequenceGenerator(name = "um_user_id_seq", sequenceName = "um_user_id_seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_user_id_seq")
private int id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "reg_date")
private Date registrationDate;
@Column(name = "reg_control_code")
private String registrationControlCode;
@Column(name = "confirmed")
private boolean registrationConfirmed;
@Column(name = "deleted")
private boolean deleted;
@Column(name = "rank")
private int rank;
@Column(name = "password")
private String passwordHash;
@Column(name = "salt")
private String passwordSalt;
public UserEntity() {
super();
}
| // Path: core/src/main/java/com/jardoapps/usermodule/User.java
// public class User {
//
// private final int id;
//
// private final String name;
//
// private final String email;
//
// private final String registrationControlCode;
//
// private final boolean registrationConfirmed;
//
// private final UserPassword password;
//
// private int rank;
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getRegistrationControlCode() {
// return registrationControlCode;
// }
//
// public boolean isRegistrationConfirmed() {
// return registrationConfirmed;
// }
//
// public UserPassword getPassword() {
// return password;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public User withId(int newId) {
// return new User(newId, name, email, registrationControlCode, registrationConfirmed, password, rank);
// }
//
// public User(int id, String name, String email, String registrationControlCode, boolean registrationConfirmed, UserPassword password, int rank) {
// this.id = id;
// this.name = name;
// this.email = email;
// this.registrationControlCode = registrationControlCode;
// this.registrationConfirmed = registrationConfirmed;
// this.password = password;
// this.rank = rank;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
// Path: jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/UserEntity.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.jardoapps.usermodule.User;
import com.jardoapps.usermodule.containers.UserPassword;
/*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule.jpa.entities;
/**
* An entity class for representing registered users.
* <p>
* This class is a part of this library's public API.
*
* @author Jaroslav Brtiš
*
*/
@Entity
@Table(name = "um_user")
public class UserEntity {
@Id
@Column(name = "id")
@SequenceGenerator(name = "um_user_id_seq", sequenceName = "um_user_id_seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_user_id_seq")
private int id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "reg_date")
private Date registrationDate;
@Column(name = "reg_control_code")
private String registrationControlCode;
@Column(name = "confirmed")
private boolean registrationConfirmed;
@Column(name = "deleted")
private boolean deleted;
@Column(name = "rank")
private int rank;
@Column(name = "password")
private String passwordHash;
@Column(name = "salt")
private String passwordSalt;
public UserEntity() {
super();
}
| public void copyUser(User user) {
|
Jardo-51/user_module | jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/UserEntity.java | // Path: core/src/main/java/com/jardoapps/usermodule/User.java
// public class User {
//
// private final int id;
//
// private final String name;
//
// private final String email;
//
// private final String registrationControlCode;
//
// private final boolean registrationConfirmed;
//
// private final UserPassword password;
//
// private int rank;
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getRegistrationControlCode() {
// return registrationControlCode;
// }
//
// public boolean isRegistrationConfirmed() {
// return registrationConfirmed;
// }
//
// public UserPassword getPassword() {
// return password;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public User withId(int newId) {
// return new User(newId, name, email, registrationControlCode, registrationConfirmed, password, rank);
// }
//
// public User(int id, String name, String email, String registrationControlCode, boolean registrationConfirmed, UserPassword password, int rank) {
// this.id = id;
// this.name = name;
// this.email = email;
// this.registrationControlCode = registrationControlCode;
// this.registrationConfirmed = registrationConfirmed;
// this.password = password;
// this.rank = rank;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
| import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.jardoapps.usermodule.User;
import com.jardoapps.usermodule.containers.UserPassword;
| @Column(name = "reg_control_code")
private String registrationControlCode;
@Column(name = "confirmed")
private boolean registrationConfirmed;
@Column(name = "deleted")
private boolean deleted;
@Column(name = "rank")
private int rank;
@Column(name = "password")
private String passwordHash;
@Column(name = "salt")
private String passwordSalt;
public UserEntity() {
super();
}
public void copyUser(User user) {
id = user.getId();
name = user.getName();
email = user.getEmail();
registrationControlCode = user.getRegistrationControlCode();
registrationConfirmed = user.isRegistrationConfirmed();
rank = user.getRank();
| // Path: core/src/main/java/com/jardoapps/usermodule/User.java
// public class User {
//
// private final int id;
//
// private final String name;
//
// private final String email;
//
// private final String registrationControlCode;
//
// private final boolean registrationConfirmed;
//
// private final UserPassword password;
//
// private int rank;
//
// public int getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public String getRegistrationControlCode() {
// return registrationControlCode;
// }
//
// public boolean isRegistrationConfirmed() {
// return registrationConfirmed;
// }
//
// public UserPassword getPassword() {
// return password;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public User withId(int newId) {
// return new User(newId, name, email, registrationControlCode, registrationConfirmed, password, rank);
// }
//
// public User(int id, String name, String email, String registrationControlCode, boolean registrationConfirmed, UserPassword password, int rank) {
// this.id = id;
// this.name = name;
// this.email = email;
// this.registrationControlCode = registrationControlCode;
// this.registrationConfirmed = registrationConfirmed;
// this.password = password;
// this.rank = rank;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
// Path: jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/UserEntity.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.jardoapps.usermodule.User;
import com.jardoapps.usermodule.containers.UserPassword;
@Column(name = "reg_control_code")
private String registrationControlCode;
@Column(name = "confirmed")
private boolean registrationConfirmed;
@Column(name = "deleted")
private boolean deleted;
@Column(name = "rank")
private int rank;
@Column(name = "password")
private String passwordHash;
@Column(name = "salt")
private String passwordSalt;
public UserEntity() {
super();
}
public void copyUser(User user) {
id = user.getId();
name = user.getName();
email = user.getEmail();
registrationControlCode = user.getRegistrationControlCode();
registrationConfirmed = user.isRegistrationConfirmed();
rank = user.getRank();
| UserPassword password = user.getPassword();
|
Jardo-51/user_module | core/src/main/java/com/jardoapps/usermodule/UserManager.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
| import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
| if (user == null) {
return ResultCode.NO_SUCH_USER;
}
if (user.isRegistrationConfirmed()) {
return ResultCode.REGISTRATION_ALREADY_CONFIRMED;
}
if (!user.getRegistrationControlCode().equalsIgnoreCase(registrationControlCode)) {
return ResultCode.INVALID_REGISTRATION_CONTROL_CODE;
}
return ResultCode.OK;
}
private ResultCode checkRegistrationPreconditions(String userEmail, String userName) {
if (userName != null) {
if (databaseModel.isUserNameRegistered(userName)) {
return ResultCode.USER_NAME_ALREADY_REGISTERED;
}
}
if (databaseModel.isEmailRegistered(userEmail)) {
return ResultCode.EMAIL_ALREADY_REGISTERED;
}
return ResultCode.OK;
}
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
// Path: core/src/main/java/com/jardoapps/usermodule/UserManager.java
import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
if (user == null) {
return ResultCode.NO_SUCH_USER;
}
if (user.isRegistrationConfirmed()) {
return ResultCode.REGISTRATION_ALREADY_CONFIRMED;
}
if (!user.getRegistrationControlCode().equalsIgnoreCase(registrationControlCode)) {
return ResultCode.INVALID_REGISTRATION_CONTROL_CODE;
}
return ResultCode.OK;
}
private ResultCode checkRegistrationPreconditions(String userEmail, String userName) {
if (userName != null) {
if (databaseModel.isUserNameRegistered(userName)) {
return ResultCode.USER_NAME_ALREADY_REGISTERED;
}
}
if (databaseModel.isEmailRegistered(userEmail)) {
return ResultCode.EMAIL_ALREADY_REGISTERED;
}
return ResultCode.OK;
}
| private UserPassword createUserPassword(String password) {
|
Jardo-51/user_module | core/src/main/java/com/jardoapps/usermodule/UserManager.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
| import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
|
if (!user.getRegistrationControlCode().equalsIgnoreCase(registrationControlCode)) {
return ResultCode.INVALID_REGISTRATION_CONTROL_CODE;
}
return ResultCode.OK;
}
private ResultCode checkRegistrationPreconditions(String userEmail, String userName) {
if (userName != null) {
if (databaseModel.isUserNameRegistered(userName)) {
return ResultCode.USER_NAME_ALREADY_REGISTERED;
}
}
if (databaseModel.isEmailRegistered(userEmail)) {
return ResultCode.EMAIL_ALREADY_REGISTERED;
}
return ResultCode.OK;
}
private UserPassword createUserPassword(String password) {
String salt = generatePasswordSalt();
String hash = calculatePasswordHash(password, salt);
return new UserPassword(hash, salt);
}
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
// Path: core/src/main/java/com/jardoapps/usermodule/UserManager.java
import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
if (!user.getRegistrationControlCode().equalsIgnoreCase(registrationControlCode)) {
return ResultCode.INVALID_REGISTRATION_CONTROL_CODE;
}
return ResultCode.OK;
}
private ResultCode checkRegistrationPreconditions(String userEmail, String userName) {
if (userName != null) {
if (databaseModel.isUserNameRegistered(userName)) {
return ResultCode.USER_NAME_ALREADY_REGISTERED;
}
}
if (databaseModel.isEmailRegistered(userEmail)) {
return ResultCode.EMAIL_ALREADY_REGISTERED;
}
return ResultCode.OK;
}
private UserPassword createUserPassword(String password) {
String salt = generatePasswordSalt();
String hash = calculatePasswordHash(password, salt);
return new UserPassword(hash, salt);
}
| private User createUserWithSocialAccount(SocialAccountDetails details) {
|
Jardo-51/user_module | core/src/main/java/com/jardoapps/usermodule/UserManager.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
| import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
| int userId = databaseModel.getUserIdByEmail(userEmail);
if (userId < 0) {
return ResultCode.NO_SUCH_USER;
}
UserPassword userPassword = createUserPassword(newPassword);
if (!databaseModel.setUserPassword(userId, userPassword)) {
LOGGER.error("DB error: Failed to set password for user with id={}", userId);
return ResultCode.DATABASE_ERROR;
}
if (!databaseModel.cancelAllPasswordResetTokens(userId)) {
LOGGER.warn("DB error: Failed to cancel password reset tokens for user with id={}", userId);
}
return ResultCode.OK;
}
/**
* Sends a testing email of specified type (registration/lost password)
* containing fake data. It is intended to be called by web masters to
* test/debug email sending functionality.
*
* @param emailType
* type of email to send (registration, lost password, ...)
* @param address
* email address to which the email will be sent
* @return True on success, otherwise false.
*/
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/SocialAccountDetails.java
// public class SocialAccountDetails {
//
// private final String accountType;
//
// private final String userId;
//
// private final String userName;
//
// private final String email;
//
// public SocialAccountDetails(String accountType, String userId, String userName, String email) {
// this.accountType = accountType;
// this.userId = userId;
// this.userName = userName;
// this.email = email;
// }
//
// public String getAccountType() {
// return accountType;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public String getEmail() {
// return email;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/defines/EmailType.java
// public enum EmailType {
// LOST_PASSWORD,
// MANUAL_REGISTRATION,
// REGISTRATION
// }
//
// Path: core/src/main/java/com/jardoapps/usermodule/utils/EmailUtils.java
// public final class EmailUtils {
//
// /**
// * Regex for checking email validity. It is designed primarily to determine
// * if an email address is suitable for user registration and therefore is
// * more strict than the RFC 822 specification. For instance address
// * <code>user@localhost</code> is considered valid by RFC 822, but is
// * <b>not</b> considered suitable for user registration.
// */
// public static final String EMAIL_REGEX = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
//
// /**
// * Check whether the given email matches the {@link #EMAIL_REGEX}. Note that
// * this method is <b>not</b> compliant with RFC 822. See documentation of
// * EMAIL_REGEX for more information. Top level domain validity is not
// * checked.
// *
// * @param email
// * email address to check
// * @return true if the given email is considered valid, otherwise false
// */
// public static boolean isEmailValid(String email) {
// if (email == null) {
// return false;
// }
// return email.matches(EMAIL_REGEX);
// }
//
// private EmailUtils() {
//
// }
//
// }
// Path: core/src/main/java/com/jardoapps/usermodule/UserManager.java
import org.slf4j.LoggerFactory;
import com.jardoapps.usermodule.containers.PasswordResetToken;
import com.jardoapps.usermodule.containers.SocialAccountDetails;
import com.jardoapps.usermodule.containers.UserPassword;
import com.jardoapps.usermodule.defines.EmailType;
import com.jardoapps.usermodule.utils.EmailUtils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.inject.Inject;
import org.slf4j.Logger;
int userId = databaseModel.getUserIdByEmail(userEmail);
if (userId < 0) {
return ResultCode.NO_SUCH_USER;
}
UserPassword userPassword = createUserPassword(newPassword);
if (!databaseModel.setUserPassword(userId, userPassword)) {
LOGGER.error("DB error: Failed to set password for user with id={}", userId);
return ResultCode.DATABASE_ERROR;
}
if (!databaseModel.cancelAllPasswordResetTokens(userId)) {
LOGGER.warn("DB error: Failed to cancel password reset tokens for user with id={}", userId);
}
return ResultCode.OK;
}
/**
* Sends a testing email of specified type (registration/lost password)
* containing fake data. It is intended to be called by web masters to
* test/debug email sending functionality.
*
* @param emailType
* type of email to send (registration, lost password, ...)
* @param address
* email address to which the email will be sent
* @return True on success, otherwise false.
*/
| public boolean sendTestingEmail(EmailType emailType, String address) {
|
Jardo-51/user_module | core/src/main/java/com/jardoapps/usermodule/User.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
| import com.jardoapps.usermodule.containers.UserPassword;
| /*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule;
/**
* Class representing a registered user.
*
* @author Jaroslav Brtiš
*
*/
public class User {
private final int id;
private final String name;
private final String email;
private final String registrationControlCode;
private final boolean registrationConfirmed;
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/UserPassword.java
// public class UserPassword {
//
// private final String hash;
// private final String salt;
//
// public String getHash() {
// return hash;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public UserPassword(String hash, String salt) {
// this.hash = hash;
// this.salt = salt;
// }
//
// }
// Path: core/src/main/java/com/jardoapps/usermodule/User.java
import com.jardoapps.usermodule.containers.UserPassword;
/*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule;
/**
* Class representing a registered user.
*
* @author Jaroslav Brtiš
*
*/
public class User {
private final int id;
private final String name;
private final String email;
private final String registrationControlCode;
private final boolean registrationConfirmed;
| private final UserPassword password;
|
Jardo-51/user_module | jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/PasswordResetTokenEntity.java | // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
| import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jardoapps.usermodule.containers.PasswordResetToken;
| /*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule.jpa.entities;
/**
* An entity class for representing password reset tokens.
* <p>
* This class is a part of this library's public API.
*
* @author Jaroslav Brtiš
*
*/
@Entity
@Table(name = "um_password_reset_token")
public class PasswordResetTokenEntity {
@Id
@GeneratedValue
long id;
@ManyToOne
@JoinColumn(name = "user_id")
UserEntity user;
@Column(name = "date_time")
Date time;
@Column(name = "token_key")
String key;
@Column(name = "valid")
boolean valid;
public PasswordResetTokenEntity() {
super();
}
| // Path: core/src/main/java/com/jardoapps/usermodule/containers/PasswordResetToken.java
// public class PasswordResetToken {
//
// private final int userId;
// private final Date creationTime;
// private final String key;
//
// public Date getCreationTime() {
// return creationTime;
// }
//
// public String getKey() {
// return key;
// }
//
// public int getUserId() {
// return userId;
// }
//
// public PasswordResetToken(int userId, String key, Date creationTime) {
// this.userId = userId;
// this.creationTime = creationTime;
// this.key = key;
// }
// }
// Path: jpa/src/main/java/com/jardoapps/usermodule/jpa/entities/PasswordResetTokenEntity.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jardoapps.usermodule.containers.PasswordResetToken;
/*
* This file is part of the User Module library.
* Copyright (C) 2014 Jaroslav Brtiš
*
* User Module library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* User Module library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with User Module library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jardoapps.usermodule.jpa.entities;
/**
* An entity class for representing password reset tokens.
* <p>
* This class is a part of this library's public API.
*
* @author Jaroslav Brtiš
*
*/
@Entity
@Table(name = "um_password_reset_token")
public class PasswordResetTokenEntity {
@Id
@GeneratedValue
long id;
@ManyToOne
@JoinColumn(name = "user_id")
UserEntity user;
@Column(name = "date_time")
Date time;
@Column(name = "token_key")
String key;
@Column(name = "valid")
boolean valid;
public PasswordResetTokenEntity() {
super();
}
| public PasswordResetTokenEntity(PasswordResetToken passwordResetToken) {
|
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/methods/ReadInnerMethod.java | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelConstructorMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class ParcelConstructorMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new ParcelConstructorMethodVisitor instance.
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public ParcelConstructorMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getReadFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == PUTFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.keySet().contains(method.getName())) {
// queueManager.getReadMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new ReadInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
| import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.ParcelConstructorMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a ParcelConstructorMethodVisitor "
+ "instead of using a boolean")
public class ReadInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new ReadInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public ReadInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context, | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelConstructorMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class ParcelConstructorMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new ParcelConstructorMethodVisitor instance.
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public ParcelConstructorMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getReadFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == PUTFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.keySet().contains(method.getName())) {
// queueManager.getReadMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new ReadInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/methods/ReadInnerMethod.java
import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.ParcelConstructorMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a ParcelConstructorMethodVisitor "
+ "instead of using a boolean")
public class ReadInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new ReadInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public ReadInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context, | @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) { |
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/methods/ReadInnerMethod.java | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelConstructorMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class ParcelConstructorMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new ParcelConstructorMethodVisitor instance.
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public ParcelConstructorMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getReadFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == PUTFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.keySet().contains(method.getName())) {
// queueManager.getReadMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new ReadInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
| import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.ParcelConstructorMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a ParcelConstructorMethodVisitor "
+ "instead of using a boolean")
public class ReadInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new ReadInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public ReadInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context,
@Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
super(methodName); | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelConstructorMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class ParcelConstructorMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new ParcelConstructorMethodVisitor instance.
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public ParcelConstructorMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getReadFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == PUTFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.keySet().contains(method.getName())) {
// queueManager.getReadMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new ReadInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/methods/ReadInnerMethod.java
import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.ParcelConstructorMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a ParcelConstructorMethodVisitor "
+ "instead of using a boolean")
public class ReadInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new ReadInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public ReadInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context,
@Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
super(methodName); | methodVisitor = new ParcelConstructorMethodVisitor(api, classNode, |
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelClassVisitor.java | // Path: src/main/java/com/monits/linters/bc/parcelable/methods/AbstractInnerMethod.java
// public abstract class AbstractInnerMethod {
// private final String methodName;
//
// /**
// * Creates a new AbstractInnerMethod instance
// *
// * @param methodName The method's name.
// */
// public AbstractInnerMethod(@Nonnull final String methodName) {
// this.methodName = methodName;
// }
//
// @Override
// public String toString() {
// return "AbstractInnerMethod [ methodName=" + methodName + " ]";
// }
//
// @Nonnull
// public String getMethodName() {
// return methodName;
// }
//
// /**
// * Returns this class {@link MethodVisitor}. Subclasses MUST implement
// * this method.
// * @return methodVisitor encapsulated in the subclass.
// */
// @Nonnull
// public abstract MethodVisitor getMethodVisitor();
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
| import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.methods.AbstractInnerMethod;
import com.monits.linters.bc.parcelable.models.QueueManager; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.visitors;
public class ParcelClassVisitor extends ClassVisitor {
private static final String PARCEL_CONSTRUCTOR_DESC = "(Landroid/os/Parcel;)V";
private static final String WRITE_TO_PARCEL_DESC = "(Landroid/os/Parcel;I)V";
private static final String WRITE_TO_PARCEL_METHOD = "writeToParcel";
private static final String CONSTRUCTOR = "<init>"; | // Path: src/main/java/com/monits/linters/bc/parcelable/methods/AbstractInnerMethod.java
// public abstract class AbstractInnerMethod {
// private final String methodName;
//
// /**
// * Creates a new AbstractInnerMethod instance
// *
// * @param methodName The method's name.
// */
// public AbstractInnerMethod(@Nonnull final String methodName) {
// this.methodName = methodName;
// }
//
// @Override
// public String toString() {
// return "AbstractInnerMethod [ methodName=" + methodName + " ]";
// }
//
// @Nonnull
// public String getMethodName() {
// return methodName;
// }
//
// /**
// * Returns this class {@link MethodVisitor}. Subclasses MUST implement
// * this method.
// * @return methodVisitor encapsulated in the subclass.
// */
// @Nonnull
// public abstract MethodVisitor getMethodVisitor();
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelClassVisitor.java
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.methods.AbstractInnerMethod;
import com.monits.linters.bc.parcelable.models.QueueManager;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.visitors;
public class ParcelClassVisitor extends ClassVisitor {
private static final String PARCEL_CONSTRUCTOR_DESC = "(Landroid/os/Parcel;)V";
private static final String WRITE_TO_PARCEL_DESC = "(Landroid/os/Parcel;I)V";
private static final String WRITE_TO_PARCEL_METHOD = "writeToParcel";
private static final String CONSTRUCTOR = "<init>"; | private final AbstractInnerMethod innerMethod; |
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelClassVisitor.java | // Path: src/main/java/com/monits/linters/bc/parcelable/methods/AbstractInnerMethod.java
// public abstract class AbstractInnerMethod {
// private final String methodName;
//
// /**
// * Creates a new AbstractInnerMethod instance
// *
// * @param methodName The method's name.
// */
// public AbstractInnerMethod(@Nonnull final String methodName) {
// this.methodName = methodName;
// }
//
// @Override
// public String toString() {
// return "AbstractInnerMethod [ methodName=" + methodName + " ]";
// }
//
// @Nonnull
// public String getMethodName() {
// return methodName;
// }
//
// /**
// * Returns this class {@link MethodVisitor}. Subclasses MUST implement
// * this method.
// * @return methodVisitor encapsulated in the subclass.
// */
// @Nonnull
// public abstract MethodVisitor getMethodVisitor();
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
| import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.methods.AbstractInnerMethod;
import com.monits.linters.bc.parcelable.models.QueueManager; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.visitors;
public class ParcelClassVisitor extends ClassVisitor {
private static final String PARCEL_CONSTRUCTOR_DESC = "(Landroid/os/Parcel;)V";
private static final String WRITE_TO_PARCEL_DESC = "(Landroid/os/Parcel;I)V";
private static final String WRITE_TO_PARCEL_METHOD = "writeToParcel";
private static final String CONSTRUCTOR = "<init>";
private final AbstractInnerMethod innerMethod;
private final ClassNode classNode;
private final ClassContext context;
private final ClassReader cr; | // Path: src/main/java/com/monits/linters/bc/parcelable/methods/AbstractInnerMethod.java
// public abstract class AbstractInnerMethod {
// private final String methodName;
//
// /**
// * Creates a new AbstractInnerMethod instance
// *
// * @param methodName The method's name.
// */
// public AbstractInnerMethod(@Nonnull final String methodName) {
// this.methodName = methodName;
// }
//
// @Override
// public String toString() {
// return "AbstractInnerMethod [ methodName=" + methodName + " ]";
// }
//
// @Nonnull
// public String getMethodName() {
// return methodName;
// }
//
// /**
// * Returns this class {@link MethodVisitor}. Subclasses MUST implement
// * this method.
// * @return methodVisitor encapsulated in the subclass.
// */
// @Nonnull
// public abstract MethodVisitor getMethodVisitor();
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/ParcelClassVisitor.java
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.methods.AbstractInnerMethod;
import com.monits.linters.bc.parcelable.models.QueueManager;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.visitors;
public class ParcelClassVisitor extends ClassVisitor {
private static final String PARCEL_CONSTRUCTOR_DESC = "(Landroid/os/Parcel;)V";
private static final String WRITE_TO_PARCEL_DESC = "(Landroid/os/Parcel;I)V";
private static final String WRITE_TO_PARCEL_METHOD = "writeToParcel";
private static final String CONSTRUCTOR = "<init>";
private final AbstractInnerMethod innerMethod;
private final ClassNode classNode;
private final ClassContext context;
private final ClassReader cr; | private final QueueManager queueManager; |
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/methods/WriteInnerMethod.java | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/WriteToParcelMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class WriteToParcelMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new WriteToParcelMethodVisitor instance
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public WriteToParcelMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getWriteFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == GETFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.values().contains(method.getName())) {
// queueManager.getWriteMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new WriteInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
| import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.WriteToParcelMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a WriteToParcelMethodVisitor "
+ "instead of using a boolean")
public class WriteInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new WriteInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public WriteInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context, | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/WriteToParcelMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class WriteToParcelMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new WriteToParcelMethodVisitor instance
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public WriteToParcelMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getWriteFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == GETFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.values().contains(method.getName())) {
// queueManager.getWriteMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new WriteInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/methods/WriteInnerMethod.java
import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.WriteToParcelMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a WriteToParcelMethodVisitor "
+ "instead of using a boolean")
public class WriteInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new WriteInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public WriteInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context, | @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) { |
Monits/android-linters | src/main/java/com/monits/linters/bc/parcelable/methods/WriteInnerMethod.java | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/WriteToParcelMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class WriteToParcelMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new WriteToParcelMethodVisitor instance
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public WriteToParcelMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getWriteFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == GETFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.values().contains(method.getName())) {
// queueManager.getWriteMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new WriteInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
| import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.WriteToParcelMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | /**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a WriteToParcelMethodVisitor "
+ "instead of using a boolean")
public class WriteInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new WriteInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public WriteInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context,
@Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
super(methodName); | // Path: src/main/java/com/monits/linters/bc/parcelable/models/QueueManager.java
// public class QueueManager {
// private final Queue<ParcelableField> writeFieldQueue;
// private final Queue<ParcelableField> readFieldQueue;
// private final Queue<Method> readMethodQueue;
// private final Queue<Method> writeMethodQueue;
//
// /**
// * Creates a new QueueManager instance.
// *
// * @param writeFieldQueue Field writing queue
// * @param readFieldQueue Field reading queue
// * @param writeMethodQueue Method writing queue
// * @param readMethodQueue Method reading queue
// */
//
// public QueueManager(@Nonnull final Queue<ParcelableField> writeFieldQueue,
// @Nonnull final Queue<ParcelableField> readFieldQueue,
// @Nonnull final Queue<Method> writeMethodQueue,
// @Nonnull final Queue<Method> readMethodQueue) {
// this.writeFieldQueue = writeFieldQueue;
// this.readFieldQueue = readFieldQueue;
// this.writeMethodQueue = writeMethodQueue;
// this.readMethodQueue = readMethodQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getWriteFieldQueue() {
// return writeFieldQueue;
// }
//
// @Nonnull
// public Queue<ParcelableField> getReadFieldQueue() {
// return readFieldQueue;
// }
//
// @Nonnull
// public Queue<Method> getReadMethodQueue() {
// return readMethodQueue;
// }
//
// @Nonnull
// public Queue<Method> getWriteMethodQueue() {
// return writeMethodQueue;
// }
// }
//
// Path: src/main/java/com/monits/linters/bc/parcelable/visitors/WriteToParcelMethodVisitor.java
// @SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
// justification = "Solved in super class")
// public class WriteToParcelMethodVisitor extends AbstractMethodVisitor {
//
// /**
// * Creates a new WriteToParcelMethodVisitor instance
// * See {@link AbstractMethodVisitor} for more information.
// *
// * @param api The api for {@link MethodVisitor}
// * @param classNode The class node that represents analyzed object's class
// * @param method The method's name
// * @param desc The desc used to call super
// * @param context The class context
// * @param cr The class reader that parses the class
// * @param queueManager The queue manager for methods invocation
// */
//
// public WriteToParcelMethodVisitor(final int api,
// @Nonnull final ClassNode classNode, @Nonnull final String method,
// @Nonnull final String desc, @Nonnull final ClassContext context,
// @Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
// super(api, classNode, method, desc, context, cr, queueManager);
// }
//
//
// @Override
// public void addFieldToQueue(@Nonnull final ParcelableField field) {
// queueManager.getWriteFieldQueue().offer(field);
// }
//
// @Override
// public boolean opcodeNeedsToBeHandled(final int opcode) {
// return opcode == GETFIELD;
// }
//
// @Override
// public void addMethodToQueue(@Nonnull final Method method) {
// final Multimap<String, String> parcelableMethods = ParcelMethodManager.INSTANCE
// .getParcelableMethods();
// if (parcelableMethods.values().contains(method.getName())) {
// queueManager.getWriteMethodQueue().add(method);
// }
// }
//
// @Override
// public AbstractInnerMethod createInnerMethod(@Nonnull final String methodName,
// @Nonnull final String desc) {
// return new WriteInnerMethod(api, classNode, methodName,
// desc, context, cr, queueManager);
// }
// }
// Path: src/main/java/com/monits/linters/bc/parcelable/methods/WriteInnerMethod.java
import javax.annotation.Nonnull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import com.android.tools.lint.detector.api.ClassContext;
import com.monits.linters.bc.parcelable.models.QueueManager;
import com.monits.linters.bc.parcelable.visitors.WriteToParcelMethodVisitor;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Copyright 2010 - 2016 - Monits
*
* 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.monits.linters.bc.parcelable.methods;
@SuppressFBWarnings(value = "CD_CIRCULAR_DEPENDENCY",
justification = "This class must create a WriteToParcelMethodVisitor "
+ "instead of using a boolean")
public class WriteInnerMethod extends AbstractInnerMethod {
private final MethodVisitor methodVisitor;
/**
* Creates a new WriteInnerMethod instance
*
* @param api The api for {@link #methodVisitor}
* @param classNode The class node for {@link #methodVisitor}
* @param methodName This class method name
* @param desc The desc for {@link #methodVisitor}
* @param context The context for {@link #methodVisitor}
* @param cr The class reader for {@link #methodVisitor}
* @param queueManager The queue manager for {@link #methodVisitor}
*/
public WriteInnerMethod(final int api,
@Nonnull final ClassNode classNode, @Nonnull final String methodName,
@Nonnull final String desc, @Nonnull final ClassContext context,
@Nonnull final ClassReader cr, @Nonnull final QueueManager queueManager) {
super(methodName); | methodVisitor = new WriteToParcelMethodVisitor(api, classNode, |
Laity000/ChatRoom-JavaFX | ChatClient/src/main/java/com/chatroom/communication/TextComm.java | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.client.Main;
import com.chatroom.messages.Message; | // Thread.sleep(1000);//线程暂停一秒
s = new Socket();
SocketAddress endpoint = new InetSocketAddress(hostName, port);
// 设置连接超时时间
s.connect(endpoint, 5 * 1000);
br = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
ps = new PrintStream(s.getOutputStream());
// 输出连接信息
if (s.isConnected()) {
logger.info("{} 本机已成功连接服务器!下一步用户登录..", s);
// System.out.println("Client connected!The next step is to
// determine whether the login is successful..");
}
// 连接指令
connect();
while (s.isConnected()) {
// 读取来自客户端的消息
String revString = br.readLine();
if (revString != null) {
logger.info("收到服务器消息..");
logger.debug("数据内容:{}", revString);
logger.info("对数据进行解析并做响应中..");
Message message = gson.fromJson(revString, Message.class);
// TODO:对服务器的消息进行解析
switch (message.getType()) {
case SUCCESS:
// 登录成功后进入ChatUI界面,需要username和pic,并且需要更新用户集(在USERLIST消息中处理)。
logger.info("[{}]用户登录成功!", userName);
// 切换到ChatUI界面 | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
// Path: ChatClient/src/main/java/com/chatroom/communication/TextComm.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.client.Main;
import com.chatroom.messages.Message;
// Thread.sleep(1000);//线程暂停一秒
s = new Socket();
SocketAddress endpoint = new InetSocketAddress(hostName, port);
// 设置连接超时时间
s.connect(endpoint, 5 * 1000);
br = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
ps = new PrintStream(s.getOutputStream());
// 输出连接信息
if (s.isConnected()) {
logger.info("{} 本机已成功连接服务器!下一步用户登录..", s);
// System.out.println("Client connected!The next step is to
// determine whether the login is successful..");
}
// 连接指令
connect();
while (s.isConnected()) {
// 读取来自客户端的消息
String revString = br.readLine();
if (revString != null) {
logger.info("收到服务器消息..");
logger.debug("数据内容:{}", revString);
logger.info("对数据进行解析并做响应中..");
Message message = gson.fromJson(revString, Message.class);
// TODO:对服务器的消息进行解析
switch (message.getType()) {
case SUCCESS:
// 登录成功后进入ChatUI界面,需要username和pic,并且需要更新用户集(在USERLIST消息中处理)。
logger.info("[{}]用户登录成功!", userName);
// 切换到ChatUI界面 | loginController.changeStage(Main.ChatUIID); |
Laity000/ChatRoom-JavaFX | ChatClient/src/main/java/com/chatroom/communication/WebsocketComm.java | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
| import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chatroom.client.Main;
import com.chatroom.messages.Message;
import com.google.gson.Gson; | package com.chatroom.communication;
/**
*
* @Title: WebsocketComm.java
* @Description: TODO 基于websocket协议的通信线程
* @author ZhangJing https://github.com/Laity000/ChatRoom-JavaFX
* @date 2017年6月15日 上午11:45:22
*
*/
public class WebsocketComm extends Comm implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(WebsocketComm.class);
// Java-WebSocket
private WebSocketClient wsc;
// url
private String url;
// Gson
private Gson gson = new Gson();
/**
* 构造函数
*
* @param hostName
* @param port
* @param userName
* @param userPic
*/
public WebsocketComm(String hostName, int port, String userName, String userPic) {
super(hostName, port, userName, userPic);
// TODO Auto-generated constructor stub
url = "ws://" + hostName + ":" + port;
}
@Override
/**
* 将message转化为字符串后发送 基于websocket协议
*/ | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
// Path: ChatClient/src/main/java/com/chatroom/communication/WebsocketComm.java
import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chatroom.client.Main;
import com.chatroom.messages.Message;
import com.google.gson.Gson;
package com.chatroom.communication;
/**
*
* @Title: WebsocketComm.java
* @Description: TODO 基于websocket协议的通信线程
* @author ZhangJing https://github.com/Laity000/ChatRoom-JavaFX
* @date 2017年6月15日 上午11:45:22
*
*/
public class WebsocketComm extends Comm implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(WebsocketComm.class);
// Java-WebSocket
private WebSocketClient wsc;
// url
private String url;
// Gson
private Gson gson = new Gson();
/**
* 构造函数
*
* @param hostName
* @param port
* @param userName
* @param userPic
*/
public WebsocketComm(String hostName, int port, String userName, String userPic) {
super(hostName, port, userName, userPic);
// TODO Auto-generated constructor stub
url = "ws://" + hostName + ":" + port;
}
@Override
/**
* 将message转化为字符串后发送 基于websocket协议
*/ | void send(Message message) { |
Laity000/ChatRoom-JavaFX | ChatClient/src/main/java/com/chatroom/communication/WebsocketComm.java | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
| import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chatroom.client.Main;
import com.chatroom.messages.Message;
import com.google.gson.Gson; | * 线程
*/
public void run() {
// TODO Auto-generated method stub
// websocket初始化
try {
wsc = new WebSocketClient(new URI(url)) {
@Override
public void onOpen(ServerHandshake handshake) {
// TODO Auto-generated method stub
logger.info("本机已成功连接{}服务器!下一步用户登录..", getURI());
}
@Override
public void onMessage(String revString) {
// TODO Auto-generated method stub
// 读取来自客户端的消息
if (revString != null) {
logger.info("收到服务器消息..");
logger.debug("数据内容:{}", revString);
logger.info("对数据进行解析并做响应中..");
Message message = gson.fromJson(revString, Message.class);
// TODO:对服务器的消息进行解析
switch (message.getType()) {
case SUCCESS:
// 登录成功后进入ChatUI界面,需要username和pic,并且需要更新用户集(在USERLIST消息中处理)。
logger.info("[{}]用户登录成功!", userName);
// 切换到ChatUI界面 | // Path: ChatClient/src/main/java/com/chatroom/client/Main.java
// public class Main extends Application {
//
// public final static String LoginUIID = "LoginUI";
// public final static String LoginUIRes = "fxml/LoginUI.fxml";
//
// public final static String ChatUIID = "ChatUI";
// public final static String ChatUIRes = "fxml/ChatUI.fxml";
//
// public final static String EmojiSelectorUIID = "EmojiSelectorUI";
// public final static String EmojiSelectorUIRes = "fxml/EmojiSelectorUI.fxml";
//
// private StageController stageController;
//
// @Override
// public void start(Stage primaryStage) {
// try {
// //新建一个StageController控制器
// stageController = new StageController();
//
// //将主舞台交给控制器处理
// stageController.addPrimaryStage(primaryStage);
//
// //加载两个舞台,每个界面一个舞台
// //stageController.loadStage(LoginUIID, LoginUIRes);
// //stageController.loadStage(ChatUIID, ChatUIRes);
// stageController.loadStage(LoginUIID, LoginUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(ChatUIID, ChatUIRes, false, StageStyle.UNDECORATED);
// stageController.loadStage(EmojiSelectorUIID, EmojiSelectorUIRes, true, StageStyle.UNDECORATED);
//
// //显示MainView舞台
// stageController.showStage(LoginUIID);
// } catch(Exception e) {
// e.printStackTrace();
// }
// }
//
// public static void main(String[] args) {
// launch(args);
// }
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
// Path: ChatClient/src/main/java/com/chatroom/communication/WebsocketComm.java
import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chatroom.client.Main;
import com.chatroom.messages.Message;
import com.google.gson.Gson;
* 线程
*/
public void run() {
// TODO Auto-generated method stub
// websocket初始化
try {
wsc = new WebSocketClient(new URI(url)) {
@Override
public void onOpen(ServerHandshake handshake) {
// TODO Auto-generated method stub
logger.info("本机已成功连接{}服务器!下一步用户登录..", getURI());
}
@Override
public void onMessage(String revString) {
// TODO Auto-generated method stub
// 读取来自客户端的消息
if (revString != null) {
logger.info("收到服务器消息..");
logger.debug("数据内容:{}", revString);
logger.info("对数据进行解析并做响应中..");
Message message = gson.fromJson(revString, Message.class);
// TODO:对服务器的消息进行解析
switch (message.getType()) {
case SUCCESS:
// 登录成功后进入ChatUI界面,需要username和pic,并且需要更新用户集(在USERLIST消息中处理)。
logger.info("[{}]用户登录成功!", userName);
// 切换到ChatUI界面 | loginController.changeStage(Main.ChatUIID); |
Laity000/ChatRoom-JavaFX | ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils; | package com.chatroom.chatserver;
/**
*
* @Title: Server.java
* @Description: TODO 后端服务器程序
* @author ZhangJing https://github.com/Laity000/ChatRoom-JavaFX
* @date 2017年5月17日 上午11:21:38
*
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
//服务端端口号
private static final int SERVER_PORT =12345;
//Gson
private static Gson gson = new Gson();
//用户名与客户端对象的映射
private static HashMap<String, Socket> socketsfromUserNames = new HashMap<>();
//用户信息集合
| // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
// Path: ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils;
package com.chatroom.chatserver;
/**
*
* @Title: Server.java
* @Description: TODO 后端服务器程序
* @author ZhangJing https://github.com/Laity000/ChatRoom-JavaFX
* @date 2017年5月17日 上午11:21:38
*
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
//服务端端口号
private static final int SERVER_PORT =12345;
//Gson
private static Gson gson = new Gson();
//用户名与客户端对象的映射
private static HashMap<String, Socket> socketsfromUserNames = new HashMap<>();
//用户信息集合
| private static LinkedList<UserInfo> userInfoList = new LinkedList<>(); |
Laity000/ChatRoom-JavaFX | ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils; | private InputStream in = null;
/**
*
* @param s
* @throws IOException
*/
public ServerThread(Socket s)throws IOException{
this.s = s;
// 初始化该Socket对应的输入流
br = new BufferedReader(new InputStreamReader(
s.getInputStream(), "utf-8"));
in = s.getInputStream();
}
public void run()
{
try
{
if(!s.isClosed()){
//System.out.println(s + "用户已连接服务器!下一步将判断是否能登录成功..");
logger.info("{} 端口已连接服务器!下一步将判断用户是否能登录成功..",s);
//socketList.add(s);
}
while (s.isConnected()) {
//读取来自客户端的消息
String revString = br.readLine();
if(revString != null){ | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
// Path: ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils;
private InputStream in = null;
/**
*
* @param s
* @throws IOException
*/
public ServerThread(Socket s)throws IOException{
this.s = s;
// 初始化该Socket对应的输入流
br = new BufferedReader(new InputStreamReader(
s.getInputStream(), "utf-8"));
in = s.getInputStream();
}
public void run()
{
try
{
if(!s.isClosed()){
//System.out.println(s + "用户已连接服务器!下一步将判断是否能登录成功..");
logger.info("{} 端口已连接服务器!下一步将判断用户是否能登录成功..",s);
//socketList.add(s);
}
while (s.isConnected()) {
//读取来自客户端的消息
String revString = br.readLine();
if(revString != null){ | Message message = gson.fromJson(revString, Message.class); |
Laity000/ChatRoom-JavaFX | ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils; | //发送消息,注意消息格式为(messageString + "\n")
ps.println(messagesString);
}
}
logger.info("数据发送完成!");
}
/**
* 检查是否登录成功,并发送登录结果
* 登陆成功后需要向所有用户发送新用户集列表和新用户上线通知
* @param message
* @throws IOException
*/
private void checkConnect(Message message) throws IOException{
String username = message.getFrom();
logger.info("用户[{}]登录分析中..", username);
//监测用户名是否已存在
if(!socketsfromUserNames.containsKey(username)){
socketsfromUserNames.put(username, s);
userInfoList.addAll(message.getUserlist());
/*
for(UserInfo user : message.getUserlist()){
userInfoList.add(user);
}
*/
logger.info("用户[{}]登录成功!", username);
//创建连接成功反馈信息
Message sResult = new Message(); | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
// Path: ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils;
//发送消息,注意消息格式为(messageString + "\n")
ps.println(messagesString);
}
}
logger.info("数据发送完成!");
}
/**
* 检查是否登录成功,并发送登录结果
* 登陆成功后需要向所有用户发送新用户集列表和新用户上线通知
* @param message
* @throws IOException
*/
private void checkConnect(Message message) throws IOException{
String username = message.getFrom();
logger.info("用户[{}]登录分析中..", username);
//监测用户名是否已存在
if(!socketsfromUserNames.containsKey(username)){
socketsfromUserNames.put(username, s);
userInfoList.addAll(message.getUserlist());
/*
for(UserInfo user : message.getUserlist()){
userInfoList.add(user);
}
*/
logger.info("用户[{}]登录成功!", username);
//创建连接成功反馈信息
Message sResult = new Message(); | sResult.setType(MessageType.SUCCESS); |
Laity000/ChatRoom-JavaFX | ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils; | //logger.info("用户集更新成功!");
}
/**
* 发送通知消息,用于通知全体用户或当前用户
* @param isAllUsers
* @param notice
* @throws IOException
*/
private void sendNotification(boolean isAllUsers, String notice) throws IOException {
Message message = new Message();
message.setType(MessageType.NOTIFICATION);
message.setContent(notice);
if(isAllUsers){
logger.info("向全体用户发送通知消息..");
sendAll(message, false);
}else {
logger.info("向当前用户发送通知消息..");
send(message, s);
}
}
/**
* 对收到的聊天消息进行转发,分为单播和广播两种方式处理
* @param message
* @throws IOException
*/
private void sendMSG(Message message) throws IOException{
String userName = message.getFrom();
String toUser = message.getTo(); | // Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Message.java
// public class Message {
// //消息类型
// private MessageType type;
// //用户集
// LinkedList<UserInfo> userlist;
// //消息来源
// private String from;
// //消息对象
// private String to;
// //消息内容
// private String content;
//
// public MessageType getType() {
// return type;
// }
// public void setType(MessageType type) {
// this.type = type;
// }
// public LinkedList<UserInfo> getUserlist() {
// return userlist;
// }
// public void setUserlist(LinkedList<UserInfo> userlist) {
// this.userlist = userlist;
// }
// public String getFrom() {
// return from;
// }
// public void setFrom(String from) {
// this.from = from;
// }
// public String getTo() {
// return to;
// }
// public void setTo(String to) {
// this.to = to;
// }
// public String getContent() {
// return content;
// }
// public void setContent(String content) {
// this.content = content;
// }
//
//
//
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/MessageType.java
// public enum MessageType {
// CONNECT,DISCONNECT,MSG,QUERY,SUCCESS,FAIL,USERLIST,NOTIFICATION
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/UserInfo.java
// public class UserInfo {
//
// public UserInfo() {
// super();
// }
//
// public UserInfo(String username, String userpic) {
// super();
// this.username = username;
// this.userpic = userpic;
// }
//
// //用户名
// private String username;
// //用户头像
// private String userpic;
//
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getUserpic() {
// return userpic;
// }
// public void setUserpic(String userpic) {
// this.userpic = userpic;
// }
//
// }
//
// Path: ChatServer-TXP/src/main/java/com/chatroom/messages/Utils.java
// public class Utils {
// public static final String ALL = "★☆";
// public static final String SUCCESS = "success";
// public static final String FAIL = "fail";
//
// }
// Path: ChatServer-TXP/src/main/java/com/chatroom/chatserver/Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.chatroom.messages.Message;
import com.chatroom.messages.MessageType;
import com.chatroom.messages.UserInfo;
import com.chatroom.messages.Utils;
//logger.info("用户集更新成功!");
}
/**
* 发送通知消息,用于通知全体用户或当前用户
* @param isAllUsers
* @param notice
* @throws IOException
*/
private void sendNotification(boolean isAllUsers, String notice) throws IOException {
Message message = new Message();
message.setType(MessageType.NOTIFICATION);
message.setContent(notice);
if(isAllUsers){
logger.info("向全体用户发送通知消息..");
sendAll(message, false);
}else {
logger.info("向当前用户发送通知消息..");
send(message, s);
}
}
/**
* 对收到的聊天消息进行转发,分为单播和广播两种方式处理
* @param message
* @throws IOException
*/
private void sendMSG(Message message) throws IOException{
String userName = message.getFrom();
String toUser = message.getTo(); | if(toUser.equals(Utils.ALL)){ |
caseydavenport/biermacht | src/com/biermacht/brews/utils/AlertBuilder.java | // Path: src/com/biermacht/brews/utils/Callbacks/BooleanCallback.java
// public abstract class BooleanCallback {
// public abstract void call(boolean b);
// }
//
// Path: src/com/biermacht/brews/utils/Callbacks/Callback.java
// public abstract class Callback {
// public abstract void call();
// }
| import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.biermacht.brews.R;
import com.biermacht.brews.utils.Callbacks.BooleanCallback;
import com.biermacht.brews.utils.Callbacks.Callback;
import java.util.ArrayList; | package com.biermacht.brews.utils;
public class AlertBuilder {
private Context context; | // Path: src/com/biermacht/brews/utils/Callbacks/BooleanCallback.java
// public abstract class BooleanCallback {
// public abstract void call(boolean b);
// }
//
// Path: src/com/biermacht/brews/utils/Callbacks/Callback.java
// public abstract class Callback {
// public abstract void call();
// }
// Path: src/com/biermacht/brews/utils/AlertBuilder.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.biermacht.brews.R;
import com.biermacht.brews.utils.Callbacks.BooleanCallback;
import com.biermacht.brews.utils.Callbacks.Callback;
import java.util.ArrayList;
package com.biermacht.brews.utils;
public class AlertBuilder {
private Context context; | private Callback callback; |
caseydavenport/biermacht | src/com/biermacht/brews/utils/AlertBuilder.java | // Path: src/com/biermacht/brews/utils/Callbacks/BooleanCallback.java
// public abstract class BooleanCallback {
// public abstract void call(boolean b);
// }
//
// Path: src/com/biermacht/brews/utils/Callbacks/Callback.java
// public abstract class Callback {
// public abstract void call();
// }
| import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.biermacht.brews.R;
import com.biermacht.brews.utils.Callbacks.BooleanCallback;
import com.biermacht.brews.utils.Callbacks.Callback;
import java.util.ArrayList; | text.setText(editText.getText().toString());
callback.call();
}
})
.setNegativeButton(R.string.cancel, null);
}
public AlertDialog.Builder editTextFloatAlert(final TextView text, final TextView title) {
LayoutInflater factory = LayoutInflater.from(context);
final LinearLayout alertView = (LinearLayout) factory.inflate(R.layout.alert_view_edit_text_float_2_4, null);
final EditText editText = (EditText) alertView.findViewById(R.id.edit_text);
editText.setText(text.getText().toString());
return new AlertDialog.Builder(context)
.setTitle(title.getText().toString())
.setView(alertView)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
text.setText(editText.getText().toString());
callback.call();
}
})
.setNegativeButton(R.string.cancel, null);
}
| // Path: src/com/biermacht/brews/utils/Callbacks/BooleanCallback.java
// public abstract class BooleanCallback {
// public abstract void call(boolean b);
// }
//
// Path: src/com/biermacht/brews/utils/Callbacks/Callback.java
// public abstract class Callback {
// public abstract void call();
// }
// Path: src/com/biermacht/brews/utils/AlertBuilder.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.biermacht.brews.R;
import com.biermacht.brews.utils.Callbacks.BooleanCallback;
import com.biermacht.brews.utils.Callbacks.Callback;
import java.util.ArrayList;
text.setText(editText.getText().toString());
callback.call();
}
})
.setNegativeButton(R.string.cancel, null);
}
public AlertDialog.Builder editTextFloatAlert(final TextView text, final TextView title) {
LayoutInflater factory = LayoutInflater.from(context);
final LinearLayout alertView = (LinearLayout) factory.inflate(R.layout.alert_view_edit_text_float_2_4, null);
final EditText editText = (EditText) alertView.findViewById(R.id.edit_text);
editText.setText(text.getText().toString());
return new AlertDialog.Builder(context)
.setTitle(title.getText().toString())
.setView(alertView)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
text.setText(editText.getText().toString());
callback.call();
}
})
.setNegativeButton(R.string.cancel, null);
}
| public AlertDialog.Builder editTextFloatCheckBoxAlert(final TextView text, final TextView title, boolean checked, final BooleanCallback cb) { |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadFileRequestBody.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/TransformProgressListener.java
// public interface TransformProgressListener {
// void onProgress(long contentRead, long contentLength, boolean completed);
//
// void onFailed(String msg);
// }
| import com.jady.retrofitclient.listener.TransformProgressListener;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink; | package com.jady.retrofitclient.upload;
/**
* 重写request 用于监听读取进度
*/
public class UploadFileRequestBody extends RequestBody {
private RequestBody mRequestBody; | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/TransformProgressListener.java
// public interface TransformProgressListener {
// void onProgress(long contentRead, long contentLength, boolean completed);
//
// void onFailed(String msg);
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadFileRequestBody.java
import com.jady.retrofitclient.listener.TransformProgressListener;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
package com.jady.retrofitclient.upload;
/**
* 重写request 用于监听读取进度
*/
public class UploadFileRequestBody extends RequestBody {
private RequestBody mRequestBody; | private TransformProgressListener mProgressListener; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadResponseBody.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/TransformProgressListener.java
// public interface TransformProgressListener {
// void onProgress(long contentRead, long contentLength, boolean completed);
//
// void onFailed(String msg);
// }
| import com.jady.retrofitclient.listener.TransformProgressListener;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source; | package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadResponseBody extends ResponseBody {
private ResponseBody responseBody; | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/TransformProgressListener.java
// public interface TransformProgressListener {
// void onProgress(long contentRead, long contentLength, boolean completed);
//
// void onFailed(String msg);
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadResponseBody.java
import com.jady.retrofitclient.listener.TransformProgressListener;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadResponseBody extends ResponseBody {
private ResponseBody responseBody; | private TransformProgressListener progressListener; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/subscriber/CommonResultSubscriber.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/HttpCallback.java
// public abstract class HttpCallback<T> {
//
// public static final String TAG = "HttpCallback";
//
// protected Type genericityType;
//
// public HttpCallback() {
// Type genericSuperclass = getClass().getGenericSuperclass();
// if (genericSuperclass instanceof ParameterizedType) {
// this.genericityType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
// } else {
// this.genericityType = Object.class;
// }
// }
//
// public abstract void onResolve(T t);
//
// public abstract void onFailed(String err_code, String message);
//
// public Type getGenericityType() {
// return genericityType;
// }
//
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
| import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.jady.retrofitclient.callback.HttpCallback;
import com.jady.retrofitclient.callback.LoadingCallback;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import rx.Subscriber; | package com.jady.retrofitclient.subscriber;
/**
* Created by jady on 2016/12/8.
*/
public class CommonResultSubscriber<T extends ResponseBody> extends Subscriber<T> {
public static final String TAG = "CommonResultSubscriber";
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
| // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/HttpCallback.java
// public abstract class HttpCallback<T> {
//
// public static final String TAG = "HttpCallback";
//
// protected Type genericityType;
//
// public HttpCallback() {
// Type genericSuperclass = getClass().getGenericSuperclass();
// if (genericSuperclass instanceof ParameterizedType) {
// this.genericityType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
// } else {
// this.genericityType = Object.class;
// }
// }
//
// public abstract void onResolve(T t);
//
// public abstract void onFailed(String err_code, String message);
//
// public Type getGenericityType() {
// return genericityType;
// }
//
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/subscriber/CommonResultSubscriber.java
import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.jady.retrofitclient.callback.HttpCallback;
import com.jady.retrofitclient.callback.LoadingCallback;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import rx.Subscriber;
package com.jady.retrofitclient.subscriber;
/**
* Created by jady on 2016/12/8.
*/
public class CommonResultSubscriber<T extends ResponseBody> extends Subscriber<T> {
public static final String TAG = "CommonResultSubscriber";
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
| private LoadingCallback loadingCallback; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/subscriber/CommonResultSubscriber.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/HttpCallback.java
// public abstract class HttpCallback<T> {
//
// public static final String TAG = "HttpCallback";
//
// protected Type genericityType;
//
// public HttpCallback() {
// Type genericSuperclass = getClass().getGenericSuperclass();
// if (genericSuperclass instanceof ParameterizedType) {
// this.genericityType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
// } else {
// this.genericityType = Object.class;
// }
// }
//
// public abstract void onResolve(T t);
//
// public abstract void onFailed(String err_code, String message);
//
// public Type getGenericityType() {
// return genericityType;
// }
//
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
| import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.jady.retrofitclient.callback.HttpCallback;
import com.jady.retrofitclient.callback.LoadingCallback;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import rx.Subscriber; | package com.jady.retrofitclient.subscriber;
/**
* Created by jady on 2016/12/8.
*/
public class CommonResultSubscriber<T extends ResponseBody> extends Subscriber<T> {
public static final String TAG = "CommonResultSubscriber";
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
private LoadingCallback loadingCallback; | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/HttpCallback.java
// public abstract class HttpCallback<T> {
//
// public static final String TAG = "HttpCallback";
//
// protected Type genericityType;
//
// public HttpCallback() {
// Type genericSuperclass = getClass().getGenericSuperclass();
// if (genericSuperclass instanceof ParameterizedType) {
// this.genericityType = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
// } else {
// this.genericityType = Object.class;
// }
// }
//
// public abstract void onResolve(T t);
//
// public abstract void onFailed(String err_code, String message);
//
// public Type getGenericityType() {
// return genericityType;
// }
//
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/subscriber/CommonResultSubscriber.java
import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.jady.retrofitclient.callback.HttpCallback;
import com.jady.retrofitclient.callback.LoadingCallback;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import rx.Subscriber;
package com.jady.retrofitclient.subscriber;
/**
* Created by jady on 2016/12/8.
*/
public class CommonResultSubscriber<T extends ResponseBody> extends Subscriber<T> {
public static final String TAG = "CommonResultSubscriber";
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
private LoadingCallback loadingCallback; | private HttpCallback httpCallback; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadSubscriber.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/FileResponseResult.java
// public interface FileResponseResult {
//
// void onSuccess();
//
// void onFailure(Throwable throwable, String content);
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
| import android.content.Context;
import android.text.TextUtils;
import com.jady.retrofitclient.callback.FileResponseResult;
import com.jady.retrofitclient.callback.LoadingCallback;
import okhttp3.ResponseBody;
import rx.Subscriber; | package com.jady.retrofitclient.upload;
/**
* Created by jady on 2016/12/8.
*/
public class UploadSubscriber<T extends ResponseBody> extends Subscriber<T> {
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
| // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/FileResponseResult.java
// public interface FileResponseResult {
//
// void onSuccess();
//
// void onFailure(Throwable throwable, String content);
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadSubscriber.java
import android.content.Context;
import android.text.TextUtils;
import com.jady.retrofitclient.callback.FileResponseResult;
import com.jady.retrofitclient.callback.LoadingCallback;
import okhttp3.ResponseBody;
import rx.Subscriber;
package com.jady.retrofitclient.upload;
/**
* Created by jady on 2016/12/8.
*/
public class UploadSubscriber<T extends ResponseBody> extends Subscriber<T> {
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
| private LoadingCallback loadingCallback; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadSubscriber.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/FileResponseResult.java
// public interface FileResponseResult {
//
// void onSuccess();
//
// void onFailure(Throwable throwable, String content);
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
| import android.content.Context;
import android.text.TextUtils;
import com.jady.retrofitclient.callback.FileResponseResult;
import com.jady.retrofitclient.callback.LoadingCallback;
import okhttp3.ResponseBody;
import rx.Subscriber; | package com.jady.retrofitclient.upload;
/**
* Created by jady on 2016/12/8.
*/
public class UploadSubscriber<T extends ResponseBody> extends Subscriber<T> {
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
private LoadingCallback loadingCallback; | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/FileResponseResult.java
// public interface FileResponseResult {
//
// void onSuccess();
//
// void onFailure(Throwable throwable, String content);
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/callback/LoadingCallback.java
// public interface LoadingCallback {
// /**
// * 开始显示加载框
// * @param msg
// */
// void onStartLoading(String msg);
//
// /**
// * 隐藏加载框
// */
// void onFinishLoading();
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/upload/UploadSubscriber.java
import android.content.Context;
import android.text.TextUtils;
import com.jady.retrofitclient.callback.FileResponseResult;
import com.jady.retrofitclient.callback.LoadingCallback;
import okhttp3.ResponseBody;
import rx.Subscriber;
package com.jady.retrofitclient.upload;
/**
* Created by jady on 2016/12/8.
*/
public class UploadSubscriber<T extends ResponseBody> extends Subscriber<T> {
private Context mContext;
private boolean showLoadingDailog = false;
private String loadingMsg;
private LoadingCallback loadingCallback; | private FileResponseResult callback; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/interceptor/OffLineIntercept.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/NetworkUtils.java
// public class NetworkUtils {
// public static boolean isNetworkConnected(Context context) {
// try {
// ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
// if (mNetworkInfo != null) {
// return mNetworkInfo.isAvailable();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
// }
| import android.content.Context;
import com.jady.retrofitclient.NetworkUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response; | package com.jady.retrofitclient.interceptor;
/**
* 离线时,20秒内会使用离线缓存
* Created by jady on 2016/12/8.
*/
public class OffLineIntercept implements Interceptor {
private Context mContext;
public OffLineIntercept(Context mContext) {
this.mContext = mContext;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request(); | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/NetworkUtils.java
// public class NetworkUtils {
// public static boolean isNetworkConnected(Context context) {
// try {
// ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
// if (mNetworkInfo != null) {
// return mNetworkInfo.isAvailable();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/interceptor/OffLineIntercept.java
import android.content.Context;
import com.jady.retrofitclient.NetworkUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
package com.jady.retrofitclient.interceptor;
/**
* 离线时,20秒内会使用离线缓存
* Created by jady on 2016/12/8.
*/
public class OffLineIntercept implements Interceptor {
private Context mContext;
public OffLineIntercept(Context mContext) {
this.mContext = mContext;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request(); | if (!NetworkUtils.isNetworkConnected(mContext)) { |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/interceptor/CacheInterceptor.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/NetworkUtils.java
// public class NetworkUtils {
// public static boolean isNetworkConnected(Context context) {
// try {
// ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
// if (mNetworkInfo != null) {
// return mNetworkInfo.isAvailable();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
// }
| import android.content.Context;
import com.jady.retrofitclient.NetworkUtils;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response; | package com.jady.retrofitclient.interceptor;
/**
* Created by Yuan on 2016/10/30.
* Detail cache for http 如果离线缓存与在线缓存同时使用,在线的时候必须先将离线缓存清空
*/
/**
* 离线时,20秒内会使用离线缓存
* Created by jady on 2016/12/8.
*/
public class CacheInterceptor implements Interceptor {
private final String TAG = "CacheInterceptor";
private Context mC;
public CacheInterceptor(Context mC) {
this.mC = mC;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
| // Path: retrofitclient/src/main/java/com/jady/retrofitclient/NetworkUtils.java
// public class NetworkUtils {
// public static boolean isNetworkConnected(Context context) {
// try {
// ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
// if (mNetworkInfo != null) {
// return mNetworkInfo.isAvailable();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/interceptor/CacheInterceptor.java
import android.content.Context;
import com.jady.retrofitclient.NetworkUtils;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
package com.jady.retrofitclient.interceptor;
/**
* Created by Yuan on 2016/10/30.
* Detail cache for http 如果离线缓存与在线缓存同时使用,在线的时候必须先将离线缓存清空
*/
/**
* 离线时,20秒内会使用离线缓存
* Created by jady on 2016/12/8.
*/
public class CacheInterceptor implements Interceptor {
private final String TAG = "CacheInterceptor";
private Context mC;
public CacheInterceptor(Context mC) {
this.mC = mC;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
| if (!NetworkUtils.isNetworkConnected(mC)) {//没网强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,就获取不到缓存) |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadInfo.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/DownloadFileListener.java
// public abstract class DownloadFileListener<T> {
// /**
// * 单个下载成功后回调
// *
// * @param t
// */
// public abstract void onNext(T t);
//
// public void onStart(){};
//
// /**
// * 批量下载完成
// */
// public abstract void onComplete();
//
// public abstract void updateProgress(float contentRead, long contentLength, boolean completed);
//
// public abstract void onError(Throwable e);
//
// public void onPause() {
//
// }
//
// public void onStop() {
//
// }
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/request/CommonRequest.java
// public interface CommonRequest {
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @Body RequestBody map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @FormUrlEncoded
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> maps);
//
// @HTTP(method = "DELETE", path = "{path}", hasBody = true)
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// /**
// * 完整路径
// *
// * @param url
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url);
//
// /**
// * 完整路径
// *
// * @param url
// * @param map
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url, @QueryMap Map<String, Object> map);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url 完整路径
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST
// Observable<ResponseBody> doPostFullPath(@Url String url, @FieldMap Map<String, Object> map);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFile(@Path(value = "path", encoded = true) String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFileFullPath(@Url String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFiles(
// @Path(value = "path", encoded = true) String url,
// @PartMap Map<String, RequestBody> maps);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFilesFullPath(
// @Url String url,
// @PartMap() Map<String, RequestBody> maps);
//
// //支持大文件
// @Streaming
// @GET
// Observable<ResponseBody> download(@Url String fileUrl);
// }
| import com.jady.retrofitclient.listener.DownloadFileListener;
import com.jady.retrofitclient.request.CommonRequest; | package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadInfo {
public static final int START = 0;
public static final int DOWNLOAD = 1;
public static final int PAUSE = 2;
public static final int STOP = 3;
public static final int ERROR = 4;
public static final int FINISH = 5;
private int id = 0;
private String savePath;
private long contentLength;
private long readLength;
private int state;
private String url;
| // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/DownloadFileListener.java
// public abstract class DownloadFileListener<T> {
// /**
// * 单个下载成功后回调
// *
// * @param t
// */
// public abstract void onNext(T t);
//
// public void onStart(){};
//
// /**
// * 批量下载完成
// */
// public abstract void onComplete();
//
// public abstract void updateProgress(float contentRead, long contentLength, boolean completed);
//
// public abstract void onError(Throwable e);
//
// public void onPause() {
//
// }
//
// public void onStop() {
//
// }
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/request/CommonRequest.java
// public interface CommonRequest {
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @Body RequestBody map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @FormUrlEncoded
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> maps);
//
// @HTTP(method = "DELETE", path = "{path}", hasBody = true)
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// /**
// * 完整路径
// *
// * @param url
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url);
//
// /**
// * 完整路径
// *
// * @param url
// * @param map
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url, @QueryMap Map<String, Object> map);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url 完整路径
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST
// Observable<ResponseBody> doPostFullPath(@Url String url, @FieldMap Map<String, Object> map);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFile(@Path(value = "path", encoded = true) String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFileFullPath(@Url String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFiles(
// @Path(value = "path", encoded = true) String url,
// @PartMap Map<String, RequestBody> maps);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFilesFullPath(
// @Url String url,
// @PartMap() Map<String, RequestBody> maps);
//
// //支持大文件
// @Streaming
// @GET
// Observable<ResponseBody> download(@Url String fileUrl);
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadInfo.java
import com.jady.retrofitclient.listener.DownloadFileListener;
import com.jady.retrofitclient.request.CommonRequest;
package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadInfo {
public static final int START = 0;
public static final int DOWNLOAD = 1;
public static final int PAUSE = 2;
public static final int STOP = 3;
public static final int ERROR = 4;
public static final int FINISH = 5;
private int id = 0;
private String savePath;
private long contentLength;
private long readLength;
private int state;
private String url;
| private DownloadFileListener listener; |
Jadyli/RetrofitClient | retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadInfo.java | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/DownloadFileListener.java
// public abstract class DownloadFileListener<T> {
// /**
// * 单个下载成功后回调
// *
// * @param t
// */
// public abstract void onNext(T t);
//
// public void onStart(){};
//
// /**
// * 批量下载完成
// */
// public abstract void onComplete();
//
// public abstract void updateProgress(float contentRead, long contentLength, boolean completed);
//
// public abstract void onError(Throwable e);
//
// public void onPause() {
//
// }
//
// public void onStop() {
//
// }
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/request/CommonRequest.java
// public interface CommonRequest {
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @Body RequestBody map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @FormUrlEncoded
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> maps);
//
// @HTTP(method = "DELETE", path = "{path}", hasBody = true)
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// /**
// * 完整路径
// *
// * @param url
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url);
//
// /**
// * 完整路径
// *
// * @param url
// * @param map
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url, @QueryMap Map<String, Object> map);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url 完整路径
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST
// Observable<ResponseBody> doPostFullPath(@Url String url, @FieldMap Map<String, Object> map);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFile(@Path(value = "path", encoded = true) String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFileFullPath(@Url String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFiles(
// @Path(value = "path", encoded = true) String url,
// @PartMap Map<String, RequestBody> maps);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFilesFullPath(
// @Url String url,
// @PartMap() Map<String, RequestBody> maps);
//
// //支持大文件
// @Streaming
// @GET
// Observable<ResponseBody> download(@Url String fileUrl);
// }
| import com.jady.retrofitclient.listener.DownloadFileListener;
import com.jady.retrofitclient.request.CommonRequest; | package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadInfo {
public static final int START = 0;
public static final int DOWNLOAD = 1;
public static final int PAUSE = 2;
public static final int STOP = 3;
public static final int ERROR = 4;
public static final int FINISH = 5;
private int id = 0;
private String savePath;
private long contentLength;
private long readLength;
private int state;
private String url;
private DownloadFileListener listener; | // Path: retrofitclient/src/main/java/com/jady/retrofitclient/listener/DownloadFileListener.java
// public abstract class DownloadFileListener<T> {
// /**
// * 单个下载成功后回调
// *
// * @param t
// */
// public abstract void onNext(T t);
//
// public void onStart(){};
//
// /**
// * 批量下载完成
// */
// public abstract void onComplete();
//
// public abstract void updateProgress(float contentRead, long contentLength, boolean completed);
//
// public abstract void onError(Throwable e);
//
// public void onPause() {
//
// }
//
// public void onStop() {
//
// }
// }
//
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/request/CommonRequest.java
// public interface CommonRequest {
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url, @Body RequestBody map);
//
// @GET("{path}")
// Observable<ResponseBody> doGet(@Path(value = "path", encoded = true) String url);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @POST("{path}")
// Observable<ResponseBody> doPost(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @FormUrlEncoded
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @FieldMap Map<String, Object> map);
//
// @PUT("{path}")
// Observable<ResponseBody> doPut(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url);
//
// @DELETE("{path}")
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @QueryMap Map<String, Object> maps);
//
// @HTTP(method = "DELETE", path = "{path}", hasBody = true)
// Observable<ResponseBody> doDelete(@Path(value = "path", encoded = true) String url, @Body RequestBody body);
//
// /**
// * 完整路径
// *
// * @param url
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url);
//
// /**
// * 完整路径
// *
// * @param url
// * @param map
// * @return
// */
// @GET
// Observable<ResponseBody> doGetFullPath(@Url String url, @QueryMap Map<String, Object> map);
//
// /**
// * 参数含有@Field和@FieldMap的请求必须加@FormUrlEncoded
// * Post请求最好用@Field,@Query也行,只是参数会暴露在Url中
// *
// * @param url 完整路径
// * @param map
// * @return
// */
// @FormUrlEncoded
// @POST
// Observable<ResponseBody> doPostFullPath(@Url String url, @FieldMap Map<String, Object> map);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFile(@Path(value = "path", encoded = true) String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFileFullPath(@Url String url,
// @Part("description") RequestBody description, @Part MultipartBody.Part file);
//
// @Multipart
// @POST("{path}")
// Observable<ResponseBody> uploadFiles(
// @Path(value = "path", encoded = true) String url,
// @PartMap Map<String, RequestBody> maps);
//
// @Multipart
// @POST
// Observable<ResponseBody> uploadFilesFullPath(
// @Url String url,
// @PartMap() Map<String, RequestBody> maps);
//
// //支持大文件
// @Streaming
// @GET
// Observable<ResponseBody> download(@Url String fileUrl);
// }
// Path: retrofitclient/src/main/java/com/jady/retrofitclient/download/DownloadInfo.java
import com.jady.retrofitclient.listener.DownloadFileListener;
import com.jady.retrofitclient.request.CommonRequest;
package com.jady.retrofitclient.download;
/**
* Created by jady on 2017/2/6.
*/
public class DownloadInfo {
public static final int START = 0;
public static final int DOWNLOAD = 1;
public static final int PAUSE = 2;
public static final int STOP = 3;
public static final int ERROR = 4;
public static final int FINISH = 5;
private int id = 0;
private String savePath;
private long contentLength;
private long readLength;
private int state;
private String url;
private DownloadFileListener listener; | private CommonRequest request; |
Jadyli/RetrofitClient | app/src/main/java/com/jady/sample/ui/adapter/MovieDemoRvAdapter.java | // Path: app/src/main/java/com/jady/sample/bean/movie/Casts.java
// public class Casts {
// private String alt;
// private Avatars avatars;
// private String name;
// private String id;
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
//
// Path: app/src/main/java/com/jady/sample/bean/movie/Directors.java
// public class Directors {
// private String alt;
// private AvatarsX avatars;
// private String name;
// private String id;
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public AvatarsX getAvatars() {
// return avatars;
// }
//
// public void setAvatars(AvatarsX avatars) {
// this.avatars = avatars;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
//
// Path: app/src/main/java/com/jady/sample/bean/movie/Subjects.java
// public class Subjects {
// private Rating rating;
// private String title;
// private int collect_count;
// private String original_title;
// private String subtype;
// private String year;
// private Images images;
// private String alt;
// private String id;
// private List<String> genres;
// private List<Casts> casts;
// private List<Directors> directors;
//
// public Rating getRating() {
// return rating;
// }
//
// public void setRating(Rating rating) {
// this.rating = rating;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getCollect_count() {
// return collect_count;
// }
//
// public void setCollect_count(int collect_count) {
// this.collect_count = collect_count;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public String getSubtype() {
// return subtype;
// }
//
// public void setSubtype(String subtype) {
// this.subtype = subtype;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public Images getImages() {
// return images;
// }
//
// public void setImages(Images images) {
// this.images = images;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Casts> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Casts> casts) {
// this.casts = casts;
// }
//
// public List<Directors> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Directors> directors) {
// this.directors = directors;
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.jady.sample.R;
import com.jady.sample.bean.movie.Casts;
import com.jady.sample.bean.movie.Directors;
import com.jady.sample.bean.movie.Subjects;
import com.jady.sample.support.GlideApp;
import java.util.ArrayList;
import java.util.List; | package com.jady.sample.ui.adapter;
/**
* Created by lipingfa on 2017/6/12.
*/
public class MovieDemoRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext; | // Path: app/src/main/java/com/jady/sample/bean/movie/Casts.java
// public class Casts {
// private String alt;
// private Avatars avatars;
// private String name;
// private String id;
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public Avatars getAvatars() {
// return avatars;
// }
//
// public void setAvatars(Avatars avatars) {
// this.avatars = avatars;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
//
// Path: app/src/main/java/com/jady/sample/bean/movie/Directors.java
// public class Directors {
// private String alt;
// private AvatarsX avatars;
// private String name;
// private String id;
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public AvatarsX getAvatars() {
// return avatars;
// }
//
// public void setAvatars(AvatarsX avatars) {
// this.avatars = avatars;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// }
//
// Path: app/src/main/java/com/jady/sample/bean/movie/Subjects.java
// public class Subjects {
// private Rating rating;
// private String title;
// private int collect_count;
// private String original_title;
// private String subtype;
// private String year;
// private Images images;
// private String alt;
// private String id;
// private List<String> genres;
// private List<Casts> casts;
// private List<Directors> directors;
//
// public Rating getRating() {
// return rating;
// }
//
// public void setRating(Rating rating) {
// this.rating = rating;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getCollect_count() {
// return collect_count;
// }
//
// public void setCollect_count(int collect_count) {
// this.collect_count = collect_count;
// }
//
// public String getOriginal_title() {
// return original_title;
// }
//
// public void setOriginal_title(String original_title) {
// this.original_title = original_title;
// }
//
// public String getSubtype() {
// return subtype;
// }
//
// public void setSubtype(String subtype) {
// this.subtype = subtype;
// }
//
// public String getYear() {
// return year;
// }
//
// public void setYear(String year) {
// this.year = year;
// }
//
// public Images getImages() {
// return images;
// }
//
// public void setImages(Images images) {
// this.images = images;
// }
//
// public String getAlt() {
// return alt;
// }
//
// public void setAlt(String alt) {
// this.alt = alt;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<String> getGenres() {
// return genres;
// }
//
// public void setGenres(List<String> genres) {
// this.genres = genres;
// }
//
// public List<Casts> getCasts() {
// return casts;
// }
//
// public void setCasts(List<Casts> casts) {
// this.casts = casts;
// }
//
// public List<Directors> getDirectors() {
// return directors;
// }
//
// public void setDirectors(List<Directors> directors) {
// this.directors = directors;
// }
// }
// Path: app/src/main/java/com/jady/sample/ui/adapter/MovieDemoRvAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.jady.sample.R;
import com.jady.sample.bean.movie.Casts;
import com.jady.sample.bean.movie.Directors;
import com.jady.sample.bean.movie.Subjects;
import com.jady.sample.support.GlideApp;
import java.util.ArrayList;
import java.util.List;
package com.jady.sample.ui.adapter;
/**
* Created by lipingfa on 2017/6/12.
*/
public class MovieDemoRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext; | private List<Subjects> dataList = new ArrayList<>(); |
sismics/home | home-core/src/main/java/com/sismics/home/core/util/DirectoryUtil.java | // Path: home-core/src/main/java/com/sismics/util/EnvironmentUtil.java
// public class EnvironmentUtil {
//
// private static String OS = System.getProperty("os.name").toLowerCase();
//
// private static String APPLICATION_MODE = System.getProperty("application.mode");
//
// private static String WINDOWS_APPDATA = System.getenv("APPDATA");
//
// private static String MAC_OS_USER_HOME = System.getProperty("user.home");
//
// private static String HOME_HOME = System.getProperty("home.home");
//
// /**
// * In a web application context.
// */
// private static boolean webappContext;
//
// /**
// * Returns true if running under Microsoft Windows.
// *
// * @return Running under Microsoft Windows
// */
// public static boolean isWindows() {
// return OS.indexOf("win") >= 0;
// }
//
// /**
// * Returns true if running under Mac OS.
// *
// * @return Running under Mac OS
// */
// public static boolean isMacOs() {
// return OS.indexOf("mac") >= 0;
// }
//
// /**
// * Returns true if running under UNIX.
// *
// * @return Running under UNIX
// */
// public static boolean isUnix() {
// return OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0;
// }
//
// /**
// * Returns true if we are in a unit testing environment.
// *
// * @return Unit testing environment
// */
// public static boolean isUnitTest() {
// return !webappContext || isDevMode();
// }
//
// /**
// * Return true if we are in dev mode.
// *
// * @return Dev mode
// */
// public static boolean isDevMode() {
// return "dev".equalsIgnoreCase(APPLICATION_MODE);
// }
//
// /**
// * Returns the MS Windows AppData directory of this user.
// *
// * @return AppData directory
// */
// public static String getWindowsAppData() {
// return WINDOWS_APPDATA;
// }
//
// /**
// * Returns the Mac OS home directory of this user.
// *
// * @return Home directory
// */
// public static String getMacOsUserHome() {
// return MAC_OS_USER_HOME;
// }
//
// /**
// * Returns the home directory of Home (e.g. /var/home).
// *
// * @return Home directory
// */
// public static String getHomeHome() {
// return HOME_HOME;
// }
//
// /**
// * Getter of webappContext.
// *
// * @return webappContext
// */
// public static boolean isWebappContext() {
// return webappContext;
// }
//
// /**
// * Setter of webappContext.
// *
// * @param webappContext webappContext
// */
// public static void setWebappContext(boolean webappContext) {
// EnvironmentUtil.webappContext = webappContext;
// }
// }
| import java.io.File;
import org.apache.commons.lang.StringUtils;
import com.sismics.util.EnvironmentUtil; | package com.sismics.home.core.util;
/**
* Utilities to gain access to the storage directories used by the application.
*
* @author jtremeaux
*/
public class DirectoryUtil {
/**
* Returns the base data directory.
*
* @return Base data directory
*/
public static File getBaseDataDirectory() {
File baseDataDir = null;
// TODO inject a variable from context.xml or similar (#41) | // Path: home-core/src/main/java/com/sismics/util/EnvironmentUtil.java
// public class EnvironmentUtil {
//
// private static String OS = System.getProperty("os.name").toLowerCase();
//
// private static String APPLICATION_MODE = System.getProperty("application.mode");
//
// private static String WINDOWS_APPDATA = System.getenv("APPDATA");
//
// private static String MAC_OS_USER_HOME = System.getProperty("user.home");
//
// private static String HOME_HOME = System.getProperty("home.home");
//
// /**
// * In a web application context.
// */
// private static boolean webappContext;
//
// /**
// * Returns true if running under Microsoft Windows.
// *
// * @return Running under Microsoft Windows
// */
// public static boolean isWindows() {
// return OS.indexOf("win") >= 0;
// }
//
// /**
// * Returns true if running under Mac OS.
// *
// * @return Running under Mac OS
// */
// public static boolean isMacOs() {
// return OS.indexOf("mac") >= 0;
// }
//
// /**
// * Returns true if running under UNIX.
// *
// * @return Running under UNIX
// */
// public static boolean isUnix() {
// return OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0;
// }
//
// /**
// * Returns true if we are in a unit testing environment.
// *
// * @return Unit testing environment
// */
// public static boolean isUnitTest() {
// return !webappContext || isDevMode();
// }
//
// /**
// * Return true if we are in dev mode.
// *
// * @return Dev mode
// */
// public static boolean isDevMode() {
// return "dev".equalsIgnoreCase(APPLICATION_MODE);
// }
//
// /**
// * Returns the MS Windows AppData directory of this user.
// *
// * @return AppData directory
// */
// public static String getWindowsAppData() {
// return WINDOWS_APPDATA;
// }
//
// /**
// * Returns the Mac OS home directory of this user.
// *
// * @return Home directory
// */
// public static String getMacOsUserHome() {
// return MAC_OS_USER_HOME;
// }
//
// /**
// * Returns the home directory of Home (e.g. /var/home).
// *
// * @return Home directory
// */
// public static String getHomeHome() {
// return HOME_HOME;
// }
//
// /**
// * Getter of webappContext.
// *
// * @return webappContext
// */
// public static boolean isWebappContext() {
// return webappContext;
// }
//
// /**
// * Setter of webappContext.
// *
// * @param webappContext webappContext
// */
// public static void setWebappContext(boolean webappContext) {
// EnvironmentUtil.webappContext = webappContext;
// }
// }
// Path: home-core/src/main/java/com/sismics/home/core/util/DirectoryUtil.java
import java.io.File;
import org.apache.commons.lang.StringUtils;
import com.sismics.util.EnvironmentUtil;
package com.sismics.home.core.util;
/**
* Utilities to gain access to the storage directories used by the application.
*
* @author jtremeaux
*/
public class DirectoryUtil {
/**
* Returns the base data directory.
*
* @return Base data directory
*/
public static File getBaseDataDirectory() {
File baseDataDir = null;
// TODO inject a variable from context.xml or similar (#41) | if (StringUtils.isNotBlank(EnvironmentUtil.getHomeHome())) { |
sismics/home | home-web-common/src/main/java/com/sismics/util/db/DbUtil.java | // Path: home-core/src/main/java/com/sismics/util/EnvironmentUtil.java
// public class EnvironmentUtil {
//
// private static String OS = System.getProperty("os.name").toLowerCase();
//
// private static String APPLICATION_MODE = System.getProperty("application.mode");
//
// private static String WINDOWS_APPDATA = System.getenv("APPDATA");
//
// private static String MAC_OS_USER_HOME = System.getProperty("user.home");
//
// private static String HOME_HOME = System.getProperty("home.home");
//
// /**
// * In a web application context.
// */
// private static boolean webappContext;
//
// /**
// * Returns true if running under Microsoft Windows.
// *
// * @return Running under Microsoft Windows
// */
// public static boolean isWindows() {
// return OS.indexOf("win") >= 0;
// }
//
// /**
// * Returns true if running under Mac OS.
// *
// * @return Running under Mac OS
// */
// public static boolean isMacOs() {
// return OS.indexOf("mac") >= 0;
// }
//
// /**
// * Returns true if running under UNIX.
// *
// * @return Running under UNIX
// */
// public static boolean isUnix() {
// return OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0;
// }
//
// /**
// * Returns true if we are in a unit testing environment.
// *
// * @return Unit testing environment
// */
// public static boolean isUnitTest() {
// return !webappContext || isDevMode();
// }
//
// /**
// * Return true if we are in dev mode.
// *
// * @return Dev mode
// */
// public static boolean isDevMode() {
// return "dev".equalsIgnoreCase(APPLICATION_MODE);
// }
//
// /**
// * Returns the MS Windows AppData directory of this user.
// *
// * @return AppData directory
// */
// public static String getWindowsAppData() {
// return WINDOWS_APPDATA;
// }
//
// /**
// * Returns the Mac OS home directory of this user.
// *
// * @return Home directory
// */
// public static String getMacOsUserHome() {
// return MAC_OS_USER_HOME;
// }
//
// /**
// * Returns the home directory of Home (e.g. /var/home).
// *
// * @return Home directory
// */
// public static String getHomeHome() {
// return HOME_HOME;
// }
//
// /**
// * Getter of webappContext.
// *
// * @return webappContext
// */
// public static boolean isWebappContext() {
// return webappContext;
// }
//
// /**
// * Setter of webappContext.
// *
// * @param webappContext webappContext
// */
// public static void setWebappContext(boolean webappContext) {
// EnvironmentUtil.webappContext = webappContext;
// }
// }
| import com.sismics.util.EnvironmentUtil;
import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException; | package com.sismics.util.db;
/**
* Database console util.
*
* @author jtremeaux
*/
public class DbUtil {
/**
* Logger.
*/
private static final Logger log = LoggerFactory.getLogger(DbUtil.class);
private static boolean started;
private static Server h2Server;
public static synchronized void start() { | // Path: home-core/src/main/java/com/sismics/util/EnvironmentUtil.java
// public class EnvironmentUtil {
//
// private static String OS = System.getProperty("os.name").toLowerCase();
//
// private static String APPLICATION_MODE = System.getProperty("application.mode");
//
// private static String WINDOWS_APPDATA = System.getenv("APPDATA");
//
// private static String MAC_OS_USER_HOME = System.getProperty("user.home");
//
// private static String HOME_HOME = System.getProperty("home.home");
//
// /**
// * In a web application context.
// */
// private static boolean webappContext;
//
// /**
// * Returns true if running under Microsoft Windows.
// *
// * @return Running under Microsoft Windows
// */
// public static boolean isWindows() {
// return OS.indexOf("win") >= 0;
// }
//
// /**
// * Returns true if running under Mac OS.
// *
// * @return Running under Mac OS
// */
// public static boolean isMacOs() {
// return OS.indexOf("mac") >= 0;
// }
//
// /**
// * Returns true if running under UNIX.
// *
// * @return Running under UNIX
// */
// public static boolean isUnix() {
// return OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0;
// }
//
// /**
// * Returns true if we are in a unit testing environment.
// *
// * @return Unit testing environment
// */
// public static boolean isUnitTest() {
// return !webappContext || isDevMode();
// }
//
// /**
// * Return true if we are in dev mode.
// *
// * @return Dev mode
// */
// public static boolean isDevMode() {
// return "dev".equalsIgnoreCase(APPLICATION_MODE);
// }
//
// /**
// * Returns the MS Windows AppData directory of this user.
// *
// * @return AppData directory
// */
// public static String getWindowsAppData() {
// return WINDOWS_APPDATA;
// }
//
// /**
// * Returns the Mac OS home directory of this user.
// *
// * @return Home directory
// */
// public static String getMacOsUserHome() {
// return MAC_OS_USER_HOME;
// }
//
// /**
// * Returns the home directory of Home (e.g. /var/home).
// *
// * @return Home directory
// */
// public static String getHomeHome() {
// return HOME_HOME;
// }
//
// /**
// * Getter of webappContext.
// *
// * @return webappContext
// */
// public static boolean isWebappContext() {
// return webappContext;
// }
//
// /**
// * Setter of webappContext.
// *
// * @param webappContext webappContext
// */
// public static void setWebappContext(boolean webappContext) {
// EnvironmentUtil.webappContext = webappContext;
// }
// }
// Path: home-web-common/src/main/java/com/sismics/util/db/DbUtil.java
import com.sismics.util.EnvironmentUtil;
import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
package com.sismics.util.db;
/**
* Database console util.
*
* @author jtremeaux
*/
public class DbUtil {
/**
* Logger.
*/
private static final Logger log = LoggerFactory.getLogger(DbUtil.class);
private static boolean started;
private static Server h2Server;
public static synchronized void start() { | if (started || !EnvironmentUtil.isDevMode()) { |
sismics/home | home-core/src/main/java/com/sismics/home/core/util/dbi/QueryUtil.java | // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java
// public class ThreadLocalContext {
// /**
// * ThreadLocal to store the context.
// */
// public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>();
//
// /**
// * JDBI handle.
// */
// private Handle handle;
//
// /**
// * Private constructor.
// */
// private ThreadLocalContext() {
// // NOP
// }
//
// /**
// * Returns an instance of this thread context.
// *
// * @return Thread local context
// */
// public static ThreadLocalContext get() {
// ThreadLocalContext context = threadLocalContext.get();
// if (context == null) {
// context = new ThreadLocalContext();
// threadLocalContext.set(context);
// }
// return context;
// }
//
// /**
// * Cleans up the instance of this thread context.
// */
// public static void cleanup() {
// threadLocalContext.set(null);
// }
//
// /**
// * Getter of handle.
// *
// * @return handle
// */
// public Handle getHandle() {
// return handle;
// }
//
// /**
// * Setter of handle.
// *
// * @param handle handle
// */
// public void setHandle(Handle handle) {
// this.handle = handle;
// }
// }
| import java.util.Map;
import java.util.Map.Entry;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import com.sismics.util.context.ThreadLocalContext; | package com.sismics.home.core.util.dbi;
/**
* Query utilities.
*
* @author jtremeaux
*/
public class QueryUtil {
/**
* Creates a native query from the query parameters.
*
* @param queryParam Query parameters
* @return Native query
*/
public static Query<Map<String, Object>> getNativeQuery(QueryParam queryParam) { | // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java
// public class ThreadLocalContext {
// /**
// * ThreadLocal to store the context.
// */
// public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>();
//
// /**
// * JDBI handle.
// */
// private Handle handle;
//
// /**
// * Private constructor.
// */
// private ThreadLocalContext() {
// // NOP
// }
//
// /**
// * Returns an instance of this thread context.
// *
// * @return Thread local context
// */
// public static ThreadLocalContext get() {
// ThreadLocalContext context = threadLocalContext.get();
// if (context == null) {
// context = new ThreadLocalContext();
// threadLocalContext.set(context);
// }
// return context;
// }
//
// /**
// * Cleans up the instance of this thread context.
// */
// public static void cleanup() {
// threadLocalContext.set(null);
// }
//
// /**
// * Getter of handle.
// *
// * @return handle
// */
// public Handle getHandle() {
// return handle;
// }
//
// /**
// * Setter of handle.
// *
// * @param handle handle
// */
// public void setHandle(Handle handle) {
// this.handle = handle;
// }
// }
// Path: home-core/src/main/java/com/sismics/home/core/util/dbi/QueryUtil.java
import java.util.Map;
import java.util.Map.Entry;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import com.sismics.util.context.ThreadLocalContext;
package com.sismics.home.core.util.dbi;
/**
* Query utilities.
*
* @author jtremeaux
*/
public class QueryUtil {
/**
* Creates a native query from the query parameters.
*
* @param queryParam Query parameters
* @return Native query
*/
public static Query<Map<String, Object>> getNativeQuery(QueryParam queryParam) { | final Handle handle = ThreadLocalContext.get().getHandle(); |
sismics/home | home-core/src/main/java/com/sismics/util/dbi/DbOpenHelper.java | // Path: home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java
// public class ConfigUtil {
// /**
// * Returns the textual value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Textual value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static String getConfigStringValue(ConfigType configType) {
// ConfigDao configDao = new ConfigDao();
// Config config = configDao.getById(configType);
// if (config == null) {
// throw new IllegalStateException("Config parameter not found: " + configType);
// }
// return config.getValue();
// }
//
// /**
// * Returns the configuration resource bundle.
// *
// * @return Resource bundle
// */
// public static ResourceBundle getConfigBundle() {
// return ResourceBundle.getBundle("config");
// }
//
// /**
// * Returns the integer value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Integer value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static int getConfigIntegerValue(ConfigType configType) {
// String value = getConfigStringValue(configType);
//
// return Integer.parseInt(value);
// }
//
// /**
// * Returns the boolean value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Boolean value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static boolean getConfigBooleanValue(ConfigType configType) {
// String value = getConfigStringValue(configType);
//
// return Boolean.parseBoolean(value);
// }
// }
| import com.google.common.base.Strings;
import com.google.common.io.CharStreams;
import com.sismics.home.core.util.ConfigUtil;
import com.sismics.util.ResourceUtil;
import org.skife.jdbi.v2.Handle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.*; | public void open() {
log.info("Opening database and executing incremental updates");
exceptions.clear();
try {
// Check if database is already created
Integer oldVersion = null;
try {
List<Map<String,Object>> resultMap = handle.select("select c.CFG_VALUE_C as ver from T_CONFIG c where c.CFG_ID_C='DB_VERSION'");
if (!resultMap.isEmpty()) {
String oldVersionStr = (String) resultMap.get(0).get("ver");
oldVersion = Integer.parseInt(oldVersionStr);
}
} catch (Exception e) {
if (e.getMessage().contains("not found")) {
log.info("Unable to get database version: Table T_CONFIG not found");
} else {
log.error("Unable to get database version", e);
}
}
if (oldVersion == null) {
// Execute creation script
log.info("Executing initial schema creation script");
onCreate();
oldVersion = 0;
}
// Execute update script | // Path: home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java
// public class ConfigUtil {
// /**
// * Returns the textual value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Textual value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static String getConfigStringValue(ConfigType configType) {
// ConfigDao configDao = new ConfigDao();
// Config config = configDao.getById(configType);
// if (config == null) {
// throw new IllegalStateException("Config parameter not found: " + configType);
// }
// return config.getValue();
// }
//
// /**
// * Returns the configuration resource bundle.
// *
// * @return Resource bundle
// */
// public static ResourceBundle getConfigBundle() {
// return ResourceBundle.getBundle("config");
// }
//
// /**
// * Returns the integer value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Integer value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static int getConfigIntegerValue(ConfigType configType) {
// String value = getConfigStringValue(configType);
//
// return Integer.parseInt(value);
// }
//
// /**
// * Returns the boolean value of a configuration parameter.
// *
// * @param configType Type of the configuration parameter
// * @return Boolean value of the configuration parameter
// * @throws IllegalStateException Configuration parameter undefined
// */
// public static boolean getConfigBooleanValue(ConfigType configType) {
// String value = getConfigStringValue(configType);
//
// return Boolean.parseBoolean(value);
// }
// }
// Path: home-core/src/main/java/com/sismics/util/dbi/DbOpenHelper.java
import com.google.common.base.Strings;
import com.google.common.io.CharStreams;
import com.sismics.home.core.util.ConfigUtil;
import com.sismics.util.ResourceUtil;
import org.skife.jdbi.v2.Handle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.*;
public void open() {
log.info("Opening database and executing incremental updates");
exceptions.clear();
try {
// Check if database is already created
Integer oldVersion = null;
try {
List<Map<String,Object>> resultMap = handle.select("select c.CFG_VALUE_C as ver from T_CONFIG c where c.CFG_ID_C='DB_VERSION'");
if (!resultMap.isEmpty()) {
String oldVersionStr = (String) resultMap.get(0).get("ver");
oldVersion = Integer.parseInt(oldVersionStr);
}
} catch (Exception e) {
if (e.getMessage().contains("not found")) {
log.info("Unable to get database version: Table T_CONFIG not found");
} else {
log.error("Unable to get database version", e);
}
}
if (oldVersion == null) {
// Execute creation script
log.info("Executing initial schema creation script");
onCreate();
oldVersion = 0;
}
// Execute update script | ResourceBundle configBundle = ConfigUtil.getConfigBundle(); |
sismics/home | home-core/src/main/java/com/sismics/home/core/dao/dbi/criteria/SensorSampleCriteria.java | // Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java
// public enum SensorSampleType {
//
// /**
// * Raw sample from sensor input.
// */
// RAW,
//
// /**
// * Sample compacted from all samples from the same minute.
// */
// MINUTE,
//
// /**
// * Sample compacted from all samples from the same hour.
// */
// HOUR,
//
// /**
// * Sample compacted from all samples from the same day.
// */
// DAY
// }
| import com.sismics.home.core.constant.SensorSampleType; | package com.sismics.home.core.dao.dbi.criteria;
/**
* Sensor sample criteria.
*
* @author bgamard
*/
public class SensorSampleCriteria {
/**
* Sensor ID.
*/
private String sensorId;
/**
* Sensor sample type.
*/ | // Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java
// public enum SensorSampleType {
//
// /**
// * Raw sample from sensor input.
// */
// RAW,
//
// /**
// * Sample compacted from all samples from the same minute.
// */
// MINUTE,
//
// /**
// * Sample compacted from all samples from the same hour.
// */
// HOUR,
//
// /**
// * Sample compacted from all samples from the same day.
// */
// DAY
// }
// Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/criteria/SensorSampleCriteria.java
import com.sismics.home.core.constant.SensorSampleType;
package com.sismics.home.core.dao.dbi.criteria;
/**
* Sensor sample criteria.
*
* @author bgamard
*/
public class SensorSampleCriteria {
/**
* Sensor ID.
*/
private String sensorId;
/**
* Sensor sample type.
*/ | private SensorSampleType type; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.