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
|
|---|---|---|---|---|---|---|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateDeserializerTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
|
package io.stardog.stardao.jackson;
public class UpdateDeserializerTest {
@Test
public void testDeserialize() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String json = "{\"name\":\"Marty\",\"birthday\":\"1985-10-26\",\"email\":null,\"country\":\"\"}";
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateDeserializerTest.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
package io.stardog.stardao.jackson;
public class UpdateDeserializerTest {
@Test
public void testDeserialize() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String json = "{\"name\":\"Marty\",\"birthday\":\"1985-10-26\",\"email\":null,\"country\":\"\"}";
|
Update<TestModel> update = mapper.readValue(json, new TypeReference<Update<TestModel>>() {});
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/ObjectIdDeserializer.java
// public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
// @Override
// public ObjectId deserialize(JsonParser parser, DeserializationContext ctx) throws IOException {
// String id = parser.getValueAsString();
// if ("".equals(id)) {
// return null;
// }
// return new ObjectId(id);
// }
// }
|
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.ObjectIdDeserializer;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
|
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that handles serializing special types that we might get back from MongoDB,
* for lossless conversion to POJOs.
*/
public class MongoModule extends SimpleModule {
public MongoModule() {
super();
addSerializer(Decimal128.class, new ToStringSerializer());
addSerializer(ObjectId.class, new ToStringSerializer());
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/ObjectIdDeserializer.java
// public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
// @Override
// public ObjectId deserialize(JsonParser parser, DeserializationContext ctx) throws IOException {
// String id = parser.getValueAsString();
// if ("".equals(id)) {
// return null;
// }
// return new ObjectId(id);
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.ObjectIdDeserializer;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that handles serializing special types that we might get back from MongoDB,
* for lossless conversion to POJOs.
*/
public class MongoModule extends SimpleModule {
public MongoModule() {
super();
addSerializer(Decimal128.class, new ToStringSerializer());
addSerializer(ObjectId.class, new ToStringSerializer());
|
addDeserializer(ObjectId.class, new ObjectIdDeserializer());
|
stardogventures/stardao
|
stardao-core/src/main/java/io/stardog/stardao/jackson/JsonHelper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.Update;
|
package io.stardog.stardao.jackson;
/**
* This helper lets you quickly construct objects for tests, including using single-quotes/unquoted field names
* to make it easier to construct JSON strings inline Java.
*
* It's not intended to be used for production purposes. Just testing.
*/
public class JsonHelper {
public static ObjectMapper MAPPER = new ObjectMapper()
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module());
/**
* Create an object, given a JSON string and a class.
* @param json JSON string
* @param klazz class of object to create
* @param <T> type of object to create
* @return object
*/
public static <T> T obj(String json, Class<T> klazz) {
try {
return MAPPER.readValue(json, klazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T object(String json, Class<T> klazz) {
return obj(json, klazz);
}
/**
* Create an Update object, given the class of the update type
* @param json JSON string
* @param klazz class of the update type
* @param <T> update type
* @return
*/
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/main/java/io/stardog/stardao/jackson/JsonHelper.java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.Update;
package io.stardog.stardao.jackson;
/**
* This helper lets you quickly construct objects for tests, including using single-quotes/unquoted field names
* to make it easier to construct JSON strings inline Java.
*
* It's not intended to be used for production purposes. Just testing.
*/
public class JsonHelper {
public static ObjectMapper MAPPER = new ObjectMapper()
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module());
/**
* Create an object, given a JSON string and a class.
* @param json JSON string
* @param klazz class of object to create
* @param <T> type of object to create
* @return object
*/
public static <T> T obj(String json, Class<T> klazz) {
try {
return MAPPER.readValue(json, klazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T object(String json, Class<T> klazz) {
return obj(json, klazz);
}
/**
* Create an Update object, given the class of the update type
* @param json JSON string
* @param klazz class of the update type
* @param <T> update type
* @return
*/
|
public static <T> Update<T> update(String json, Class<T> klazz) {
|
stardogventures/stardao
|
stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
|
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
|
TestUser created = dao.create(TestUser.builder().name("Ian").build());
TestUser load = dao.loadOpt(created.getId()).get();
assertEquals(load, created);
}
@Test
public void testCreateAndLoadOptPartial() throws Exception {
TestUser created = dao.create(TestUser.builder()
.name("Ian")
.email("ian@example.com")
.active(true)
.build());
TestUser load = dao.loadOpt(created.getId(), ImmutableSet.of("name", "active")).get();
assertEquals("Ian", load.getName());
assertNull(load.getEmail());
assertTrue(load.getActive());
}
@Test
public void testLoadByQuery() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
TestUser load = dao.loadByQuery(new Document("email", "ian@example.com"));
assertEquals(load, created);
try {
dao.loadByQuery(new Document("email", "notfound@example.com"));
fail("Expected DataNotFoundException");
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
// Path: stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
TestUser created = dao.create(TestUser.builder().name("Ian").build());
TestUser load = dao.loadOpt(created.getId()).get();
assertEquals(load, created);
}
@Test
public void testCreateAndLoadOptPartial() throws Exception {
TestUser created = dao.create(TestUser.builder()
.name("Ian")
.email("ian@example.com")
.active(true)
.build());
TestUser load = dao.loadOpt(created.getId(), ImmutableSet.of("name", "active")).get();
assertEquals("Ian", load.getName());
assertNull(load.getEmail());
assertTrue(load.getActive());
}
@Test
public void testLoadByQuery() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
TestUser load = dao.loadByQuery(new Document("email", "ian@example.com"));
assertEquals(load, created);
try {
dao.loadByQuery(new Document("email", "notfound@example.com"));
fail("Expected DataNotFoundException");
|
} catch (DataNotFoundException e) {
|
stardogventures/stardao
|
stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
|
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
|
fail("Expected DataNotFoundException");
} catch (DataNotFoundException e) {
assertEquals("TestUser not found", e.getMessage());
}
}
@Test
public void testLoadByQuerySort() throws Exception {
TestUser created1 = dao.create(TestUser.builder().name("Ian").email("ian1@example.com").build());
TestUser created2 = dao.create(TestUser.builder().name("Ian").email("ian2@example.com").build());
TestUser load = dao.loadByQuery(new Document("name", "Ian"), new Document("email", 1));
assertEquals(created1, load);
}
@Test
public void testLoadByQueryOpt() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
TestUser load = dao.loadByQueryOpt(new Document("email", "ian@example.com")).get();
assertEquals(load, created);
assertFalse(dao.loadByQueryOpt(new Document("email", "bob@example.com")).isPresent());
}
@Test
public void testFindByQuery() throws Exception {
TestUser created1 = dao.create(TestUser.builder().name("Ian").email("ian1@example.com").build());
TestUser created2 = dao.create(TestUser.builder().name("Ian").email("ian2@example.com").build());
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
// Path: stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
fail("Expected DataNotFoundException");
} catch (DataNotFoundException e) {
assertEquals("TestUser not found", e.getMessage());
}
}
@Test
public void testLoadByQuerySort() throws Exception {
TestUser created1 = dao.create(TestUser.builder().name("Ian").email("ian1@example.com").build());
TestUser created2 = dao.create(TestUser.builder().name("Ian").email("ian2@example.com").build());
TestUser load = dao.loadByQuery(new Document("name", "Ian"), new Document("email", 1));
assertEquals(created1, load);
}
@Test
public void testLoadByQueryOpt() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
TestUser load = dao.loadByQueryOpt(new Document("email", "ian@example.com")).get();
assertEquals(load, created);
assertFalse(dao.loadByQueryOpt(new Document("email", "bob@example.com")).isPresent());
}
@Test
public void testFindByQuery() throws Exception {
TestUser created1 = dao.create(TestUser.builder().name("Ian").email("ian1@example.com").build());
TestUser created2 = dao.create(TestUser.builder().name("Ian").email("ian2@example.com").build());
|
Results<TestUser,ObjectId> results = dao.findByQuery(new Document("name", "Ian"), new Document("email", -1));
|
stardogventures/stardao
|
stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
|
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
|
@Test
public void testCreate() throws Exception {
Instant now = Instant.now();
ObjectId creatorId = new ObjectId();
TestUser created = dao.create(TestUser.builder().name("Ian").build(), now, creatorId);
assertNotNull(created.getId());
assertEquals("Ian", created.getName());
assertEquals(creatorId, created.getCreateId());
assertEquals(now.toEpochMilli(), created.getCreateAt().toEpochMilli());
}
@Test
public void testCreateWithFieldsInPlace() throws Exception {
Instant now = Instant.now();
ObjectId creatorId = new ObjectId();
TestUser created = dao.create(TestUser.builder().name("Ian").createAt(now).createId(creatorId).build(), Instant.now(), new ObjectId());
assertNotNull(created.getId());
assertEquals("Ian", created.getName());
assertEquals(creatorId, created.getCreateId());
assertEquals(now.toEpochMilli(), created.getCreateAt().toEpochMilli());
}
@Test
public void testUpdate() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
ObjectId updateBy = new ObjectId();
Instant now = Instant.now();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataNotFoundException.java
// public class DataNotFoundException extends DataException {
// public DataNotFoundException(String message) {
// super(message);
// }
// }
// Path: stardao-mongodb/src/test/java/io/stardog/stardao/mongodb/AbstractMongoDaoTest.java
import com.github.fakemongo.Fongo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.exceptions.DataNotFoundException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.geojson.Point;
import org.junit.Before;
import org.junit.Test;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.Optional;
import static org.junit.Assert.*;
@Test
public void testCreate() throws Exception {
Instant now = Instant.now();
ObjectId creatorId = new ObjectId();
TestUser created = dao.create(TestUser.builder().name("Ian").build(), now, creatorId);
assertNotNull(created.getId());
assertEquals("Ian", created.getName());
assertEquals(creatorId, created.getCreateId());
assertEquals(now.toEpochMilli(), created.getCreateAt().toEpochMilli());
}
@Test
public void testCreateWithFieldsInPlace() throws Exception {
Instant now = Instant.now();
ObjectId creatorId = new ObjectId();
TestUser created = dao.create(TestUser.builder().name("Ian").createAt(now).createId(creatorId).build(), Instant.now(), new ObjectId());
assertNotNull(created.getId());
assertEquals("Ian", created.getName());
assertEquals(creatorId, created.getCreateId());
assertEquals(now.toEpochMilli(), created.getCreateAt().toEpochMilli());
}
@Test
public void testUpdate() throws Exception {
TestUser created = dao.create(TestUser.builder().name("Ian").email("ian@example.com").build());
ObjectId updateBy = new ObjectId();
Instant now = Instant.now();
|
Update<TestUser> update = Update.of(
|
stardogventures/stardao
|
stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/TestModel.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
|
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import io.stardog.stardao.annotations.CreatedAt;
import io.stardog.stardao.annotations.CreatedBy;
import io.stardog.stardao.annotations.UpdatedAt;
import io.stardog.stardao.annotations.UpdatedBy;
import io.stardog.stardao.annotations.Id;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.annotations.Updatable;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.annotation.Nullable;
import javax.validation.constraints.Pattern;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.dynamodb;
@AutoValue
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
public abstract class TestModel {
@Nullable
@Id
public abstract UUID getId();
@Nullable
@Updatable
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
// Path: stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/TestModel.java
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import io.stardog.stardao.annotations.CreatedAt;
import io.stardog.stardao.annotations.CreatedBy;
import io.stardog.stardao.annotations.UpdatedAt;
import io.stardog.stardao.annotations.UpdatedBy;
import io.stardog.stardao.annotations.Id;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.annotations.Updatable;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.annotation.Nullable;
import javax.validation.constraints.Pattern;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.dynamodb;
@AutoValue
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
public abstract class TestModel {
@Nullable
@Id
public abstract UUID getId();
@Nullable
@Updatable
|
@NotEmpty(groups = Required.class)
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/jackson/JsonHelperTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jackson;
public class JsonHelperTest {
@Test
public void testObject() throws Exception {
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/jackson/JsonHelperTest.java
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
package io.stardog.stardao.jackson;
public class JsonHelperTest {
@Test
public void testObject() throws Exception {
|
TestModel object = JsonHelper.object("{'name':'Ian','active':true}", TestModel.class);
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/jackson/JsonHelperTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jackson;
public class JsonHelperTest {
@Test
public void testObject() throws Exception {
TestModel object = JsonHelper.object("{'name':'Ian','active':true}", TestModel.class);
assertEquals("Ian", object.getName());
}
@Test
public void testUpdate() throws Exception {
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/jackson/JsonHelperTest.java
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
package io.stardog.stardao.jackson;
public class JsonHelperTest {
@Test
public void testObject() throws Exception {
TestModel object = JsonHelper.object("{'name':'Ian','active':true}", TestModel.class);
assertEquals("Ian", object.getName());
}
@Test
public void testUpdate() throws Exception {
|
Update<TestModel> update = JsonHelper.update("{'name':'Ian','active':true,email:null}", TestModel.class);
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
|
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import io.stardog.stardao.annotations.CreatedAt;
import io.stardog.stardao.annotations.CreatedBy;
import io.stardog.stardao.annotations.Id;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.annotations.Updatable;
import io.stardog.stardao.annotations.UpdatedAt;
import io.stardog.stardao.annotations.UpdatedBy;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.annotation.Nullable;
import javax.validation.constraints.Pattern;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.core;
@AutoValue
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
public abstract class TestModel {
@Nullable
@Id
public abstract UUID getId();
@Nullable
@Updatable
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import io.stardog.stardao.annotations.CreatedAt;
import io.stardog.stardao.annotations.CreatedBy;
import io.stardog.stardao.annotations.Id;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.annotations.Updatable;
import io.stardog.stardao.annotations.UpdatedAt;
import io.stardog.stardao.annotations.UpdatedBy;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.annotation.Nullable;
import javax.validation.constraints.Pattern;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.core;
@AutoValue
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
public abstract class TestModel {
@Nullable
@Id
public abstract UUID getId();
@Nullable
@Updatable
|
@NotEmpty(groups = Required.class)
|
stardogventures/stardao
|
stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/AbstractDynamoDaoTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.KeyAttribute;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
|
dao.create(TestModel.builder()
.name("Ian White")
.email("ian@example.com")
.build());
dao.create(TestModel.builder()
.name("Bob Smith")
.email("bob@example.com")
.build());
int count = 0;
for (TestModel m : dao.iterateAll()) {
count++;
}
assertEquals(2, count);
}
private void populateSampleData() {
dao.create(TestModel.builder()
.name("Ian White")
.email("ian@example.com")
.build());
dao.create(TestModel.builder()
.name("Bob Smith")
.email("bob@example.com")
.build());
}
@Test
public void testScanAll() throws Exception {
populateSampleData();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/AbstractDynamoDaoTest.java
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.KeyAttribute;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
dao.create(TestModel.builder()
.name("Ian White")
.email("ian@example.com")
.build());
dao.create(TestModel.builder()
.name("Bob Smith")
.email("bob@example.com")
.build());
int count = 0;
for (TestModel m : dao.iterateAll()) {
count++;
}
assertEquals(2, count);
}
private void populateSampleData() {
dao.create(TestModel.builder()
.name("Ian White")
.email("ian@example.com")
.build());
dao.create(TestModel.builder()
.name("Bob Smith")
.email("bob@example.com")
.build());
}
@Test
public void testScanAll() throws Exception {
populateSampleData();
|
Results<TestModel,UUID> results = dao.scanAll();
|
stardogventures/stardao
|
stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/AbstractDynamoDaoTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.KeyAttribute;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
|
Instant now = Instant.now();
UUID creatorId = UUID.randomUUID();
Item item = dao.toCreateItem(TestModel.builder().name("Ian White").build(), now, creatorId);
assertNotNull(item.get("id"));
assertEquals(creatorId.toString(), item.get("createId"));
assertEquals(new BigDecimal(now.toEpochMilli()), item.get("createAt"));
}
@Test
public void testUpdate() throws Exception {
TestModel model = dao.create(TestModel.builder().name("Ian").build());
dao.update(model.getId(), dao.updateOf(TestModel.builder().name("Rename").build()));
TestModel change = dao.load(model.getId());
assertEquals("Rename", change.getName());
}
@Test
public void testUpdateAndReturn() throws Exception {
TestModel model = dao.create(TestModel.builder().name("Ian").build());
TestModel prev = dao.updateAndReturn(model.getId(), dao.updateOf(TestModel.builder().name("Rename").build()));
assertEquals(model, prev);
TestModel change = dao.load(model.getId());
assertEquals("Rename", change.getName());
}
@Test
public void testToUpdateItemSpec() throws Exception {
UUID updateId = UUID.randomUUID();
UUID updaterId = UUID.randomUUID();
Instant now = Instant.now();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Results.java
// @AutoValue
// public abstract class Results<M,N> {
// @ApiModelProperty(value = "list of results returned", required = true)
// public abstract List<M> getData();
//
// @ApiModelProperty(value = "identifier to return the next item in the sequence")
// public abstract Optional<N> getNext();
//
// public static <M,N> Results<M,N> of(Iterable<M> data) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.empty());
// }
//
// public static <M,N> Results<M,N> of(Iterable<M> data, N next) {
// return new AutoValue_Results<M, N>(ImmutableList.copyOf(data), Optional.ofNullable(next));
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/AbstractDynamoDaoTest.java
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.KeyAttribute;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.Results;
import io.stardog.stardao.core.Update;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
Instant now = Instant.now();
UUID creatorId = UUID.randomUUID();
Item item = dao.toCreateItem(TestModel.builder().name("Ian White").build(), now, creatorId);
assertNotNull(item.get("id"));
assertEquals(creatorId.toString(), item.get("createId"));
assertEquals(new BigDecimal(now.toEpochMilli()), item.get("createAt"));
}
@Test
public void testUpdate() throws Exception {
TestModel model = dao.create(TestModel.builder().name("Ian").build());
dao.update(model.getId(), dao.updateOf(TestModel.builder().name("Rename").build()));
TestModel change = dao.load(model.getId());
assertEquals("Rename", change.getName());
}
@Test
public void testUpdateAndReturn() throws Exception {
TestModel model = dao.create(TestModel.builder().name("Ian").build());
TestModel prev = dao.updateAndReturn(model.getId(), dao.updateOf(TestModel.builder().name("Rename").build()));
assertEquals(model, prev);
TestModel change = dao.load(model.getId());
assertEquals("Rename", change.getName());
}
@Test
public void testToUpdateItemSpec() throws Exception {
UUID updateId = UUID.randomUUID();
UUID updaterId = UUID.randomUUID();
Instant now = Instant.now();
|
Update<TestModel> update = Update.of(
|
stardogventures/stardao
|
stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
|
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
|
package io.stardog.stardao.validation;
public class ModelValidator {
private final Validator validator;
private final ObjectMapper mapper;
public ModelValidator(Validator validator, ObjectMapper mapper) {
this.validator = validator;
this.mapper = mapper;
}
public List<ValidationError> getModelValidationErrors(Object object, Class validationGroup) {
if (object == null) {
return ImmutableList.of(ValidationError.of("", "object is null"));
}
Set<ConstraintViolation<Object>> violations = validator.validate(object, validationGroup);
Set<String> errorFields = new HashSet<>();
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
for (ConstraintViolation<Object> v : violations) {
String field = v.getPropertyPath().toString();
if (!errorFields.contains(field)) {
errors.add(ValidationError.of(field, v.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate a user-sourced create partial. Ensure that:
* - the create is only touching @Updatable fields
* - all non-optional @Updatable fields are being touched
* - the object otherwise passes validation
* @param create object to create
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
package io.stardog.stardao.validation;
public class ModelValidator {
private final Validator validator;
private final ObjectMapper mapper;
public ModelValidator(Validator validator, ObjectMapper mapper) {
this.validator = validator;
this.mapper = mapper;
}
public List<ValidationError> getModelValidationErrors(Object object, Class validationGroup) {
if (object == null) {
return ImmutableList.of(ValidationError.of("", "object is null"));
}
Set<ConstraintViolation<Object>> violations = validator.validate(object, validationGroup);
Set<String> errorFields = new HashSet<>();
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
for (ConstraintViolation<Object> v : violations) {
String field = v.getPropertyPath().toString();
if (!errorFields.contains(field)) {
errors.add(ValidationError.of(field, v.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate a user-sourced create partial. Ensure that:
* - the create is only touching @Updatable fields
* - all non-optional @Updatable fields are being touched
* - the object otherwise passes validation
* @param create object to create
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
|
public List<ValidationError> getCreateValidationErrors(Object create, FieldData fieldData) {
|
stardogventures/stardao
|
stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
|
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
|
Set<String> errorFields = new HashSet<>();
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
for (ConstraintViolation<Object> v : violations) {
String field = v.getPropertyPath().toString();
if (!errorFields.contains(field)) {
errors.add(ValidationError.of(field, v.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate a user-sourced create partial. Ensure that:
* - the create is only touching @Updatable fields
* - all non-optional @Updatable fields are being touched
* - the object otherwise passes validation
* @param create object to create
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
public List<ValidationError> getCreateValidationErrors(Object create, FieldData fieldData) {
if (create == null) {
return ImmutableList.of(ValidationError.of("", "create is null"));
}
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
Map<String,Object> createMap = mapper.convertValue(create, new TypeReference<Map<String,Object>>() { });
Set<String> createFields = createMap.keySet();
for (String fieldName : createFields) {
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
Set<String> errorFields = new HashSet<>();
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
for (ConstraintViolation<Object> v : violations) {
String field = v.getPropertyPath().toString();
if (!errorFields.contains(field)) {
errors.add(ValidationError.of(field, v.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate a user-sourced create partial. Ensure that:
* - the create is only touching @Updatable fields
* - all non-optional @Updatable fields are being touched
* - the object otherwise passes validation
* @param create object to create
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
public List<ValidationError> getCreateValidationErrors(Object create, FieldData fieldData) {
if (create == null) {
return ImmutableList.of(ValidationError.of("", "create is null"));
}
ImmutableList.Builder<ValidationError> errors = ImmutableList.builder();
Map<String,Object> createMap = mapper.convertValue(create, new TypeReference<Map<String,Object>>() { });
Set<String> createFields = createMap.keySet();
for (String fieldName : createFields) {
|
Field field = fieldData.getMap().get(fieldName);
|
stardogventures/stardao
|
stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
|
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
|
errors.add(ValidationError.of(fieldName, "is not creatable"));
}
}
for (Field field : fieldData.getMap().values()) {
Object value = createMap.get(field.getName());
if (!field.isOptional() && (field.isCreatable() || field.isUpdatable()) && (value == null || "".equals(value))) {
errors.add(ValidationError.of(field.getName(), "is required"));
}
}
Set<ConstraintViolation<Object>> violations = validator.validate(create, Default.class);
Set<String> errorFields = new HashSet<>();
for (ConstraintViolation<?> cv : violations) {
String field = cv.getPropertyPath().toString();
if (createFields.contains(field) && !errorFields.contains(field)) {
errors.add(ValidationError.of(field, cv.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate an user-sourced update. Ensure that:
* - the update is only touching @Updatable fields
* - the update is not unsetting any non-optional fields
* - the fields that are being touched all validate properly
* @param update update
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
errors.add(ValidationError.of(fieldName, "is not creatable"));
}
}
for (Field field : fieldData.getMap().values()) {
Object value = createMap.get(field.getName());
if (!field.isOptional() && (field.isCreatable() || field.isUpdatable()) && (value == null || "".equals(value))) {
errors.add(ValidationError.of(field.getName(), "is required"));
}
}
Set<ConstraintViolation<Object>> violations = validator.validate(create, Default.class);
Set<String> errorFields = new HashSet<>();
for (ConstraintViolation<?> cv : violations) {
String field = cv.getPropertyPath().toString();
if (createFields.contains(field) && !errorFields.contains(field)) {
errors.add(ValidationError.of(field, cv.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
/**
* Validate an user-sourced update. Ensure that:
* - the update is only touching @Updatable fields
* - the update is not unsetting any non-optional fields
* - the fields that are being touched all validate properly
* @param update update
* @param fieldData field data for model
* @return list of validation errors (empty if passes validation)
*/
|
public List<ValidationError> getUpdateValidationErrors(Update<?> update, FieldData fieldData) {
|
stardogventures/stardao
|
stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
|
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
|
// ensure we are only touching @Updatable fields
for (String fieldName : updateFields) {
Field field = fieldData.getMap().get(fieldName);
if (field == null) {
errors.add(ValidationError.of(fieldName, "does not exist"));
} else if (!field.isUpdatable()) {
errors.add(ValidationError.of(fieldName, "is not updatable"));
} else if (!field.isOptional() && update.getRemoveFields().contains(fieldName)) {
errors.add(ValidationError.of(fieldName, "is required"));
}
}
// validate the model -- but ignore fields that aren't being touched
Set<ConstraintViolation<Object>> violations = validator.validate(update.getPartial(), Default.class);
Set<String> errorFields = new HashSet<>();
for (ConstraintViolation<?> cv : violations) {
String field = cv.getPropertyPath().toString();
if (updateFields.contains(field) && !errorFields.contains(field)) {
errors.add(ValidationError.of(field, cv.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
public boolean validateModel(Object model) {
List<ValidationError> errors = getModelValidationErrors(model, Default.class);
if (!errors.isEmpty()) {
|
// Path: stardao-core/src/main/java/io/stardog/stardao/annotations/Required.java
// public interface Required extends Default {
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ModelValidator.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import io.stardog.stardao.annotations.Required;
import io.stardog.stardao.core.Update;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.exceptions.DataValidationException;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
// ensure we are only touching @Updatable fields
for (String fieldName : updateFields) {
Field field = fieldData.getMap().get(fieldName);
if (field == null) {
errors.add(ValidationError.of(fieldName, "does not exist"));
} else if (!field.isUpdatable()) {
errors.add(ValidationError.of(fieldName, "is not updatable"));
} else if (!field.isOptional() && update.getRemoveFields().contains(fieldName)) {
errors.add(ValidationError.of(fieldName, "is required"));
}
}
// validate the model -- but ignore fields that aren't being touched
Set<ConstraintViolation<Object>> violations = validator.validate(update.getPartial(), Default.class);
Set<String> errorFields = new HashSet<>();
for (ConstraintViolation<?> cv : violations) {
String field = cv.getPropertyPath().toString();
if (updateFields.contains(field) && !errorFields.contains(field)) {
errors.add(ValidationError.of(field, cv.getMessage()));
errorFields.add(field);
}
}
return errors.build();
}
public boolean validateModel(Object model) {
List<ValidationError> errors = getModelValidationErrors(model, Default.class);
if (!errors.isEmpty()) {
|
throw new DataValidationException(errors);
|
stardogventures/stardao
|
stardao-auto/src/test/java/io/stardog/stardao/auto/processor/AutoPartialProcessorTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/jackson/JsonHelper.java
// public class JsonHelper {
// public static ObjectMapper MAPPER = new ObjectMapper()
// .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
// .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
// .registerModule(new JavaTimeModule())
// .registerModule(new Jdk8Module());
//
// /**
// * Create an object, given a JSON string and a class.
// * @param json JSON string
// * @param klazz class of object to create
// * @param <T> type of object to create
// * @return object
// */
// public static <T> T obj(String json, Class<T> klazz) {
// try {
// return MAPPER.readValue(json, klazz);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static <T> T object(String json, Class<T> klazz) {
// return obj(json, klazz);
// }
//
// /**
// * Create an Update object, given the class of the update type
// * @param json JSON string
// * @param klazz class of the update type
// * @param <T> update type
// * @return
// */
// public static <T> Update<T> update(String json, Class<T> klazz) {
// try {
// JavaType type = MAPPER.getTypeFactory().constructParametricType(Update.class, klazz);
// return MAPPER.readValue(json, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Turn an object into JSON.
// * @param object object
// * @return JSON string of object
// */
// public static String json(Object object) {
// try {
// return MAPPER.writeValueAsString(object);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.stardog.stardao.jackson.JsonHelper;
import org.bson.types.ObjectId;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.Optional;
import static org.junit.Assert.*;
|
}
@Test
public void testGeneratedOf() throws Exception {
TestUser user = TestUser.builder().id(new ObjectId()).name("Bob Jones").age(42).email("example@example.com").build();
PartialTestUser partial = PartialTestUser.of(user);
assertEquals("Bob Jones", partial.getName().get());
assertEquals(new Integer(42), partial.getAge().get());
assertEquals("example@example.com", partial.getEmail().get());
}
@Test
public void testJackson() throws Exception {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new Jdk8Module());
PartialTestUser user = PartialTestUser.builder().age(Optional.of(36)).build();
String json = mapper.writeValueAsString(user);
assertEquals("{\"age\":36}", json);
user = mapper.readValue("{\"age\":36,\"email\":\"example@example.com\"}", PartialTestUser.class);
assertEquals(new Integer(36), user.getAge().get());
assertEquals("example@example.com", user.getEmail().get());
user = mapper.readValue("{\"name\":\"Bob\"}", PartialTestUser.class);
assertEquals("Bob", user.getName().get());
}
@Test
public void testJsonHelper() throws Exception {
|
// Path: stardao-core/src/main/java/io/stardog/stardao/jackson/JsonHelper.java
// public class JsonHelper {
// public static ObjectMapper MAPPER = new ObjectMapper()
// .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
// .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
// .registerModule(new JavaTimeModule())
// .registerModule(new Jdk8Module());
//
// /**
// * Create an object, given a JSON string and a class.
// * @param json JSON string
// * @param klazz class of object to create
// * @param <T> type of object to create
// * @return object
// */
// public static <T> T obj(String json, Class<T> klazz) {
// try {
// return MAPPER.readValue(json, klazz);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public static <T> T object(String json, Class<T> klazz) {
// return obj(json, klazz);
// }
//
// /**
// * Create an Update object, given the class of the update type
// * @param json JSON string
// * @param klazz class of the update type
// * @param <T> update type
// * @return
// */
// public static <T> Update<T> update(String json, Class<T> klazz) {
// try {
// JavaType type = MAPPER.getTypeFactory().constructParametricType(Update.class, klazz);
// return MAPPER.readValue(json, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Turn an object into JSON.
// * @param object object
// * @return JSON string of object
// */
// public static String json(Object object) {
// try {
// return MAPPER.writeValueAsString(object);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: stardao-auto/src/test/java/io/stardog/stardao/auto/processor/AutoPartialProcessorTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.stardog.stardao.jackson.JsonHelper;
import org.bson.types.ObjectId;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.Optional;
import static org.junit.Assert.*;
}
@Test
public void testGeneratedOf() throws Exception {
TestUser user = TestUser.builder().id(new ObjectId()).name("Bob Jones").age(42).email("example@example.com").build();
PartialTestUser partial = PartialTestUser.of(user);
assertEquals("Bob Jones", partial.getName().get());
assertEquals(new Integer(42), partial.getAge().get());
assertEquals("example@example.com", partial.getEmail().get());
}
@Test
public void testJackson() throws Exception {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new Jdk8Module());
PartialTestUser user = PartialTestUser.builder().age(Optional.of(36)).build();
String json = mapper.writeValueAsString(user);
assertEquals("{\"age\":36}", json);
user = mapper.readValue("{\"age\":36,\"email\":\"example@example.com\"}", PartialTestUser.class);
assertEquals(new Integer(36), user.getAge().get());
assertEquals("example@example.com", user.getEmail().get());
user = mapper.readValue("{\"name\":\"Bob\"}", PartialTestUser.class);
assertEquals("Bob", user.getName().get());
}
@Test
public void testJsonHelper() throws Exception {
|
PartialTestUser user = JsonHelper.object("{age:36}", PartialTestUser.class);
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/core/field/FieldScannerTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
|
import io.stardog.stardao.core.TestModel;
import org.junit.Test;
import java.lang.reflect.Method;
import java.time.Instant;
import static org.junit.Assert.*;
|
package io.stardog.stardao.core.field;
public class FieldScannerTest {
@Test
public void testScanAnnotations() throws Exception {
FieldScanner scanner = new FieldScanner();
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/core/field/FieldScannerTest.java
import io.stardog.stardao.core.TestModel;
import org.junit.Test;
import java.lang.reflect.Method;
import java.time.Instant;
import static org.junit.Assert.*;
package io.stardog.stardao.core.field;
public class FieldScannerTest {
@Test
public void testScanAnnotations() throws Exception {
FieldScanner scanner = new FieldScanner();
|
FieldData data = scanner.scanAnnotations(TestModel.class);
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
|
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
|
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
|
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
|
addSerializer(Instant.class, new InstantExtJsonSerializer());
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
|
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
addSerializer(Instant.class, new InstantExtJsonSerializer());
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
addSerializer(Instant.class, new InstantExtJsonSerializer());
|
addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
|
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
|
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
addSerializer(Instant.class, new InstantExtJsonSerializer());
addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
|
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/BigDecimalExtJsonSerializer.java
// public class BigDecimalExtJsonSerializer extends JsonSerializer<BigDecimal> {
// @Override
// public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$numberDecimal", bigDecimal.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/InstantExtJsonSerializer.java
// public class InstantExtJsonSerializer extends JsonSerializer<Instant> {
// @Override
// public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeNumberField("$date", instant.toEpochMilli());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/ObjectIdExtJsonSerializer.java
// public class ObjectIdExtJsonSerializer extends JsonSerializer<ObjectId> {
// @Override
// public void serialize(ObjectId objectId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$oid", objectId.toString());
// jsonGenerator.writeEndObject();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/serializers/extjson/UUIDExtJsonSerializer.java
// public class UUIDExtJsonSerializer extends JsonSerializer<UUID> {
// @Override
// public void serialize(UUID uuid, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
// ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
// uuidBytes.putLong(uuid.getMostSignificantBits());
// uuidBytes.putLong(uuid.getLeastSignificantBits());
//
// jsonGenerator.writeStartObject();
// jsonGenerator.writeStringField("$binary", Base64.getEncoder().encodeToString(uuidBytes.array()));
// jsonGenerator.writeStringField("$type", "4");
// jsonGenerator.writeEndObject();
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.BigDecimalExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.InstantExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.ObjectIdExtJsonSerializer;
import io.stardog.stardao.mongodb.mapper.jackson.serializers.extjson.UUIDExtJsonSerializer;
import org.bson.types.ObjectId;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
package io.stardog.stardao.mongodb.mapper.jackson.modules;
/**
* A Jackson module that can serialize objects into "extended JSON", MongoDB's custom JSON format.
* From extended JSON, we can transform into a Mongo BSON document.
*/
public class ExtendedJsonModule extends SimpleModule {
public ExtendedJsonModule() {
super();
addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
addSerializer(Instant.class, new InstantExtJsonSerializer());
addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
|
addSerializer(UUID.class, new UUIDExtJsonSerializer());
|
stardogventures/stardao
|
stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/JacksonItemMapperTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
// public class JacksonItemMapper<M> implements ItemMapper<M> {
// private final Class<M> modelClass;
// private final FieldData fieldData;
// private final ObjectMapper objectMapper;
// private final Map<String,String> objectToItemFieldRenames;
// private final Map<String,String> itemToObjectFieldRenames;
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
// this(modelClass, fieldData, new ObjectMapper()
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
// .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule()));
// }
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
// this.modelClass = modelClass;
// this.fieldData = fieldData;
// this.objectMapper = objectMapper;
// this.objectToItemFieldRenames = new HashMap<>();
// this.itemToObjectFieldRenames = new HashMap<>();
// for (Field field : fieldData.getMap().values()) {
// if (!field.getStorageName().equals(field.getName())) {
// objectToItemFieldRenames.put(field.getName(), field.getStorageName());
// itemToObjectFieldRenames.put(field.getStorageName(), field.getName());
// }
// }
// }
//
// public ObjectMapper getObjectMapper() {
// return objectMapper;
// }
//
// /**
// * Map a DynamoDB Item to a POJO, using the Jackson object modelMapper.
// * @param item item to convert to a POJO
// * @return POJO representation of item
// */
// public M toObject(Item item) {
// if (item == null) {
// return null;
// }
// item = renameItem(item, itemToObjectFieldRenames);
// Map<String,Object> map = item.asMap();
// try {
// String json = objectMapper.writeValueAsString(map);
// return objectMapper.readValue(json, modelClass);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// /**
// * Map a POJO to a DynamoDB Item, using the Jackson object modelMapper.
// * @param object POJO to convert to an item
// * @return item representation of POJO
// */
// public Item toItem(Object object) {
// try {
// String json = objectMapper.writeValueAsString(object);
// Item item = Item.fromJSON(json);
//
// // remove any empty strings, since DynamoDB cannot store them
// List<String> removeAttrs = new ArrayList<>();
// for (Map.Entry<String,Object> attr : item.attributes()) {
// if ("".equals(attr.getValue())) {
// removeAttrs.add(attr.getKey());
// }
// }
// for (String attrName : removeAttrs) {
// item.removeAttribute(attrName);
// }
//
// item = renameItem(item, objectToItemFieldRenames);
// return item;
// } catch (JsonProcessingException e) {
// throw new IllegalArgumentException("Unable to convert " + object, e);
// }
// }
//
// protected Item renameItem(Item item, Map<String,String> renames) {
// Map<String,Object> map = item.asMap();
// Item renamedItem = new Item();
// for (String key : map.keySet()) {
// String renamedKey = renames.getOrDefault(key, key);
// if (renamedKey != null && !"".equals(renamedKey)) {
// renamedItem.with(renamedKey, item.get(key));
// }
// }
// return renamedItem;
// }
// }
|
import com.amazonaws.services.dynamodbv2.document.Item;
import com.google.common.collect.ImmutableMap;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.dynamodb.mapper.JacksonItemMapper;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
|
package io.stardog.stardao.dynamodb;
public class JacksonItemMapperTest {
@Test
public void testToItem() throws Exception {
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
// public class JacksonItemMapper<M> implements ItemMapper<M> {
// private final Class<M> modelClass;
// private final FieldData fieldData;
// private final ObjectMapper objectMapper;
// private final Map<String,String> objectToItemFieldRenames;
// private final Map<String,String> itemToObjectFieldRenames;
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
// this(modelClass, fieldData, new ObjectMapper()
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
// .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule()));
// }
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
// this.modelClass = modelClass;
// this.fieldData = fieldData;
// this.objectMapper = objectMapper;
// this.objectToItemFieldRenames = new HashMap<>();
// this.itemToObjectFieldRenames = new HashMap<>();
// for (Field field : fieldData.getMap().values()) {
// if (!field.getStorageName().equals(field.getName())) {
// objectToItemFieldRenames.put(field.getName(), field.getStorageName());
// itemToObjectFieldRenames.put(field.getStorageName(), field.getName());
// }
// }
// }
//
// public ObjectMapper getObjectMapper() {
// return objectMapper;
// }
//
// /**
// * Map a DynamoDB Item to a POJO, using the Jackson object modelMapper.
// * @param item item to convert to a POJO
// * @return POJO representation of item
// */
// public M toObject(Item item) {
// if (item == null) {
// return null;
// }
// item = renameItem(item, itemToObjectFieldRenames);
// Map<String,Object> map = item.asMap();
// try {
// String json = objectMapper.writeValueAsString(map);
// return objectMapper.readValue(json, modelClass);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// /**
// * Map a POJO to a DynamoDB Item, using the Jackson object modelMapper.
// * @param object POJO to convert to an item
// * @return item representation of POJO
// */
// public Item toItem(Object object) {
// try {
// String json = objectMapper.writeValueAsString(object);
// Item item = Item.fromJSON(json);
//
// // remove any empty strings, since DynamoDB cannot store them
// List<String> removeAttrs = new ArrayList<>();
// for (Map.Entry<String,Object> attr : item.attributes()) {
// if ("".equals(attr.getValue())) {
// removeAttrs.add(attr.getKey());
// }
// }
// for (String attrName : removeAttrs) {
// item.removeAttribute(attrName);
// }
//
// item = renameItem(item, objectToItemFieldRenames);
// return item;
// } catch (JsonProcessingException e) {
// throw new IllegalArgumentException("Unable to convert " + object, e);
// }
// }
//
// protected Item renameItem(Item item, Map<String,String> renames) {
// Map<String,Object> map = item.asMap();
// Item renamedItem = new Item();
// for (String key : map.keySet()) {
// String renamedKey = renames.getOrDefault(key, key);
// if (renamedKey != null && !"".equals(renamedKey)) {
// renamedItem.with(renamedKey, item.get(key));
// }
// }
// return renamedItem;
// }
// }
// Path: stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/JacksonItemMapperTest.java
import com.amazonaws.services.dynamodbv2.document.Item;
import com.google.common.collect.ImmutableMap;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.dynamodb.mapper.JacksonItemMapper;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
package io.stardog.stardao.dynamodb;
public class JacksonItemMapperTest {
@Test
public void testToItem() throws Exception {
|
JacksonItemMapper<TestObject> mapper = new JacksonItemMapper<>(TestObject.class, FieldData.builder().map(ImmutableMap.of()).build());
|
stardogventures/stardao
|
stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/JacksonItemMapperTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
// public class JacksonItemMapper<M> implements ItemMapper<M> {
// private final Class<M> modelClass;
// private final FieldData fieldData;
// private final ObjectMapper objectMapper;
// private final Map<String,String> objectToItemFieldRenames;
// private final Map<String,String> itemToObjectFieldRenames;
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
// this(modelClass, fieldData, new ObjectMapper()
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
// .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule()));
// }
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
// this.modelClass = modelClass;
// this.fieldData = fieldData;
// this.objectMapper = objectMapper;
// this.objectToItemFieldRenames = new HashMap<>();
// this.itemToObjectFieldRenames = new HashMap<>();
// for (Field field : fieldData.getMap().values()) {
// if (!field.getStorageName().equals(field.getName())) {
// objectToItemFieldRenames.put(field.getName(), field.getStorageName());
// itemToObjectFieldRenames.put(field.getStorageName(), field.getName());
// }
// }
// }
//
// public ObjectMapper getObjectMapper() {
// return objectMapper;
// }
//
// /**
// * Map a DynamoDB Item to a POJO, using the Jackson object modelMapper.
// * @param item item to convert to a POJO
// * @return POJO representation of item
// */
// public M toObject(Item item) {
// if (item == null) {
// return null;
// }
// item = renameItem(item, itemToObjectFieldRenames);
// Map<String,Object> map = item.asMap();
// try {
// String json = objectMapper.writeValueAsString(map);
// return objectMapper.readValue(json, modelClass);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// /**
// * Map a POJO to a DynamoDB Item, using the Jackson object modelMapper.
// * @param object POJO to convert to an item
// * @return item representation of POJO
// */
// public Item toItem(Object object) {
// try {
// String json = objectMapper.writeValueAsString(object);
// Item item = Item.fromJSON(json);
//
// // remove any empty strings, since DynamoDB cannot store them
// List<String> removeAttrs = new ArrayList<>();
// for (Map.Entry<String,Object> attr : item.attributes()) {
// if ("".equals(attr.getValue())) {
// removeAttrs.add(attr.getKey());
// }
// }
// for (String attrName : removeAttrs) {
// item.removeAttribute(attrName);
// }
//
// item = renameItem(item, objectToItemFieldRenames);
// return item;
// } catch (JsonProcessingException e) {
// throw new IllegalArgumentException("Unable to convert " + object, e);
// }
// }
//
// protected Item renameItem(Item item, Map<String,String> renames) {
// Map<String,Object> map = item.asMap();
// Item renamedItem = new Item();
// for (String key : map.keySet()) {
// String renamedKey = renames.getOrDefault(key, key);
// if (renamedKey != null && !"".equals(renamedKey)) {
// renamedItem.with(renamedKey, item.get(key));
// }
// }
// return renamedItem;
// }
// }
|
import com.amazonaws.services.dynamodbv2.document.Item;
import com.google.common.collect.ImmutableMap;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.dynamodb.mapper.JacksonItemMapper;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
|
package io.stardog.stardao.dynamodb;
public class JacksonItemMapperTest {
@Test
public void testToItem() throws Exception {
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
// public class JacksonItemMapper<M> implements ItemMapper<M> {
// private final Class<M> modelClass;
// private final FieldData fieldData;
// private final ObjectMapper objectMapper;
// private final Map<String,String> objectToItemFieldRenames;
// private final Map<String,String> itemToObjectFieldRenames;
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
// this(modelClass, fieldData, new ObjectMapper()
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
// .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
// .registerModule(new Jdk8Module())
// .registerModule(new JavaTimeModule()));
// }
//
// public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
// this.modelClass = modelClass;
// this.fieldData = fieldData;
// this.objectMapper = objectMapper;
// this.objectToItemFieldRenames = new HashMap<>();
// this.itemToObjectFieldRenames = new HashMap<>();
// for (Field field : fieldData.getMap().values()) {
// if (!field.getStorageName().equals(field.getName())) {
// objectToItemFieldRenames.put(field.getName(), field.getStorageName());
// itemToObjectFieldRenames.put(field.getStorageName(), field.getName());
// }
// }
// }
//
// public ObjectMapper getObjectMapper() {
// return objectMapper;
// }
//
// /**
// * Map a DynamoDB Item to a POJO, using the Jackson object modelMapper.
// * @param item item to convert to a POJO
// * @return POJO representation of item
// */
// public M toObject(Item item) {
// if (item == null) {
// return null;
// }
// item = renameItem(item, itemToObjectFieldRenames);
// Map<String,Object> map = item.asMap();
// try {
// String json = objectMapper.writeValueAsString(map);
// return objectMapper.readValue(json, modelClass);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// /**
// * Map a POJO to a DynamoDB Item, using the Jackson object modelMapper.
// * @param object POJO to convert to an item
// * @return item representation of POJO
// */
// public Item toItem(Object object) {
// try {
// String json = objectMapper.writeValueAsString(object);
// Item item = Item.fromJSON(json);
//
// // remove any empty strings, since DynamoDB cannot store them
// List<String> removeAttrs = new ArrayList<>();
// for (Map.Entry<String,Object> attr : item.attributes()) {
// if ("".equals(attr.getValue())) {
// removeAttrs.add(attr.getKey());
// }
// }
// for (String attrName : removeAttrs) {
// item.removeAttribute(attrName);
// }
//
// item = renameItem(item, objectToItemFieldRenames);
// return item;
// } catch (JsonProcessingException e) {
// throw new IllegalArgumentException("Unable to convert " + object, e);
// }
// }
//
// protected Item renameItem(Item item, Map<String,String> renames) {
// Map<String,Object> map = item.asMap();
// Item renamedItem = new Item();
// for (String key : map.keySet()) {
// String renamedKey = renames.getOrDefault(key, key);
// if (renamedKey != null && !"".equals(renamedKey)) {
// renamedItem.with(renamedKey, item.get(key));
// }
// }
// return renamedItem;
// }
// }
// Path: stardao-dynamodb/src/test/java/io/stardog/stardao/dynamodb/JacksonItemMapperTest.java
import com.amazonaws.services.dynamodbv2.document.Item;
import com.google.common.collect.ImmutableMap;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.dynamodb.mapper.JacksonItemMapper;
import org.junit.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
package io.stardog.stardao.dynamodb;
public class JacksonItemMapperTest {
@Test
public void testToItem() throws Exception {
|
JacksonItemMapper<TestObject> mapper = new JacksonItemMapper<>(TestObject.class, FieldData.builder().map(ImmutableMap.of()).build());
|
stardogventures/stardao
|
stardao-jersey/src/test/java/io/stardog/stardao/jersey/exceptionmappers/DataValidationExceptionMapperTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ValidationError.java
// @AutoValue
// public abstract class ValidationError {
// public abstract String getField();
// public abstract String getMessage();
//
// public static ValidationError of(String field, String message) {
// return new AutoValue_ValidationError(field, message);
// }
//
// @Override
// public String toString() {
// return getField() + ": " + getMessage();
// }
// }
|
import io.stardog.stardao.exceptions.DataValidationException;
import io.stardog.stardao.validation.ValidationError;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jersey.exceptionmappers;
public class DataValidationExceptionMapperTest {
@Test
@SuppressWarnings("unchecked")
public void toResponse() throws Exception {
DataValidationExceptionMapper mapper = new DataValidationExceptionMapper();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ValidationError.java
// @AutoValue
// public abstract class ValidationError {
// public abstract String getField();
// public abstract String getMessage();
//
// public static ValidationError of(String field, String message) {
// return new AutoValue_ValidationError(field, message);
// }
//
// @Override
// public String toString() {
// return getField() + ": " + getMessage();
// }
// }
// Path: stardao-jersey/src/test/java/io/stardog/stardao/jersey/exceptionmappers/DataValidationExceptionMapperTest.java
import io.stardog.stardao.exceptions.DataValidationException;
import io.stardog.stardao.validation.ValidationError;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
package io.stardog.stardao.jersey.exceptionmappers;
public class DataValidationExceptionMapperTest {
@Test
@SuppressWarnings("unchecked")
public void toResponse() throws Exception {
DataValidationExceptionMapper mapper = new DataValidationExceptionMapper();
|
DataValidationException exception = new DataValidationException(Arrays.asList(ValidationError.of("field", "is invalid")));
|
stardogventures/stardao
|
stardao-jersey/src/test/java/io/stardog/stardao/jersey/exceptionmappers/DataValidationExceptionMapperTest.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ValidationError.java
// @AutoValue
// public abstract class ValidationError {
// public abstract String getField();
// public abstract String getMessage();
//
// public static ValidationError of(String field, String message) {
// return new AutoValue_ValidationError(field, message);
// }
//
// @Override
// public String toString() {
// return getField() + ": " + getMessage();
// }
// }
|
import io.stardog.stardao.exceptions.DataValidationException;
import io.stardog.stardao.validation.ValidationError;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jersey.exceptionmappers;
public class DataValidationExceptionMapperTest {
@Test
@SuppressWarnings("unchecked")
public void toResponse() throws Exception {
DataValidationExceptionMapper mapper = new DataValidationExceptionMapper();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/exceptions/DataValidationException.java
// public class DataValidationException extends DataException {
// private final List<ValidationError> errors;
//
// public DataValidationException(List<ValidationError> errors) {
// this.errors = errors;
// }
//
// public List<ValidationError> getErrors() {
// return errors;
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder();
// for (ValidationError error : errors) {
// sb.append(error.toString());
// sb.append("; ");
// }
// return sb.toString().substring(0, sb.toString().length()-2);
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/validation/ValidationError.java
// @AutoValue
// public abstract class ValidationError {
// public abstract String getField();
// public abstract String getMessage();
//
// public static ValidationError of(String field, String message) {
// return new AutoValue_ValidationError(field, message);
// }
//
// @Override
// public String toString() {
// return getField() + ": " + getMessage();
// }
// }
// Path: stardao-jersey/src/test/java/io/stardog/stardao/jersey/exceptionmappers/DataValidationExceptionMapperTest.java
import io.stardog.stardao.exceptions.DataValidationException;
import io.stardog.stardao.validation.ValidationError;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
package io.stardog.stardao.jersey.exceptionmappers;
public class DataValidationExceptionMapperTest {
@Test
@SuppressWarnings("unchecked")
public void toResponse() throws Exception {
DataValidationExceptionMapper mapper = new DataValidationExceptionMapper();
|
DataValidationException exception = new DataValidationException(Arrays.asList(ValidationError.of("field", "is invalid")));
|
stardogventures/stardao
|
stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
|
import com.amazonaws.services.dynamodbv2.document.Item;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
|
package io.stardog.stardao.dynamodb.mapper;
public class JacksonItemMapper<M> implements ItemMapper<M> {
private final Class<M> modelClass;
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
import com.amazonaws.services.dynamodbv2.document.Item;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package io.stardog.stardao.dynamodb.mapper;
public class JacksonItemMapper<M> implements ItemMapper<M> {
private final Class<M> modelClass;
|
private final FieldData fieldData;
|
stardogventures/stardao
|
stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
|
import com.amazonaws.services.dynamodbv2.document.Item;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
|
package io.stardog.stardao.dynamodb.mapper;
public class JacksonItemMapper<M> implements ItemMapper<M> {
private final Class<M> modelClass;
private final FieldData fieldData;
private final ObjectMapper objectMapper;
private final Map<String,String> objectToItemFieldRenames;
private final Map<String,String> itemToObjectFieldRenames;
public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
this(modelClass, fieldData, new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule()));
}
public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
this.modelClass = modelClass;
this.fieldData = fieldData;
this.objectMapper = objectMapper;
this.objectToItemFieldRenames = new HashMap<>();
this.itemToObjectFieldRenames = new HashMap<>();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/JacksonItemMapper.java
import com.amazonaws.services.dynamodbv2.document.Item;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package io.stardog.stardao.dynamodb.mapper;
public class JacksonItemMapper<M> implements ItemMapper<M> {
private final Class<M> modelClass;
private final FieldData fieldData;
private final ObjectMapper objectMapper;
private final Map<String,String> objectToItemFieldRenames;
private final Map<String,String> itemToObjectFieldRenames;
public JacksonItemMapper(Class<M> modelClass, FieldData fieldData) {
this(modelClass, fieldData, new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule()));
}
public JacksonItemMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper) {
this.modelClass = modelClass;
this.fieldData = fieldData;
this.objectMapper = objectMapper;
this.objectToItemFieldRenames = new HashMap<>();
this.itemToObjectFieldRenames = new HashMap<>();
|
for (Field field : fieldData.getMap().values()) {
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
|
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
|
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
|
.registerModule(new ExtendedJsonModule());
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
|
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
|
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
|
.registerModule(new MongoModule());
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
|
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
|
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new MongoModule());
public JacksonDocumentMapper(Class<M> modelClass) {
this.modelClass = modelClass;
this.objectMapper = DEFAULT_OBJECT_MAPPER;
this.extendedJsonMapper = DEFAULT_EXTENDED_JSON_MAPPER;
this.objectToDocumentFieldRenames = ImmutableMap.of();
this.documentToObjectFieldRenames = ImmutableMap.of();
}
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
package io.stardog.stardao.mongodb.mapper.jackson;
public class JacksonDocumentMapper<M> implements DocumentMapper<M> {
private final Class<M> modelClass;
private final ObjectMapper objectMapper;
private final ObjectMapper extendedJsonMapper;
private final Map<String,String> objectToDocumentFieldRenames;
private final Map<String,String> documentToObjectFieldRenames;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new MongoModule());
public JacksonDocumentMapper(Class<M> modelClass) {
this.modelClass = modelClass;
this.objectMapper = DEFAULT_OBJECT_MAPPER;
this.extendedJsonMapper = DEFAULT_EXTENDED_JSON_MAPPER;
this.objectToDocumentFieldRenames = ImmutableMap.of();
this.documentToObjectFieldRenames = ImmutableMap.of();
}
|
public JacksonDocumentMapper(Class<M> modelClass, FieldData fieldData) {
|
stardogventures/stardao
|
stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
|
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
|
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new MongoModule());
public JacksonDocumentMapper(Class<M> modelClass) {
this.modelClass = modelClass;
this.objectMapper = DEFAULT_OBJECT_MAPPER;
this.extendedJsonMapper = DEFAULT_EXTENDED_JSON_MAPPER;
this.objectToDocumentFieldRenames = ImmutableMap.of();
this.documentToObjectFieldRenames = ImmutableMap.of();
}
public JacksonDocumentMapper(Class<M> modelClass, FieldData fieldData) {
this(modelClass, fieldData, DEFAULT_OBJECT_MAPPER, DEFAULT_EXTENDED_JSON_MAPPER);
}
public JacksonDocumentMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper, ObjectMapper extendedJsonMapper) {
this.modelClass = modelClass;
this.objectMapper = objectMapper;
this.extendedJsonMapper = extendedJsonMapper;
this.objectToDocumentFieldRenames = new HashMap<>();
this.documentToObjectFieldRenames = new HashMap<>();
|
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/Field.java
// @AutoValue
// public abstract class Field {
// public abstract String getName();
// public abstract String getStorageName();
// public abstract boolean isOptional();
// public abstract boolean isCreatable();
// public abstract boolean isUpdatable();
//
// public abstract Field.Builder toBuilder();
// public static Field.Builder builder() { return new AutoValue_Field.Builder(); }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder name(String name);
// public abstract Builder storageName(String storageName);
// public abstract Builder optional(boolean optional);
// public abstract Builder creatable(boolean creatable);
// public abstract Builder updatable(boolean updatable);
// public abstract Field build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/field/FieldData.java
// @AutoValue
// public abstract class FieldData {
// @Nullable
// public abstract Field getId();
// @Nullable
// public abstract Field getCreatedAt();
// @Nullable
// public abstract Field getCreatedBy();
// @Nullable
// public abstract Field getUpdatedAt();
// @Nullable
// public abstract Field getUpdatedBy();
// public abstract Map<String,Field> getMap();
//
// public abstract Builder toBuilder();
// public static FieldData.Builder builder() {
// return new AutoValue_FieldData.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
// public abstract Builder id(Field id);
// public abstract Builder createdAt(Field field);
// public abstract Builder createdBy(Field field);
// public abstract Builder updatedAt(Field field);
// public abstract Builder updatedBy(Field field);
// public abstract Builder map(Map<String,Field> fields);
// public abstract FieldData build();
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/DocumentMapper.java
// public interface DocumentMapper<M> {
// public M toObject(Document document);
// public Document toDocument(M object);
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/ExtendedJsonModule.java
// public class ExtendedJsonModule extends SimpleModule {
// public ExtendedJsonModule() {
// super();
// addSerializer(ObjectId.class, new ObjectIdExtJsonSerializer());
// addSerializer(Instant.class, new InstantExtJsonSerializer());
// addSerializer(BigDecimal.class, new BigDecimalExtJsonSerializer());
// addSerializer(UUID.class, new UUIDExtJsonSerializer());
//
// // local dates should be stored as strings, not arrays
// addSerializer(LocalDate.class, new ToStringSerializer());
// }
// }
//
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/modules/MongoModule.java
// public class MongoModule extends SimpleModule {
// public MongoModule() {
// super();
// addSerializer(Decimal128.class, new ToStringSerializer());
// addSerializer(ObjectId.class, new ToStringSerializer());
// addDeserializer(ObjectId.class, new ObjectIdDeserializer());
// }
// }
// Path: stardao-mongodb/src/main/java/io/stardog/stardao/mongodb/mapper/jackson/JacksonDocumentMapper.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.mongodb.MongoException;
import io.stardog.stardao.core.field.Field;
import io.stardog.stardao.core.field.FieldData;
import io.stardog.stardao.mongodb.mapper.DocumentMapper;
import io.stardog.stardao.mongodb.mapper.jackson.modules.ExtendedJsonModule;
import io.stardog.stardao.mongodb.mapper.jackson.modules.MongoModule;
import org.bson.Document;
import java.util.HashMap;
import java.util.Map;
public final static ObjectMapper DEFAULT_EXTENDED_JSON_MAPPER = new ObjectMapper()
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new ExtendedJsonModule());
public final static ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule())
.registerModule(new Jdk8Module())
.registerModule(new MongoModule());
public JacksonDocumentMapper(Class<M> modelClass) {
this.modelClass = modelClass;
this.objectMapper = DEFAULT_OBJECT_MAPPER;
this.extendedJsonMapper = DEFAULT_EXTENDED_JSON_MAPPER;
this.objectToDocumentFieldRenames = ImmutableMap.of();
this.documentToObjectFieldRenames = ImmutableMap.of();
}
public JacksonDocumentMapper(Class<M> modelClass, FieldData fieldData) {
this(modelClass, fieldData, DEFAULT_OBJECT_MAPPER, DEFAULT_EXTENDED_JSON_MAPPER);
}
public JacksonDocumentMapper(Class<M> modelClass, FieldData fieldData, ObjectMapper objectMapper, ObjectMapper extendedJsonMapper) {
this.modelClass = modelClass;
this.objectMapper = objectMapper;
this.extendedJsonMapper = extendedJsonMapper;
this.objectToDocumentFieldRenames = new HashMap<>();
this.documentToObjectFieldRenames = new HashMap<>();
|
for (Field field : fieldData.getMap().values()) {
|
stardogventures/stardao
|
stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/DynamoIterator.java
|
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/ItemMapper.java
// public interface ItemMapper<M> {
// public M toObject(Item item);
// public Item toItem(M object);
// }
|
import com.amazonaws.services.dynamodbv2.document.Item;
import io.stardog.stardao.dynamodb.mapper.ItemMapper;
import java.util.Iterator;
|
package io.stardog.stardao.dynamodb;
public class DynamoIterator<M> implements Iterator<M> {
private final Iterator<Item> iterator;
|
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/mapper/ItemMapper.java
// public interface ItemMapper<M> {
// public M toObject(Item item);
// public Item toItem(M object);
// }
// Path: stardao-dynamodb/src/main/java/io/stardog/stardao/dynamodb/DynamoIterator.java
import com.amazonaws.services.dynamodbv2.document.Item;
import io.stardog.stardao.dynamodb.mapper.ItemMapper;
import java.util.Iterator;
package io.stardog.stardao.dynamodb;
public class DynamoIterator<M> implements Iterator<M> {
private final Iterator<Item> iterator;
|
private final ItemMapper<M> mapper;
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateSerializerTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jackson;
public class UpdateSerializerTest {
@Test
public void serialize() throws Exception {
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateSerializerTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
package io.stardog.stardao.jackson;
public class UpdateSerializerTest {
@Test
public void serialize() throws Exception {
|
Update<TestModel> update = Update.of(TestModel.builder()
|
stardogventures/stardao
|
stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateSerializerTest.java
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
|
package io.stardog.stardao.jackson;
public class UpdateSerializerTest {
@Test
public void serialize() throws Exception {
|
// Path: stardao-core/src/test/java/io/stardog/stardao/core/TestModel.java
// @AutoValue
// @JsonInclude(JsonInclude.Include.NON_NULL)
// @JsonDeserialize(builder=AutoValue_TestModel.Builder.class)
// public abstract class TestModel {
// @Nullable
// @Id
// public abstract UUID getId();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getName();
//
// @Nullable
// @Updatable
// @Email
// @Pattern(regexp=".+@.+\\..+", message = "invalid email")
// public abstract String getEmail();
//
// @Nullable
// @Updatable
// @NotEmpty(groups = Required.class)
// public abstract String getCountry();
//
// @Nullable
// @Updatable
// @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
// public abstract LocalDate getBirthday();
//
// @Nullable
// @Updatable
// public abstract Boolean getActive();
//
// @Nullable
// @CreatedBy
// public abstract UUID getCreateId();
//
// @Nullable
// @CreatedAt
// public abstract Instant getCreateAt();
//
// @Nullable
// @UpdatedBy
// public abstract UUID getUpdateId();
//
// @Nullable
// @UpdatedAt
// public abstract Instant getUpdateAt();
//
// @Nullable
// public abstract Instant getLoginAt();
//
// public Instant getLoginAt(long millis) {
// return Instant.ofEpochMilli(millis);
// }
//
// public abstract Builder toBuilder();
// public static TestModel.Builder builder() {
// return new AutoValue_TestModel.Builder();
// }
//
// @AutoValue.Builder
// @JsonPOJOBuilder(withPrefix = "")
// public abstract static class Builder {
// public abstract Builder id(UUID id);
// public abstract Builder name(String name);
// public abstract Builder email(String email);
// public abstract Builder country(String state);
// public abstract Builder birthday(LocalDate state);
// public abstract Builder active(Boolean active);
// public abstract Builder createAt(Instant at);
// public abstract Builder createId(UUID id);
// public abstract Builder updateAt(Instant at);
// public abstract Builder updateId(UUID id);
// public abstract Builder loginAt(Instant at);
// public abstract TestModel build();
// }
// }
//
// Path: stardao-core/src/main/java/io/stardog/stardao/core/Update.java
// @AutoValue
// @JsonDeserialize(using = UpdateDeserializer.class)
// @JsonSerialize(using = UpdateSerializer.class)
// public abstract class Update<P> {
// public abstract P getPartial();
// public abstract Set<String> getSetFields();
// public abstract Set<String> getRemoveFields();
//
// public static <T> Update<T> of(T setObject, Set<String> setFields) {
// return new AutoValue_Update<>(setObject, setFields, ImmutableSet.of());
// }
//
// public static <T> Update<T> of(T setObject, Set<String> setFields, Set<String> removeFields) {
// return new AutoValue_Update<>(setObject, setFields, removeFields);
// }
//
// public boolean isEmpty() {
// return getSetFields().isEmpty() && getRemoveFields().isEmpty();
// }
//
// public Set<String> getUpdateFields() {
// return Sets.union(getSetFields(), getRemoveFields());
// }
//
// public boolean isUpdateField(String field) {
// return getSetFields().contains(field) || getRemoveFields().contains(field);
// }
// }
// Path: stardao-core/src/test/java/io/stardog/stardao/jackson/UpdateSerializerTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableSet;
import io.stardog.stardao.core.TestModel;
import io.stardog.stardao.core.Update;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.*;
package io.stardog.stardao.jackson;
public class UpdateSerializerTest {
@Test
public void serialize() throws Exception {
|
Update<TestModel> update = Update.of(TestModel.builder()
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/NavigationDrawerFragment.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
|
package com.ryansteckler.nlpunbounce;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mClosing = false;
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/NavigationDrawerFragment.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
package com.ryansteckler.nlpunbounce;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mClosing = false;
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
ThemeHelper.onActivityCreateSetTheme(this.getActivity());
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/AlarmRegexFragment.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/adapters/RegexAdapter.java
// public class RegexAdapter extends ArrayAdapter<String> {
//
//
// private final ArrayList<String> list;
// private final Activity context;
// private final String mEntityName;
//
// public RegexAdapter(Activity context, ArrayList<String> list, String entityName) {
// super(context, R.layout.fragment_regex_listitem, list);
// this.context = context;
// this.list = list;
// this.mEntityName = entityName;
// }
//
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// View view = null;
// if (convertView == null) {
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.fragment_regex_listitem, null);
// } else {
// view = convertView;
// }
//
// TextView text = (TextView) view.findViewById(R.id.textviewRegexName);
// text.setText(this.list.get(position).substring(0, this.list.get(position).indexOf("$$||$$")));
// Button button = (Button) view.findViewById(R.id.btn_delete_regex);
// if (button != null) {
// button.setTag(position);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Integer tag = (Integer) v.getTag();
// int pos = tag.intValue();
//
// list.remove(pos);
//
// // saves the list
// SharedPreferences prefs = context.getSharedPreferences("com.ryansteckler.nlpunbounce_preferences", Context.MODE_WORLD_READABLE);
// Set<String> set = new HashSet<String>();
// set.addAll(list);
// SharedPreferences.Editor editor = prefs.edit();
// editor.putStringSet(mEntityName + "_regex_set", set);
// editor.commit();
//
// notifyDataSetChanged();
//
// }
// });
// }
// return view;
// }
//
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.app.DialogFragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.adapters.RegexAdapter;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
|
// Create The Adapter with passing ArrayList as 3rd parameter
mAdapter = new RegexAdapter(getActivity(), list, "alarm");
// Sets The Adapter
setListAdapter(mAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new_custom) {
//Create a new custom alarm regex
DialogFragment dialog = RegexDialogFragment.newInstance("", "", "alarm");
dialog.setTargetFragment(this, 0);
dialog.show(getActivity().getFragmentManager(), "RegexDialog");
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/adapters/RegexAdapter.java
// public class RegexAdapter extends ArrayAdapter<String> {
//
//
// private final ArrayList<String> list;
// private final Activity context;
// private final String mEntityName;
//
// public RegexAdapter(Activity context, ArrayList<String> list, String entityName) {
// super(context, R.layout.fragment_regex_listitem, list);
// this.context = context;
// this.list = list;
// this.mEntityName = entityName;
// }
//
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// View view = null;
// if (convertView == null) {
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.fragment_regex_listitem, null);
// } else {
// view = convertView;
// }
//
// TextView text = (TextView) view.findViewById(R.id.textviewRegexName);
// text.setText(this.list.get(position).substring(0, this.list.get(position).indexOf("$$||$$")));
// Button button = (Button) view.findViewById(R.id.btn_delete_regex);
// if (button != null) {
// button.setTag(position);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Integer tag = (Integer) v.getTag();
// int pos = tag.intValue();
//
// list.remove(pos);
//
// // saves the list
// SharedPreferences prefs = context.getSharedPreferences("com.ryansteckler.nlpunbounce_preferences", Context.MODE_WORLD_READABLE);
// Set<String> set = new HashSet<String>();
// set.addAll(list);
// SharedPreferences.Editor editor = prefs.edit();
// editor.putStringSet(mEntityName + "_regex_set", set);
// editor.commit();
//
// notifyDataSetChanged();
//
// }
// });
// }
// return view;
// }
//
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/AlarmRegexFragment.java
import android.app.DialogFragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.adapters.RegexAdapter;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
// Create The Adapter with passing ArrayList as 3rd parameter
mAdapter = new RegexAdapter(getActivity(), list, "alarm");
// Sets The Adapter
setListAdapter(mAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new_custom) {
//Create a new custom alarm regex
DialogFragment dialog = RegexDialogFragment.newInstance("", "", "alarm");
dialog.setTargetFragment(this, 0);
dialog.show(getActivity().getFragmentManager(), "RegexDialog");
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
ThemeHelper.onActivityCreateSetTheme(this.getActivity());
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/SELinuxService.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/RootHelper.java
// public class RootHelper {
// /**
// * @author Kevin Kowalewski
// */
//
// private RootHelper() {
// }
//
// public static boolean isDeviceRooted() {
// return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4();
// }
//
// public static boolean checkRootMethod1() {
// String buildTags = android.os.Build.TAGS;
// return buildTags != null && buildTags.contains("test-keys");
// }
//
// public static boolean checkRootMethod2() {
// try {
// File file = new File("/system/app/Superuser.apk");
// return file.exists();
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean checkRootMethod4() {
// try {
// File file = new File("/system/xbin/su");
// return file.exists();
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean checkRootMethod3() {
// return new ExecShell().executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null;
// }
//
//
// public static void handleSELinux() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Process localProcess = null;
// try {
//
// Process process = Runtime.getRuntime().exec(new String[]{"su"});
// DataOutputStream os = new DataOutputStream(process.getOutputStream());
// os.writeBytes("/system/bin/chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files/nlp* \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files/nlp* \n");
// os.flush();
// os.writeBytes("exit\n");
// os.flush();
// os.close();
//
// BufferedReader in = new BufferedReader(new InputStreamReader(
// process.getInputStream()));
// String line;
// String fullResponse = "";
// try {
// while ((line = in.readLine()) != null) {
// fullResponse += ("\n" + (line));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// int i = 0;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// }
|
import android.app.IntentService;
import android.content.Intent;
import com.ryansteckler.nlpunbounce.helpers.RootHelper;
|
package com.ryansteckler.nlpunbounce;
/**
* Created by rsteckler on 3/2/15.
*/
public class SELinuxService extends IntentService {
public SELinuxService() {
super("SeLinuxService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public SELinuxService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent workIntent) {
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/RootHelper.java
// public class RootHelper {
// /**
// * @author Kevin Kowalewski
// */
//
// private RootHelper() {
// }
//
// public static boolean isDeviceRooted() {
// return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4();
// }
//
// public static boolean checkRootMethod1() {
// String buildTags = android.os.Build.TAGS;
// return buildTags != null && buildTags.contains("test-keys");
// }
//
// public static boolean checkRootMethod2() {
// try {
// File file = new File("/system/app/Superuser.apk");
// return file.exists();
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean checkRootMethod4() {
// try {
// File file = new File("/system/xbin/su");
// return file.exists();
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean checkRootMethod3() {
// return new ExecShell().executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null;
// }
//
//
// public static void handleSELinux() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Process localProcess = null;
// try {
//
// Process process = Runtime.getRuntime().exec(new String[]{"su"});
// DataOutputStream os = new DataOutputStream(process.getOutputStream());
// os.writeBytes("/system/bin/chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files/nlp* \n");
// os.flush();
// os.writeBytes("chcon u:object_r:system_data_file:s0 /data/data/com.ryansteckler.nlpunbounce/files/nlp* \n");
// os.flush();
// os.writeBytes("exit\n");
// os.flush();
// os.close();
//
// BufferedReader in = new BufferedReader(new InputStreamReader(
// process.getInputStream()));
// String line;
// String fullResponse = "";
// try {
// while ((line = in.readLine()) != null) {
// fullResponse += ("\n" + (line));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// int i = 0;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/SELinuxService.java
import android.app.IntentService;
import android.content.Intent;
import com.ryansteckler.nlpunbounce.helpers.RootHelper;
package com.ryansteckler.nlpunbounce;
/**
* Created by rsteckler on 3/2/15.
*/
public class SELinuxService extends IntentService {
public SELinuxService() {
super("SeLinuxService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public SELinuxService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent workIntent) {
|
RootHelper.handleSELinux();
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/MaterialSettingsActivity.java
|
// Path: app/src/main/java/com/ryansteckler/inappbilling/Purchase.java
// public class Purchase {
// String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS
// String mOrderId;
// String mPackageName;
// String mSku;
// long mPurchaseTime;
// int mPurchaseState;
// String mDeveloperPayload;
// String mToken;
// String mOriginalJson;
// String mSignature;
//
// public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
// mItemType = itemType;
// mOriginalJson = jsonPurchaseInfo;
// JSONObject o = new JSONObject(mOriginalJson);
// mOrderId = o.optString("orderId");
// mPackageName = o.optString("packageName");
// mSku = o.optString("productId");
// mPurchaseTime = o.optLong("purchaseTime");
// mPurchaseState = o.optInt("purchaseState");
// mDeveloperPayload = o.optString("developerPayload");
// mToken = o.optString("token", o.optString("purchaseToken"));
// mSignature = signature;
// }
//
// public String getItemType() { return mItemType; }
// public String getOrderId() { return mOrderId; }
// public String getPackageName() { return mPackageName; }
// public String getSku() { return mSku; }
// public long getPurchaseTime() { return mPurchaseTime; }
// public int getPurchaseState() { return mPurchaseState; }
// public String getDeveloperPayload() { return mDeveloperPayload; }
// public String getToken() { return mToken; }
// public String getOriginalJson() { return mOriginalJson; }
// public String getSignature() { return mSignature; }
//
// @Override
// public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; }
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.ryansteckler.inappbilling.IabHelper;
import com.ryansteckler.inappbilling.IabResult;
import com.ryansteckler.inappbilling.Inventory;
import com.ryansteckler.inappbilling.Purchase;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
|
package com.ryansteckler.nlpunbounce;
public class MaterialSettingsActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks,
WakelocksFragment.OnFragmentInteractionListener,
BaseDetailFragment.FragmentInteractionListener,
HomeFragment.OnFragmentInteractionListener,
AlarmsFragment.OnFragmentInteractionListener,
ServicesFragment.OnFragmentInteractionListener
{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
IabHelper mHelper;
|
// Path: app/src/main/java/com/ryansteckler/inappbilling/Purchase.java
// public class Purchase {
// String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS
// String mOrderId;
// String mPackageName;
// String mSku;
// long mPurchaseTime;
// int mPurchaseState;
// String mDeveloperPayload;
// String mToken;
// String mOriginalJson;
// String mSignature;
//
// public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
// mItemType = itemType;
// mOriginalJson = jsonPurchaseInfo;
// JSONObject o = new JSONObject(mOriginalJson);
// mOrderId = o.optString("orderId");
// mPackageName = o.optString("packageName");
// mSku = o.optString("productId");
// mPurchaseTime = o.optLong("purchaseTime");
// mPurchaseState = o.optInt("purchaseState");
// mDeveloperPayload = o.optString("developerPayload");
// mToken = o.optString("token", o.optString("purchaseToken"));
// mSignature = signature;
// }
//
// public String getItemType() { return mItemType; }
// public String getOrderId() { return mOrderId; }
// public String getPackageName() { return mPackageName; }
// public String getSku() { return mSku; }
// public long getPurchaseTime() { return mPurchaseTime; }
// public int getPurchaseState() { return mPurchaseState; }
// public String getDeveloperPayload() { return mDeveloperPayload; }
// public String getToken() { return mToken; }
// public String getOriginalJson() { return mOriginalJson; }
// public String getSignature() { return mSignature; }
//
// @Override
// public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; }
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/MaterialSettingsActivity.java
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.ryansteckler.inappbilling.IabHelper;
import com.ryansteckler.inappbilling.IabResult;
import com.ryansteckler.inappbilling.Inventory;
import com.ryansteckler.inappbilling.Purchase;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
package com.ryansteckler.nlpunbounce;
public class MaterialSettingsActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks,
WakelocksFragment.OnFragmentInteractionListener,
BaseDetailFragment.FragmentInteractionListener,
HomeFragment.OnFragmentInteractionListener,
AlarmsFragment.OnFragmentInteractionListener,
ServicesFragment.OnFragmentInteractionListener
{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
IabHelper mHelper;
|
int mCurTheme = ThemeHelper.THEME_DEFAULT;
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/MaterialSettingsActivity.java
|
// Path: app/src/main/java/com/ryansteckler/inappbilling/Purchase.java
// public class Purchase {
// String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS
// String mOrderId;
// String mPackageName;
// String mSku;
// long mPurchaseTime;
// int mPurchaseState;
// String mDeveloperPayload;
// String mToken;
// String mOriginalJson;
// String mSignature;
//
// public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
// mItemType = itemType;
// mOriginalJson = jsonPurchaseInfo;
// JSONObject o = new JSONObject(mOriginalJson);
// mOrderId = o.optString("orderId");
// mPackageName = o.optString("packageName");
// mSku = o.optString("productId");
// mPurchaseTime = o.optLong("purchaseTime");
// mPurchaseState = o.optInt("purchaseState");
// mDeveloperPayload = o.optString("developerPayload");
// mToken = o.optString("token", o.optString("purchaseToken"));
// mSignature = signature;
// }
//
// public String getItemType() { return mItemType; }
// public String getOrderId() { return mOrderId; }
// public String getPackageName() { return mPackageName; }
// public String getSku() { return mSku; }
// public long getPurchaseTime() { return mPurchaseTime; }
// public int getPurchaseState() { return mPurchaseState; }
// public String getDeveloperPayload() { return mDeveloperPayload; }
// public String getToken() { return mToken; }
// public String getOriginalJson() { return mOriginalJson; }
// public String getSignature() { return mSignature; }
//
// @Override
// public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; }
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.ryansteckler.inappbilling.IabHelper;
import com.ryansteckler.inappbilling.IabResult;
import com.ryansteckler.inappbilling.Inventory;
import com.ryansteckler.inappbilling.Purchase;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
|
mCurTheme = ThemeHelper.onActivityResumeVerifyTheme(this, mCurTheme);
mCurForceEnglish = LocaleHelper.onActivityResumeVerifyLocale(this, mCurForceEnglish);
}
private void updateDonationUi() {
if (isPremium()) {
View againView = (View) findViewById(R.id.layoutDonateAgain);
if (againView != null)
againView.setVisibility(View.VISIBLE);
View donateView = (View) findViewById(R.id.layoutDonate);
if (donateView != null)
donateView.setVisibility(View.GONE);
}
}
public boolean isPremium() {
return mIsPremium;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
|
// Path: app/src/main/java/com/ryansteckler/inappbilling/Purchase.java
// public class Purchase {
// String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS
// String mOrderId;
// String mPackageName;
// String mSku;
// long mPurchaseTime;
// int mPurchaseState;
// String mDeveloperPayload;
// String mToken;
// String mOriginalJson;
// String mSignature;
//
// public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
// mItemType = itemType;
// mOriginalJson = jsonPurchaseInfo;
// JSONObject o = new JSONObject(mOriginalJson);
// mOrderId = o.optString("orderId");
// mPackageName = o.optString("packageName");
// mSku = o.optString("productId");
// mPurchaseTime = o.optLong("purchaseTime");
// mPurchaseState = o.optInt("purchaseState");
// mDeveloperPayload = o.optString("developerPayload");
// mToken = o.optString("token", o.optString("purchaseToken"));
// mSignature = signature;
// }
//
// public String getItemType() { return mItemType; }
// public String getOrderId() { return mOrderId; }
// public String getPackageName() { return mPackageName; }
// public String getSku() { return mSku; }
// public long getPurchaseTime() { return mPurchaseTime; }
// public int getPurchaseState() { return mPurchaseState; }
// public String getDeveloperPayload() { return mDeveloperPayload; }
// public String getToken() { return mToken; }
// public String getOriginalJson() { return mOriginalJson; }
// public String getSignature() { return mSignature; }
//
// @Override
// public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; }
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/MaterialSettingsActivity.java
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.ryansteckler.inappbilling.IabHelper;
import com.ryansteckler.inappbilling.IabResult;
import com.ryansteckler.inappbilling.Inventory;
import com.ryansteckler.inappbilling.Purchase;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
mCurTheme = ThemeHelper.onActivityResumeVerifyTheme(this, mCurTheme);
mCurForceEnglish = LocaleHelper.onActivityResumeVerifyLocale(this, mCurForceEnglish);
}
private void updateDonationUi() {
if (isPremium()) {
View againView = (View) findViewById(R.id.layoutDonateAgain);
if (againView != null)
againView.setVisibility(View.VISIBLE);
View donateView = (View) findViewById(R.id.layoutDonate);
if (donateView != null)
donateView.setVisibility(View.GONE);
}
}
public boolean isPremium() {
return mIsPremium;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
|
public void onIabPurchaseFinished(IabResult result, Purchase purchase)
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/SettingsActivity.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.SettingsHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
|
package com.ryansteckler.nlpunbounce;
public class SettingsActivity extends Activity {
private static final String TAG = "Anmplify: ";
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/SettingsActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;
import com.ryansteckler.nlpunbounce.helpers.LocaleHelper;
import com.ryansteckler.nlpunbounce.helpers.SettingsHelper;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
package com.ryansteckler.nlpunbounce;
public class SettingsActivity extends Activity {
private static final String TAG = "Anmplify: ";
|
int mCurTheme = ThemeHelper.THEME_DEFAULT;
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/models/AlarmStats.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/UidNameResolver.java
// public class UidNameResolver {
//
// protected String[] m_packages;
// protected String[] m_packageNames;
// private static Context m_context;
// private static UidNameResolver m_instance;
//
// private UidNameResolver(Context ctx) {
// m_context = ctx;
// }
//
// public static UidNameResolver getInstance(Context ctx) {
// if (m_instance == null) {
// m_instance = new UidNameResolver(ctx);
// }
//
// return m_instance;
// }
//
// public Drawable getIcon(String packageName) {
// Drawable icon = null;
// // retrieve and store the icon for that package
// String myPackage = packageName;
// if (!myPackage.equals("")) {
// PackageManager manager = m_context.getPackageManager();
// try {
// icon = manager.getApplicationIcon(myPackage);
// } catch (Exception e) {
// // nop: no icon found
// icon = null;
// }
// }
// return icon;
// }
//
// public String getLabel(String packageName) {
// String ret = packageName;
// PackageManager pm = m_context.getPackageManager();
// try {
// ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
// CharSequence label = ai.loadLabel(pm);
// if (label != null) {
// ret = label.toString();
// }
// } catch (NameNotFoundException e) {
// ret = packageName;
// }
//
// return ret;
// }
//
// public String getLabelForServices(int uId, String serviceName) {
//
// PackageManager pm = m_context.getPackageManager();
// String applicationName = null;
// if (uId > 0) {
// String[] packages = pm.getPackagesForUid(uId);
// if (null != packages) {
// for (String packageEntry : packages) {
// if (serviceName.contains(packageEntry)) {
// ApplicationInfo ai;
// try {
// ai = pm.getApplicationInfo(packageEntry, 0);
// } catch (final PackageManager.NameNotFoundException e) {
// ai = null;
// }
// applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "Unknown");
// break;
// }
// }
//
// return applicationName;
//
// } else {
// return "Unknown";
// }
// } else {
// return "Unknown";
// }
// }
//
// // Side effects: sets mName and mUniqueName
// // Sets mNamePackage, mName and mUniqueName
// public String getNameForUid(int uid) {
// String uidName = "";
// String uidNamePackage = "";
// boolean uidUniqueName = false;
//
// PackageManager pm = m_context.getPackageManager();
// m_packages = pm.getPackagesForUid(uid);
//
// if (m_packages == null) {
// uidName = Integer.toString(uid);
// return uidName;
// }
//
// m_packageNames = new String[m_packages.length];
// System.arraycopy(m_packages, 0, m_packageNames, 0, m_packages.length);
//
// // Convert package names to user-facing labels where possible
// for (int i = 0; i < m_packageNames.length; i++) {
// m_packageNames[i] = getLabel(m_packageNames[i]);
// }
//
// if (m_packageNames.length == 1) {
// uidNamePackage = m_packages[0];
// uidName = m_packageNames[0];
// uidUniqueName = true;
// } else {
// uidName = "UID"; // Default name
// // Look for an official name for this UID.
// for (String name : m_packages) {
// try {
// PackageInfo pi = pm.getPackageInfo(name, 0);
// if (pi.sharedUserLabel != 0) {
// CharSequence nm = pm.getText(name,
// pi.sharedUserLabel, pi.applicationInfo);
// if (nm != null) {
// uidName = nm.toString();
// break;
// }
// }
// } catch (NameNotFoundException e) {
// }
// }
// }
// return uidName;
// }
//
// /**
// * Returns the name for UIDs < 2000
// *
// * @param uid
// * @return
// */
// String getName(int uid) {
// String ret = "";
// switch (uid) {
// case 0:
// ret = "root";
// break;
// case 1000:
// ret = "system";
// break;
// case 1001:
// ret = "radio";
// break;
// case 1002:
// ret = "bluetooth";
// break;
// case 1003:
// ret = "graphics";
// break;
// case 1004:
// ret = "input";
// break;
// case 1005:
// ret = "audio";
// break;
// case 1006:
// ret = "camera";
// break;
// case 1007:
// ret = "log";
// break;
// case 1008:
// ret = "compass";
// break;
// case 1009:
// ret = "mount";
// break;
// case 1010:
// ret = "wifi";
// break;
// case 1011:
// ret = "adb";
// break;
// case 1013:
// ret = "media";
// break;
// case 1014:
// ret = "dhcp";
// break;
//
// }
// return ret;
// }
//
// }
|
import android.content.Context;
import com.ryansteckler.nlpunbounce.helpers.UidNameResolver;
import java.io.Serializable;
|
package com.ryansteckler.nlpunbounce.models;
/**
* Created by rsteckler on 9/13/14.
*/
public class AlarmStats extends BaseStats implements Serializable {
public AlarmStats(String alarmName, String packageName) {
setType("alarm");
setName(alarmName);
if (null != packageName && !packageName.trim().equals("")) setPackage(packageName);
else {
setPackage("No Package");
}
}
private AlarmStats() {
}
@Override
public String getDerivedPackageName(Context ctx) {
if (null== getDerivedPackageName()){
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/UidNameResolver.java
// public class UidNameResolver {
//
// protected String[] m_packages;
// protected String[] m_packageNames;
// private static Context m_context;
// private static UidNameResolver m_instance;
//
// private UidNameResolver(Context ctx) {
// m_context = ctx;
// }
//
// public static UidNameResolver getInstance(Context ctx) {
// if (m_instance == null) {
// m_instance = new UidNameResolver(ctx);
// }
//
// return m_instance;
// }
//
// public Drawable getIcon(String packageName) {
// Drawable icon = null;
// // retrieve and store the icon for that package
// String myPackage = packageName;
// if (!myPackage.equals("")) {
// PackageManager manager = m_context.getPackageManager();
// try {
// icon = manager.getApplicationIcon(myPackage);
// } catch (Exception e) {
// // nop: no icon found
// icon = null;
// }
// }
// return icon;
// }
//
// public String getLabel(String packageName) {
// String ret = packageName;
// PackageManager pm = m_context.getPackageManager();
// try {
// ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
// CharSequence label = ai.loadLabel(pm);
// if (label != null) {
// ret = label.toString();
// }
// } catch (NameNotFoundException e) {
// ret = packageName;
// }
//
// return ret;
// }
//
// public String getLabelForServices(int uId, String serviceName) {
//
// PackageManager pm = m_context.getPackageManager();
// String applicationName = null;
// if (uId > 0) {
// String[] packages = pm.getPackagesForUid(uId);
// if (null != packages) {
// for (String packageEntry : packages) {
// if (serviceName.contains(packageEntry)) {
// ApplicationInfo ai;
// try {
// ai = pm.getApplicationInfo(packageEntry, 0);
// } catch (final PackageManager.NameNotFoundException e) {
// ai = null;
// }
// applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "Unknown");
// break;
// }
// }
//
// return applicationName;
//
// } else {
// return "Unknown";
// }
// } else {
// return "Unknown";
// }
// }
//
// // Side effects: sets mName and mUniqueName
// // Sets mNamePackage, mName and mUniqueName
// public String getNameForUid(int uid) {
// String uidName = "";
// String uidNamePackage = "";
// boolean uidUniqueName = false;
//
// PackageManager pm = m_context.getPackageManager();
// m_packages = pm.getPackagesForUid(uid);
//
// if (m_packages == null) {
// uidName = Integer.toString(uid);
// return uidName;
// }
//
// m_packageNames = new String[m_packages.length];
// System.arraycopy(m_packages, 0, m_packageNames, 0, m_packages.length);
//
// // Convert package names to user-facing labels where possible
// for (int i = 0; i < m_packageNames.length; i++) {
// m_packageNames[i] = getLabel(m_packageNames[i]);
// }
//
// if (m_packageNames.length == 1) {
// uidNamePackage = m_packages[0];
// uidName = m_packageNames[0];
// uidUniqueName = true;
// } else {
// uidName = "UID"; // Default name
// // Look for an official name for this UID.
// for (String name : m_packages) {
// try {
// PackageInfo pi = pm.getPackageInfo(name, 0);
// if (pi.sharedUserLabel != 0) {
// CharSequence nm = pm.getText(name,
// pi.sharedUserLabel, pi.applicationInfo);
// if (nm != null) {
// uidName = nm.toString();
// break;
// }
// }
// } catch (NameNotFoundException e) {
// }
// }
// }
// return uidName;
// }
//
// /**
// * Returns the name for UIDs < 2000
// *
// * @param uid
// * @return
// */
// String getName(int uid) {
// String ret = "";
// switch (uid) {
// case 0:
// ret = "root";
// break;
// case 1000:
// ret = "system";
// break;
// case 1001:
// ret = "radio";
// break;
// case 1002:
// ret = "bluetooth";
// break;
// case 1003:
// ret = "graphics";
// break;
// case 1004:
// ret = "input";
// break;
// case 1005:
// ret = "audio";
// break;
// case 1006:
// ret = "camera";
// break;
// case 1007:
// ret = "log";
// break;
// case 1008:
// ret = "compass";
// break;
// case 1009:
// ret = "mount";
// break;
// case 1010:
// ret = "wifi";
// break;
// case 1011:
// ret = "adb";
// break;
// case 1013:
// ret = "media";
// break;
// case 1014:
// ret = "dhcp";
// break;
//
// }
// return ret;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/models/AlarmStats.java
import android.content.Context;
import com.ryansteckler.nlpunbounce.helpers.UidNameResolver;
import java.io.Serializable;
package com.ryansteckler.nlpunbounce.models;
/**
* Created by rsteckler on 9/13/14.
*/
public class AlarmStats extends BaseStats implements Serializable {
public AlarmStats(String alarmName, String packageName) {
setType("alarm");
setName(alarmName);
if (null != packageName && !packageName.trim().equals("")) setPackage(packageName);
else {
setPackage("No Package");
}
}
private AlarmStats() {
}
@Override
public String getDerivedPackageName(Context ctx) {
if (null== getDerivedPackageName()){
|
UidNameResolver resolver = UidNameResolver.getInstance(ctx);
|
rsteckler/unbounce-android
|
app/src/main/java/com/ryansteckler/nlpunbounce/WakelockRegexFragment.java
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/adapters/RegexAdapter.java
// public class RegexAdapter extends ArrayAdapter<String> {
//
//
// private final ArrayList<String> list;
// private final Activity context;
// private final String mEntityName;
//
// public RegexAdapter(Activity context, ArrayList<String> list, String entityName) {
// super(context, R.layout.fragment_regex_listitem, list);
// this.context = context;
// this.list = list;
// this.mEntityName = entityName;
// }
//
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// View view = null;
// if (convertView == null) {
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.fragment_regex_listitem, null);
// } else {
// view = convertView;
// }
//
// TextView text = (TextView) view.findViewById(R.id.textviewRegexName);
// text.setText(this.list.get(position).substring(0, this.list.get(position).indexOf("$$||$$")));
// Button button = (Button) view.findViewById(R.id.btn_delete_regex);
// if (button != null) {
// button.setTag(position);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Integer tag = (Integer) v.getTag();
// int pos = tag.intValue();
//
// list.remove(pos);
//
// // saves the list
// SharedPreferences prefs = context.getSharedPreferences("com.ryansteckler.nlpunbounce_preferences", Context.MODE_WORLD_READABLE);
// Set<String> set = new HashSet<String>();
// set.addAll(list);
// SharedPreferences.Editor editor = prefs.edit();
// editor.putStringSet(mEntityName + "_regex_set", set);
// editor.commit();
//
// notifyDataSetChanged();
//
// }
// });
// }
// return view;
// }
//
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
|
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.adapters.RegexAdapter;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
|
// Create The Adapter with passing ArrayList as 3rd parameter
mAdapter = new RegexAdapter(getActivity(), list, "wakelock");
// Sets The Adapter
setListAdapter(mAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new_custom) {
//Create a new custom wakelock regex
DialogFragment dialog = RegexDialogFragment.newInstance("", "", "wakelock");
dialog.setTargetFragment(this, 0);
dialog.show(getActivity().getFragmentManager(), "RegexDialog");
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/adapters/RegexAdapter.java
// public class RegexAdapter extends ArrayAdapter<String> {
//
//
// private final ArrayList<String> list;
// private final Activity context;
// private final String mEntityName;
//
// public RegexAdapter(Activity context, ArrayList<String> list, String entityName) {
// super(context, R.layout.fragment_regex_listitem, list);
// this.context = context;
// this.list = list;
// this.mEntityName = entityName;
// }
//
// @Override
// public View getView(final int position, View convertView, ViewGroup parent) {
// View view = null;
// if (convertView == null) {
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.fragment_regex_listitem, null);
// } else {
// view = convertView;
// }
//
// TextView text = (TextView) view.findViewById(R.id.textviewRegexName);
// text.setText(this.list.get(position).substring(0, this.list.get(position).indexOf("$$||$$")));
// Button button = (Button) view.findViewById(R.id.btn_delete_regex);
// if (button != null) {
// button.setTag(position);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Integer tag = (Integer) v.getTag();
// int pos = tag.intValue();
//
// list.remove(pos);
//
// // saves the list
// SharedPreferences prefs = context.getSharedPreferences("com.ryansteckler.nlpunbounce_preferences", Context.MODE_WORLD_READABLE);
// Set<String> set = new HashSet<String>();
// set.addAll(list);
// SharedPreferences.Editor editor = prefs.edit();
// editor.putStringSet(mEntityName + "_regex_set", set);
// editor.commit();
//
// notifyDataSetChanged();
//
// }
// });
// }
// return view;
// }
//
// }
//
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/helpers/ThemeHelper.java
// public class ThemeHelper {
//
// private static int sTheme = -1;
// public final static int THEME_DEFAULT = 0;
// public final static int THEME_DARK = 1;
// /**
// * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
// */
// public static void changeToTheme(Activity activity, int theme)
// {
// sTheme = theme;
// activity.finish();
// activity.startActivity(new Intent(activity, activity.getClass()));
// }
// /** Set the theme of the activity, according to the configuration. */
// public static int onActivityCreateSetTheme(Activity activity)
// {
// if (sTheme == -1) {
// // Load from prefs
// SharedPreferences prefs = activity.getSharedPreferences("com.ryansteckler.nlpunbounce" + "_preferences", Context.MODE_WORLD_READABLE);
// sTheme = prefs.getString("theme", "default").equals("default") ? THEME_DEFAULT : THEME_DARK;
// }
//
// switch (sTheme)
// {
// default:
// case THEME_DEFAULT:
// activity.setTheme(R.style.UnbounceThemeLight);
// break;
// case THEME_DARK:
// activity.setTheme(R.style.UnbounceThemeDark);
// break;
// }
// return sTheme;
// }
// public static int onActivityResumeVerifyTheme(Activity activity, int curTheme)
// {
// if (curTheme != sTheme) {
// changeToTheme(activity, sTheme);
// }
//
// return sTheme;
// }
//
// public static int getTheme() {
// return sTheme;
// }
//
// }
// Path: app/src/main/java/com/ryansteckler/nlpunbounce/WakelockRegexFragment.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.ryansteckler.nlpunbounce.adapters.RegexAdapter;
import com.ryansteckler.nlpunbounce.helpers.ThemeHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
// Create The Adapter with passing ArrayList as 3rd parameter
mAdapter = new RegexAdapter(getActivity(), list, "wakelock");
// Sets The Adapter
setListAdapter(mAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new_custom) {
//Create a new custom wakelock regex
DialogFragment dialog = RegexDialogFragment.newInstance("", "", "wakelock");
dialog.setTargetFragment(this, 0);
dialog.show(getActivity().getFragmentManager(), "RegexDialog");
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
|
ThemeHelper.onActivityCreateSetTheme(this.getActivity());
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/CassandraFactory.java
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import java.util.List;
import org.easycassandra.ReplicaStrategy;
import com.datastax.driver.core.Session;
|
package org.easycassandra.persistence.cassandra;
/**
* the base of Cassandra factory.
*/
public interface CassandraFactory {
/**
* returns the session of Cassandra Driver.
* @return session of cassandra
*/
Session getSession();
/**
* returns the keyspace default.
* @return the keySpace
*/
String getKeySpace();
/**
* returns the host default.
* @return the host
*/
List<String> getHosts();
/**
* returns the port default.
* @return the port
*/
int getPort();
/**
* create a new keySpace on the cluster.
* @param keySpace - the keySpace name
* @param factor - the number of replica factor
* @param replicaStrategy the replicaStrategy
*/
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/CassandraFactory.java
import java.util.List;
import org.easycassandra.ReplicaStrategy;
import com.datastax.driver.core.Session;
package org.easycassandra.persistence.cassandra;
/**
* the base of Cassandra factory.
*/
public interface CassandraFactory {
/**
* returns the session of Cassandra Driver.
* @return session of cassandra
*/
Session getSession();
/**
* returns the keyspace default.
* @return the keySpace
*/
String getKeySpace();
/**
* returns the host default.
* @return the host
*/
List<String> getHosts();
/**
* returns the port default.
* @return the port
*/
int getPort();
/**
* create a new keySpace on the cluster.
* @param keySpace - the keySpace name
* @param factor - the number of replica factor
* @param replicaStrategy the replicaStrategy
*/
|
void createKeySpace(String keySpace, ReplicaStrategy replicaStrategy,
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FindByIndexQuery.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/IndexProblemException.java
// public class IndexProblemException extends EasyCassandraException {
//
// /**
// * Constructor to IndexProblemException.
// * @param message information to log
// */
// public IndexProblemException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 1L;
//
// }
|
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.IndexProblemException;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
|
/*
* 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.easycassandra.persistence.cassandra;
/**
* Class to execute a index.
* @author otaviojava
*/
class FindByIndexQuery extends FindByKeyQuery {
public FindByIndexQuery(String keySpace) {
super(keySpace);
}
public <T, I> List<T> findByIndex(I index, Class<T> bean, Session session,
ConsistencyLevel consistency) {
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/IndexProblemException.java
// public class IndexProblemException extends EasyCassandraException {
//
// /**
// * Constructor to IndexProblemException.
// * @param message information to log
// */
// public IndexProblemException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 1L;
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FindByIndexQuery.java
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.IndexProblemException;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
/*
* 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.easycassandra.persistence.cassandra;
/**
* Class to execute a index.
* @author otaviojava
*/
class FindByIndexQuery extends FindByKeyQuery {
public FindByIndexQuery(String keySpace) {
super(keySpace);
}
public <T, I> List<T> findByIndex(I index, Class<T> bean, Session session,
ConsistencyLevel consistency) {
|
ClassInformation classInformation = ClassInformations.INSTACE.getClass(bean);
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FindByIndexQuery.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/IndexProblemException.java
// public class IndexProblemException extends EasyCassandraException {
//
// /**
// * Constructor to IndexProblemException.
// * @param message information to log
// */
// public IndexProblemException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 1L;
//
// }
|
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.IndexProblemException;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
|
/*
* 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.easycassandra.persistence.cassandra;
/**
* Class to execute a index.
* @author otaviojava
*/
class FindByIndexQuery extends FindByKeyQuery {
public FindByIndexQuery(String keySpace) {
super(keySpace);
}
public <T, I> List<T> findByIndex(I index, Class<T> bean, Session session,
ConsistencyLevel consistency) {
ClassInformation classInformation = ClassInformations.INSTACE.getClass(bean);
List<FieldInformation> fields = classInformation.getIndexFields();
checkFieldNull(bean, fields);
return findByIndex(fields.get(0).getName(), index, bean, session, consistency);
}
/**
* Edited by Nenita Casuga to make method static and package protected so it can be reused.
*
*/
static <T> void checkFieldNull(Class<T> bean, List<FieldInformation> fields) {
if (fields.isEmpty()) {
StringBuilder erro = new StringBuilder();
erro.append("No found some field with @org.easycassandra.Index within ");
erro.append(bean.getName()).append(" class.");
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/IndexProblemException.java
// public class IndexProblemException extends EasyCassandraException {
//
// /**
// * Constructor to IndexProblemException.
// * @param message information to log
// */
// public IndexProblemException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 1L;
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FindByIndexQuery.java
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.IndexProblemException;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
/*
* 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.easycassandra.persistence.cassandra;
/**
* Class to execute a index.
* @author otaviojava
*/
class FindByIndexQuery extends FindByKeyQuery {
public FindByIndexQuery(String keySpace) {
super(keySpace);
}
public <T, I> List<T> findByIndex(I index, Class<T> bean, Session session,
ConsistencyLevel consistency) {
ClassInformation classInformation = ClassInformations.INSTACE.getClass(bean);
List<FieldInformation> fields = classInformation.getIndexFields();
checkFieldNull(bean, fields);
return findByIndex(fields.get(0).getName(), index, bean, session, consistency);
}
/**
* Edited by Nenita Casuga to make method static and package protected so it can be reused.
*
*/
static <T> void checkFieldNull(Class<T> bean, List<FieldInformation> fields) {
if (fields.isEmpty()) {
StringBuilder erro = new StringBuilder();
erro.append("No found some field with @org.easycassandra.Index within ");
erro.append(bean.getName()).append(" class.");
|
throw new IndexProblemException(erro.toString());
|
otaviojava/Easy-Cassandra
|
src/test/java/org/easycassandra/persistence/cassandra/spring/ContactRepositoryTest.java
|
// Path: src/test/java/org/easycassandra/persistence/cassandra/spring/repository/ContactRepository.java
// @Repository("contactRepository")
// public class ContactRepository extends CassandraRepository<Contact, UUID> {
//
// @Autowired
// private CassandraTemplate cassandraTemplate;
//
// @Override
// protected CassandraTemplate getCassandraTemplate() {
// return cassandraTemplate;
// }
//
// }
|
import java.util.UUID;
import junit.framework.Assert;
import org.easycassandra.persistence.cassandra.spring.entity.Contact;
import org.easycassandra.persistence.cassandra.spring.repository.ContactRepository;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
|
package org.easycassandra.persistence.cassandra.spring;
/**
* test to ContactRepository.
*/
public class ContactRepositoryTest {
private static final int TWENTY = 20;
|
// Path: src/test/java/org/easycassandra/persistence/cassandra/spring/repository/ContactRepository.java
// @Repository("contactRepository")
// public class ContactRepository extends CassandraRepository<Contact, UUID> {
//
// @Autowired
// private CassandraTemplate cassandraTemplate;
//
// @Override
// protected CassandraTemplate getCassandraTemplate() {
// return cassandraTemplate;
// }
//
// }
// Path: src/test/java/org/easycassandra/persistence/cassandra/spring/ContactRepositoryTest.java
import java.util.UUID;
import junit.framework.Assert;
import org.easycassandra.persistence.cassandra.spring.entity.Contact;
import org.easycassandra.persistence.cassandra.spring.repository.ContactRepository;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
package org.easycassandra.persistence.cassandra.spring;
/**
* test to ContactRepository.
*/
public class ContactRepositoryTest {
private static final int TWENTY = 20;
|
private ContactRepository contactReporitory;
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/TruncateQuery.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
|
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Truncate;
|
package org.easycassandra.persistence.cassandra;
/**
* Command to remove all information on Cassandra.
* @author otaviojava
*/
class TruncateQuery {
private String keySpace;
public TruncateQuery(String keySpace) {
this.keySpace = keySpace;
}
/**
*truncate the column family.
* @param bean the kind of object
* @param session the session
* @param <T> the kind of object
*/
public <T> void truncate(Class<T> bean, Session session) {
Truncate query = getQuery(bean);
session.execute(query.toString());
}
protected <T> Truncate getQuery(Class<T> bean) {
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/TruncateQuery.java
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Truncate;
package org.easycassandra.persistence.cassandra;
/**
* Command to remove all information on Cassandra.
* @author otaviojava
*/
class TruncateQuery {
private String keySpace;
public TruncateQuery(String keySpace) {
this.keySpace = keySpace;
}
/**
*truncate the column family.
* @param bean the kind of object
* @param session the session
* @param <T> the kind of object
*/
public <T> void truncate(Class<T> bean, Session session) {
Truncate query = getQuery(bean);
session.execute(query.toString());
}
protected <T> Truncate getQuery(Class<T> bean) {
|
ClassInformation classInformation = ClassInformations.INSTACE
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FindAllQuery.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
|
import java.util.LinkedList;
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformation.KeySpaceInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
|
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* Mount and run the query to returns all data from column family.
* @author otaviojava
*/
public class FindAllQuery {
private String keySpace;
/**
* constructor.
* @param keySpace
* the keyspace
*/
public FindAllQuery(String keySpace) {
this.keySpace = keySpace;
}
/**
* list using select * from object.
* @param bean the bean
* @param session the sesion
* @param consistency the consistency
* @param <T> kind of class
* @return the entities executing select * from
*/
public <T> List<T> listAll(Class<T> bean, Session session,
ConsistencyLevel consistency) {
QueryBean byKeyBean = createQueryBean(bean, consistency);
return RecoveryObject.INTANCE.recoverObjet(bean,
session.execute(byKeyBean.select));
}
/**
* create the {@link QueryBean}.
* @param bean the bean
* @param consistency the consistency
* @param <T> kind of class
* @return {@link QueryBean}
*/
protected <T> QueryBean createQueryBean(Class<T> bean,
ConsistencyLevel consistency) {
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FindAllQuery.java
import java.util.LinkedList;
import java.util.List;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformation.KeySpaceInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* Mount and run the query to returns all data from column family.
* @author otaviojava
*/
public class FindAllQuery {
private String keySpace;
/**
* constructor.
* @param keySpace
* the keyspace
*/
public FindAllQuery(String keySpace) {
this.keySpace = keySpace;
}
/**
* list using select * from object.
* @param bean the bean
* @param session the sesion
* @param consistency the consistency
* @param <T> kind of class
* @return the entities executing select * from
*/
public <T> List<T> listAll(Class<T> bean, Session session,
ConsistencyLevel consistency) {
QueryBean byKeyBean = createQueryBean(bean, consistency);
return RecoveryObject.INTANCE.recoverObjet(bean,
session.execute(byKeyBean.select));
}
/**
* create the {@link QueryBean}.
* @param bean the bean
* @param consistency the consistency
* @param <T> kind of class
* @return {@link QueryBean}
*/
protected <T> QueryBean createQueryBean(Class<T> bean,
ConsistencyLevel consistency) {
|
ClassInformation classInformation = ClassInformations.INSTACE.getClass(bean);
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FixKeySpaceUtil.java
|
// Path: src/main/java/org/easycassandra/EasyCassandraException.java
// public class EasyCassandraException extends RuntimeException {
//
// /**
// *
// */
// private static final long serialVersionUID = -5116386811420121860L;
//
// /**
// * The Constructor for Exception.
// * @param message information to log
// */
// public EasyCassandraException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.easycassandra.EasyCassandraException;
import org.easycassandra.ReplicaStrategy;
|
package org.easycassandra.persistence.cassandra;
/**
* util to create keyspace.
* @author otaviojava
*
*/
enum FixKeySpaceUtil {
INSTANCE;
|
// Path: src/main/java/org/easycassandra/EasyCassandraException.java
// public class EasyCassandraException extends RuntimeException {
//
// /**
// *
// */
// private static final long serialVersionUID = -5116386811420121860L;
//
// /**
// * The Constructor for Exception.
// * @param message information to log
// */
// public EasyCassandraException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FixKeySpaceUtil.java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.easycassandra.EasyCassandraException;
import org.easycassandra.ReplicaStrategy;
package org.easycassandra.persistence.cassandra;
/**
* util to create keyspace.
* @author otaviojava
*
*/
enum FixKeySpaceUtil {
INSTANCE;
|
public CreateKeySpace getCreate(ReplicaStrategy replicaStrategy) {
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FixKeySpaceUtil.java
|
// Path: src/main/java/org/easycassandra/EasyCassandraException.java
// public class EasyCassandraException extends RuntimeException {
//
// /**
// *
// */
// private static final long serialVersionUID = -5116386811420121860L;
//
// /**
// * The Constructor for Exception.
// * @param message information to log
// */
// public EasyCassandraException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.easycassandra.EasyCassandraException;
import org.easycassandra.ReplicaStrategy;
|
private static final String BEGIN_QUERY = "CREATE KEYSPACE IF NOT EXISTS";
private static final String ERRO_QUERY_MANDATORY = "When you define custom type to Create "
+ "keyspace you must inform the query.";
private static final String ERRO_QUERY_BEGIN_MANDATORY = "On custom query you must use "
+ BEGIN_QUERY + " to create your query.";
@Override
public String createQuery(KeySpaceQueryInformation information) {
if (information.customQuery == null
|| information.customQuery.isEmpty()) {
throw new CreateKeySpaceException(ERRO_QUERY_MANDATORY);
}
if (!findBeginQuery(information)) {
throw new CreateKeySpaceException(ERRO_QUERY_BEGIN_MANDATORY);
}
return information.customQuery;
}
private boolean findBeginQuery(KeySpaceQueryInformation information) {
return Pattern
.compile(Pattern.quote(BEGIN_QUERY),
Pattern.CASE_INSENSITIVE).matcher(information.customQuery)
.find();
}
}
/**
* Exception to create keySpace.
* @author otaviojava
*/
|
// Path: src/main/java/org/easycassandra/EasyCassandraException.java
// public class EasyCassandraException extends RuntimeException {
//
// /**
// *
// */
// private static final long serialVersionUID = -5116386811420121860L;
//
// /**
// * The Constructor for Exception.
// * @param message information to log
// */
// public EasyCassandraException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FixKeySpaceUtil.java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.easycassandra.EasyCassandraException;
import org.easycassandra.ReplicaStrategy;
private static final String BEGIN_QUERY = "CREATE KEYSPACE IF NOT EXISTS";
private static final String ERRO_QUERY_MANDATORY = "When you define custom type to Create "
+ "keyspace you must inform the query.";
private static final String ERRO_QUERY_BEGIN_MANDATORY = "On custom query you must use "
+ BEGIN_QUERY + " to create your query.";
@Override
public String createQuery(KeySpaceQueryInformation information) {
if (information.customQuery == null
|| information.customQuery.isEmpty()) {
throw new CreateKeySpaceException(ERRO_QUERY_MANDATORY);
}
if (!findBeginQuery(information)) {
throw new CreateKeySpaceException(ERRO_QUERY_BEGIN_MANDATORY);
}
return information.customQuery;
}
private boolean findBeginQuery(KeySpaceQueryInformation information) {
return Pattern
.compile(Pattern.quote(BEGIN_QUERY),
Pattern.CASE_INSENSITIVE).matcher(information.customQuery)
.find();
}
}
/**
* Exception to create keySpace.
* @author otaviojava
*/
|
static class CreateKeySpaceException extends EasyCassandraException {
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/ClusterInformation.java
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.easycassandra.ReplicaStrategy;
import org.easycassandra.persistence.cassandra.FixKeySpaceUtil.KeySpaceQueryInformation;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Builder;
|
package org.easycassandra.persistence.cassandra;
/**
* this dto has information to build a cluster to be used on the constructors factory.
* @author otaviojava
*/
public class ClusterInformation {
private List<String> hosts = new LinkedList<>();
private String keySpace;
private String user = "";
private String password = "";
private Map<String, Integer> dataCenter = new HashMap<>();
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/ClusterInformation.java
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.easycassandra.ReplicaStrategy;
import org.easycassandra.persistence.cassandra.FixKeySpaceUtil.KeySpaceQueryInformation;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Builder;
package org.easycassandra.persistence.cassandra;
/**
* this dto has information to build a cluster to be used on the constructors factory.
* @author otaviojava
*/
public class ClusterInformation {
private List<String> hosts = new LinkedList<>();
private String keySpace;
private String user = "";
private String password = "";
private Map<String, Integer> dataCenter = new HashMap<>();
|
private ReplicaStrategy replicaStrategy = REPLICASTRATEGY_DEFAULT;
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/EasyCassandraFactory.java
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import org.easycassandra.ReplicaStrategy;
|
package org.easycassandra.persistence.cassandra;
/**
* Class for manage Connections.
* @author otaviojava
*
*/
public interface EasyCassandraFactory {
/**
* Method for create the Cassandra's Client, if the keyspace there is not,if
* keyspace there isn't, it will created with simple strategy replica and
* number of fator 3.
* @param keySpace
* - the keyspace's name
* @return the client bridge for the Cassandra data base
*/
@Deprecated
Persistence getPersistence(String keySpace);
/**
* Method for create the Cassandra's Client, if the keyspace there is not,if
* keyspace there isn't, it will created with replacyStrategy and number of
* factor.
* @param host
* - place where is Cassandra data base
* @param keySpace
* - the keyspace's name
* @param replicaStrategy
* - replica strategy
* @param factor
* - number of the factor
* @return the client bridge for the Cassandra data base
*/
@Deprecated
Persistence getPersistence(String host, String keySpace,
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/EasyCassandraFactory.java
import org.easycassandra.ReplicaStrategy;
package org.easycassandra.persistence.cassandra;
/**
* Class for manage Connections.
* @author otaviojava
*
*/
public interface EasyCassandraFactory {
/**
* Method for create the Cassandra's Client, if the keyspace there is not,if
* keyspace there isn't, it will created with simple strategy replica and
* number of fator 3.
* @param keySpace
* - the keyspace's name
* @return the client bridge for the Cassandra data base
*/
@Deprecated
Persistence getPersistence(String keySpace);
/**
* Method for create the Cassandra's Client, if the keyspace there is not,if
* keyspace there isn't, it will created with replacyStrategy and number of
* factor.
* @param host
* - place where is Cassandra data base
* @param keySpace
* - the keyspace's name
* @param replicaStrategy
* - replica strategy
* @param factor
* - number of the factor
* @return the client bridge for the Cassandra data base
*/
@Deprecated
Persistence getPersistence(String host, String keySpace,
|
ReplicaStrategy replicaStrategy, int factor);
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
|
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
|
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* Class to fix a column family.
* @author otaviojava
*/
class FixColumnFamily {
private static final String QUERY_PRIMARY_KEY = " PRIMARY KEY (";
private static final String CLUSTERING_ORDER = " WITH CLUSTERING ORDER BY (";
/**
* verify if exist column family and try to create.
* @param session - bridge to cassandra data base
* @param keySpace - the keyspace
* @param familyColumn - name of family column
* @param class1 - bean
* @return - if get it or not
*/
public boolean verifyColumnFamily(Session session, String keySpace, String familyColumn,
Class<?> class1) {
try {
Select select = QueryBuilder.select().from(keySpace, familyColumn).limit(1);
ResultSet resultSet = session.execute(select);
verifyRowType(resultSet, class1, session);
findIndex(class1, session);
return true;
} catch (InvalidQueryException exception) {
if (exception.getCause().getMessage().contains("unconfigured columnfamily ")) {
Logger.getLogger(FixColumnFamily.class.getName()).info(
"Column family doesn't exist, try to create");
createColumnFamily(familyColumn, class1, session);
findIndex(class1, session);
return true;
}
}
return false;
}
/**
* Column family exists verify.
* @param resultSet
*/
private void verifyRowType(ResultSet resultSet, Class<?> class1, Session session) {
Map<String, String> mapNameType = new HashMap<String, String>();
for (Definition column : resultSet.getColumnDefinitions()) {
mapNameType
.put(column.getName(), column.getType().getName().name());
}
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* Class to fix a column family.
* @author otaviojava
*/
class FixColumnFamily {
private static final String QUERY_PRIMARY_KEY = " PRIMARY KEY (";
private static final String CLUSTERING_ORDER = " WITH CLUSTERING ORDER BY (";
/**
* verify if exist column family and try to create.
* @param session - bridge to cassandra data base
* @param keySpace - the keyspace
* @param familyColumn - name of family column
* @param class1 - bean
* @return - if get it or not
*/
public boolean verifyColumnFamily(Session session, String keySpace, String familyColumn,
Class<?> class1) {
try {
Select select = QueryBuilder.select().from(keySpace, familyColumn).limit(1);
ResultSet resultSet = session.execute(select);
verifyRowType(resultSet, class1, session);
findIndex(class1, session);
return true;
} catch (InvalidQueryException exception) {
if (exception.getCause().getMessage().contains("unconfigured columnfamily ")) {
Logger.getLogger(FixColumnFamily.class.getName()).info(
"Column family doesn't exist, try to create");
createColumnFamily(familyColumn, class1, session);
findIndex(class1, session);
return true;
}
}
return false;
}
/**
* Column family exists verify.
* @param resultSet
*/
private void verifyRowType(ResultSet resultSet, Class<?> class1, Session session) {
Map<String, String> mapNameType = new HashMap<String, String>();
for (Definition column : resultSet.getColumnDefinitions()) {
mapNameType
.put(column.getName(), column.getType().getName().name());
}
|
ClassInformation classInformation = ClassInformations.INSTACE.getClass(class1);
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
|
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
|
* - field to add in column family
*/
private void executeAlterTableAdd(ClassInformation classInformation, Session session,
FieldInformation field) {
StringBuilder cqlAlterTable = new StringBuilder();
cqlAlterTable.append("ALTER TABLE ").append(classInformation.getNameSchema());
cqlAlterTable.append(" ADD ");
AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
cqlAlterTable.append(addColumn.addRow(field, RelationShipJavaCassandra.INSTANCE));
cqlAlterTable.deleteCharAt(cqlAlterTable.length() - 1);
cqlAlterTable.append(";");
session.execute(cqlAlterTable.toString());
}
/**
* Field Java isn't equivalents with CQL type create error mensage.
* @param classInformation
* @param field
* @param cqlTypes
*/
private void createMessageErro(ClassInformation classInformation,
FieldInformation field, String cqlType) {
StringBuilder erroMensage = new StringBuilder();
erroMensage.append("In the objetc ").append(classInformation.getClass().getName());
erroMensage.append(" the field ").append(field.getName());
erroMensage.append(" of the type ").append(field.getField().getType().getName());
erroMensage.append(" isn't equivalent with CQL type ").append(cqlType);
erroMensage.append(" was expected: ").append(
RelationShipJavaCassandra.INSTANCE.getJavaValue(cqlType
.toLowerCase()));
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
* - field to add in column family
*/
private void executeAlterTableAdd(ClassInformation classInformation, Session session,
FieldInformation field) {
StringBuilder cqlAlterTable = new StringBuilder();
cqlAlterTable.append("ALTER TABLE ").append(classInformation.getNameSchema());
cqlAlterTable.append(" ADD ");
AddColumn addColumn = AddColumnUtil.INSTANCE.factory(field);
cqlAlterTable.append(addColumn.addRow(field, RelationShipJavaCassandra.INSTANCE));
cqlAlterTable.deleteCharAt(cqlAlterTable.length() - 1);
cqlAlterTable.append(";");
session.execute(cqlAlterTable.toString());
}
/**
* Field Java isn't equivalents with CQL type create error mensage.
* @param classInformation
* @param field
* @param cqlTypes
*/
private void createMessageErro(ClassInformation classInformation,
FieldInformation field, String cqlType) {
StringBuilder erroMensage = new StringBuilder();
erroMensage.append("In the objetc ").append(classInformation.getClass().getName());
erroMensage.append(" the field ").append(field.getName());
erroMensage.append(" of the type ").append(field.getField().getType().getName());
erroMensage.append(" isn't equivalent with CQL type ").append(cqlType);
erroMensage.append(" was expected: ").append(
RelationShipJavaCassandra.INSTANCE.getJavaValue(cqlType
.toLowerCase()));
|
throw new FieldJavaNotEquivalentCQLException(erroMensage.toString());
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
|
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
|
cqlCreateTable.append(",").append(subKey.getName()).append(" ").append(getOrderString(subKey));
}
}
}
if (!firstTime){
cqlCreateTable.append(")");
}
}
private static String getOrderString(FieldInformation subKey) {
return subKey.getOrder()==Order.DESC?"DESC":"ASC";
}
/**
* @param bean
*/
private void createErro(ClassInformation bean) {
StringBuilder erroMensage = new StringBuilder();
erroMensage.append("the bean ").append(bean.getNameSchema());
erroMensage
.append(" hasn't a field with id annotation, "
+ "you may to use either javax.persistence.Id");
erroMensage.append(" to simple id or javax.persistence.EmbeddedId");
erroMensage
.append(" to complex id, another object with one "
+ "or more fields annotated with java.persistence.Column.");
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldJavaNotEquivalentCQLException.java
// public class FieldJavaNotEquivalentCQLException extends EasyCassandraException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor to FieldJavaNotEquivalentCQLException.
// * @param message information to log
// */
// public FieldJavaNotEquivalentCQLException(String message) {
// super(message);
//
// }
//
// }
//
// Path: src/main/java/org/easycassandra/KeyProblemsException.java
// public class KeyProblemsException extends EasyCassandraException {
//
// /**
// * Constructor to KeyProblemsException.
// * @param message
// * information to log
// */
// public KeyProblemsException(String message) {
// super(message);
//
// }
//
// private static final long serialVersionUID = 1L;
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/FixColumnFamily.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.easycassandra.ClassInformation;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldJavaNotEquivalentCQLException;
import org.easycassandra.KeyProblemsException;
import org.easycassandra.persistence.cassandra.AddColumnUtil.AddColumn;
import org.easycassandra.persistence.cassandra.VerifyRowUtil.VerifyRow;
import com.datastax.driver.core.ColumnDefinitions.Definition;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import java.util.Collections;
import java.util.Comparator;
import org.easycassandra.Order;
cqlCreateTable.append(",").append(subKey.getName()).append(" ").append(getOrderString(subKey));
}
}
}
if (!firstTime){
cqlCreateTable.append(")");
}
}
private static String getOrderString(FieldInformation subKey) {
return subKey.getOrder()==Order.DESC?"DESC":"ASC";
}
/**
* @param bean
*/
private void createErro(ClassInformation bean) {
StringBuilder erroMensage = new StringBuilder();
erroMensage.append("the bean ").append(bean.getNameSchema());
erroMensage
.append(" hasn't a field with id annotation, "
+ "you may to use either javax.persistence.Id");
erroMensage.append(" to simple id or javax.persistence.EmbeddedId");
erroMensage
.append(" to complex id, another object with one "
+ "or more fields annotated with java.persistence.Column.");
|
throw new KeyProblemsException(erroMensage.toString());
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/AbstractCassandraFactory.java
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
|
import java.util.List;
import org.easycassandra.ReplicaStrategy;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
|
}
@Override
public List<String> getHosts() {
return clusterInformation.getHosts();
}
@Override
public String getKeySpace() {
return clusterInformation.getKeySpace();
}
@Override
public int getPort() {
return clusterInformation.getPort();
}
@Override
public Session getSession() {
return session;
}
protected boolean fixColumnFamily(Session session, String familyColumn,
Class<?> class1) {
return new FixColumnFamily().verifyColumnFamily(session,
clusterInformation.getKeySpace(), familyColumn, class1);
}
@Override
public void createKeySpace(String keySpace,
|
// Path: src/main/java/org/easycassandra/ReplicaStrategy.java
// public enum ReplicaStrategy {
// /**
// * SimpleStrategy places the first replica on a node determined by the
// * partitioner. Additional replicas are placed on the next nodes clockwise
// * in the ring without considering rack or data center location.
// */
// SIMPLES_TRATEGY("'SimpleStrategy'"),
// /**
// * is the preferred replication placement strategy when you have information
// * about how nodes are grouped in your data center, or when you have (or
// * plan to have) your cluster deployed across multiple data centers. This
// * strategy allows you to specify how many replicas you want in each data
// * center.
// */
// NETWORK_TOPOLOGY_STRATEGY("'NetworkTopologyStrategy'"),
// /**
// * use a custom query.
// */
// CUSTOM_STRATEGY("");
//
// private String value;
//
// ReplicaStrategy(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/AbstractCassandraFactory.java
import java.util.List;
import org.easycassandra.ReplicaStrategy;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
}
@Override
public List<String> getHosts() {
return clusterInformation.getHosts();
}
@Override
public String getKeySpace() {
return clusterInformation.getKeySpace();
}
@Override
public int getPort() {
return clusterInformation.getPort();
}
@Override
public Session getSession() {
return session;
}
protected boolean fixColumnFamily(Session session, String familyColumn,
Class<?> class1) {
return new FixColumnFamily().verifyColumnFamily(session,
clusterInformation.getKeySpace(), familyColumn, class1);
}
@Override
public void createKeySpace(String keySpace,
|
ReplicaStrategy replicaStrategy, int factor) {
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/AddColumnUtil.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldType.java
// public enum FieldType {
// ENUM, LIST, SET, MAP, COLLECTION, CUSTOM, DEFAULT, EMPTY;
//
// /**
// * find you the kind of annotation on field and then define a enum type, follow the sequences:
// * <ul>
// * <li>Enum</li>
// * <li>List</li>
// * <li>Set</li>
// * <li>Map</li>
// * <li>Collection</li>
// * <li>Custom</li>
// * <li>Default - if there is not a annotation</li>
// * </ul>.
// * @param field - the field with annotation
// * @return the type
// */
// public static FieldType getTypeByField(Field field) {
//
// if (ColumnUtil.INTANCE.isEnumField(field)) {
// return ENUM;
// }
// if (ColumnUtil.INTANCE.isList(field)) {
// return LIST;
// }
// if (ColumnUtil.INTANCE.isSet(field)) {
// return SET;
// }
// if (ColumnUtil.INTANCE.isMap(field)) {
// return MAP;
// }
// if (ColumnUtil.INTANCE.isElementCollection(field)) {
// return COLLECTION;
// }
// if (ColumnUtil.INTANCE.isCustom(field)) {
// return CUSTOM;
// }
// return DEFAULT;
// }
//
// private static final String LIST_QUALIFIELD = "java.util.List";
// private static final String SET_QUALIFIELD = "java.util.Set";
// private static final String MAP_QUALIFIELD = "java.util.Map";
//
// /**
// * find out the kind of enum on type of Collection.
// * @param field - the field with annotation
// * @return the enum type
// */
// public static FieldType findCollectionbyQualifield(Field field) {
//
// switch (field.getType().getName()) {
// case LIST_QUALIFIELD:
// return LIST;
// case SET_QUALIFIELD:
// return SET;
// case MAP_QUALIFIELD:
// return MAP;
// default:
// return DEFAULT;
// }
// }
//
// }
|
import java.nio.ByteBuffer;
import java.util.EnumMap;
import java.util.Map;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldType;
|
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* create a column to cassandra checking the annotation.
* @author otaviojava
*/
enum AddColumnUtil {
INSTANCE;
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldType.java
// public enum FieldType {
// ENUM, LIST, SET, MAP, COLLECTION, CUSTOM, DEFAULT, EMPTY;
//
// /**
// * find you the kind of annotation on field and then define a enum type, follow the sequences:
// * <ul>
// * <li>Enum</li>
// * <li>List</li>
// * <li>Set</li>
// * <li>Map</li>
// * <li>Collection</li>
// * <li>Custom</li>
// * <li>Default - if there is not a annotation</li>
// * </ul>.
// * @param field - the field with annotation
// * @return the type
// */
// public static FieldType getTypeByField(Field field) {
//
// if (ColumnUtil.INTANCE.isEnumField(field)) {
// return ENUM;
// }
// if (ColumnUtil.INTANCE.isList(field)) {
// return LIST;
// }
// if (ColumnUtil.INTANCE.isSet(field)) {
// return SET;
// }
// if (ColumnUtil.INTANCE.isMap(field)) {
// return MAP;
// }
// if (ColumnUtil.INTANCE.isElementCollection(field)) {
// return COLLECTION;
// }
// if (ColumnUtil.INTANCE.isCustom(field)) {
// return CUSTOM;
// }
// return DEFAULT;
// }
//
// private static final String LIST_QUALIFIELD = "java.util.List";
// private static final String SET_QUALIFIELD = "java.util.Set";
// private static final String MAP_QUALIFIELD = "java.util.Map";
//
// /**
// * find out the kind of enum on type of Collection.
// * @param field - the field with annotation
// * @return the enum type
// */
// public static FieldType findCollectionbyQualifield(Field field) {
//
// switch (field.getType().getName()) {
// case LIST_QUALIFIELD:
// return LIST;
// case SET_QUALIFIELD:
// return SET;
// case MAP_QUALIFIELD:
// return MAP;
// default:
// return DEFAULT;
// }
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/AddColumnUtil.java
import java.nio.ByteBuffer;
import java.util.EnumMap;
import java.util.Map;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldType;
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra.persistence.cassandra;
/**
* create a column to cassandra checking the annotation.
* @author otaviojava
*/
enum AddColumnUtil {
INSTANCE;
|
private Map<FieldType, AddColumn> addColumnMap;
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/persistence/cassandra/AddColumnUtil.java
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldType.java
// public enum FieldType {
// ENUM, LIST, SET, MAP, COLLECTION, CUSTOM, DEFAULT, EMPTY;
//
// /**
// * find you the kind of annotation on field and then define a enum type, follow the sequences:
// * <ul>
// * <li>Enum</li>
// * <li>List</li>
// * <li>Set</li>
// * <li>Map</li>
// * <li>Collection</li>
// * <li>Custom</li>
// * <li>Default - if there is not a annotation</li>
// * </ul>.
// * @param field - the field with annotation
// * @return the type
// */
// public static FieldType getTypeByField(Field field) {
//
// if (ColumnUtil.INTANCE.isEnumField(field)) {
// return ENUM;
// }
// if (ColumnUtil.INTANCE.isList(field)) {
// return LIST;
// }
// if (ColumnUtil.INTANCE.isSet(field)) {
// return SET;
// }
// if (ColumnUtil.INTANCE.isMap(field)) {
// return MAP;
// }
// if (ColumnUtil.INTANCE.isElementCollection(field)) {
// return COLLECTION;
// }
// if (ColumnUtil.INTANCE.isCustom(field)) {
// return CUSTOM;
// }
// return DEFAULT;
// }
//
// private static final String LIST_QUALIFIELD = "java.util.List";
// private static final String SET_QUALIFIELD = "java.util.Set";
// private static final String MAP_QUALIFIELD = "java.util.Map";
//
// /**
// * find out the kind of enum on type of Collection.
// * @param field - the field with annotation
// * @return the enum type
// */
// public static FieldType findCollectionbyQualifield(Field field) {
//
// switch (field.getType().getName()) {
// case LIST_QUALIFIELD:
// return LIST;
// case SET_QUALIFIELD:
// return SET;
// case MAP_QUALIFIELD:
// return MAP;
// default:
// return DEFAULT;
// }
// }
//
// }
|
import java.nio.ByteBuffer;
import java.util.EnumMap;
import java.util.Map;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldType;
|
@Override
public String addRow(FieldInformation field,
RelationShipJavaCassandra javaCassandra) {
StringBuilder row = new StringBuilder();
String columnName = field.getName();
String keyType = getType(field.getKey().getName());
row.append(columnName)
.append(" list<")
.append(keyType)
.append(">,");
return row.toString();
}
}
/**
* {@link AddColumn} to enum.
* @author otaviojava
*/
class EnumAdd implements AddColumn {
@Override
public String addRow(FieldInformation field,
RelationShipJavaCassandra javaCassandra) {
String columnName = field.getName();
StringBuilder row = new StringBuilder();
row.append(columnName)
.append(" ")
.append(javaCassandra
|
// Path: src/main/java/org/easycassandra/ClassInformations.java
// public enum ClassInformations {
//
// INSTACE;
// /**
// * field that contains all class on Cassandra.
// * Key - qualifield
// * value - the wrapper of class
// */
// private Map<String, ClassInformation> classMap;
//
// /**
// * The integer class is used to enum how default.
// */
// public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class;
//
// /**
// * return the wrapper of class.
// * @param clazz class to find
// * @return {@link ClassInformation}
// */
// public ClassInformation getClass(Class<?> clazz) {
//
// if (classMap.get(clazz.getName()) == null) {
// classMap.put(clazz.getName(), new ClassInformation(clazz));
// }
// return classMap.get(clazz.getName());
// }
//
// {
// classMap = Collections.synchronizedMap(new TreeMap<String, ClassInformation>());
// }
// }
//
// Path: src/main/java/org/easycassandra/FieldType.java
// public enum FieldType {
// ENUM, LIST, SET, MAP, COLLECTION, CUSTOM, DEFAULT, EMPTY;
//
// /**
// * find you the kind of annotation on field and then define a enum type, follow the sequences:
// * <ul>
// * <li>Enum</li>
// * <li>List</li>
// * <li>Set</li>
// * <li>Map</li>
// * <li>Collection</li>
// * <li>Custom</li>
// * <li>Default - if there is not a annotation</li>
// * </ul>.
// * @param field - the field with annotation
// * @return the type
// */
// public static FieldType getTypeByField(Field field) {
//
// if (ColumnUtil.INTANCE.isEnumField(field)) {
// return ENUM;
// }
// if (ColumnUtil.INTANCE.isList(field)) {
// return LIST;
// }
// if (ColumnUtil.INTANCE.isSet(field)) {
// return SET;
// }
// if (ColumnUtil.INTANCE.isMap(field)) {
// return MAP;
// }
// if (ColumnUtil.INTANCE.isElementCollection(field)) {
// return COLLECTION;
// }
// if (ColumnUtil.INTANCE.isCustom(field)) {
// return CUSTOM;
// }
// return DEFAULT;
// }
//
// private static final String LIST_QUALIFIELD = "java.util.List";
// private static final String SET_QUALIFIELD = "java.util.Set";
// private static final String MAP_QUALIFIELD = "java.util.Map";
//
// /**
// * find out the kind of enum on type of Collection.
// * @param field - the field with annotation
// * @return the enum type
// */
// public static FieldType findCollectionbyQualifield(Field field) {
//
// switch (field.getType().getName()) {
// case LIST_QUALIFIELD:
// return LIST;
// case SET_QUALIFIELD:
// return SET;
// case MAP_QUALIFIELD:
// return MAP;
// default:
// return DEFAULT;
// }
// }
//
// }
// Path: src/main/java/org/easycassandra/persistence/cassandra/AddColumnUtil.java
import java.nio.ByteBuffer;
import java.util.EnumMap;
import java.util.Map;
import org.easycassandra.ClassInformations;
import org.easycassandra.FieldInformation;
import org.easycassandra.FieldType;
@Override
public String addRow(FieldInformation field,
RelationShipJavaCassandra javaCassandra) {
StringBuilder row = new StringBuilder();
String columnName = field.getName();
String keyType = getType(field.getKey().getName());
row.append(columnName)
.append(" list<")
.append(keyType)
.append(">,");
return row.toString();
}
}
/**
* {@link AddColumn} to enum.
* @author otaviojava
*/
class EnumAdd implements AddColumn {
@Override
public String addRow(FieldInformation field,
RelationShipJavaCassandra javaCassandra) {
String columnName = field.getName();
StringBuilder row = new StringBuilder();
row.append(columnName)
.append(" ")
.append(javaCassandra
|
.getPreferenceCQLType(ClassInformations.DEFAULT_ENUM_CLASS
|
otaviojava/Easy-Cassandra
|
src/test/java/org/easycassandra/bean/PersonDAOASyncTest.java
|
// Path: src/test/java/org/easycassandra/bean/model/Address.java
// public class Address implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "cyte")
// private String city;
//
// @Column(name = "street")
// private String street;
//
// @Column(name = "cep")
// private String cep;
//
// public String getCep() {
// return cep;
// }
//
// public void setCep(String cep) {
// this.cep = cep;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Address) {
// Address other = Address.class.cast(obj);
// return new EqualsBuilder().append(city, other.city).append(cep, other.cep).isEquals();
// }
// return false;
//
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder().append(city).append(cep).toHashCode();
// }
// }
|
import java.util.List;
import org.easycassandra.bean.dao.PersistenceDaoAsync;
import org.easycassandra.bean.model.Address;
import org.easycassandra.bean.model.Person;
import org.easycassandra.bean.model.Sex;
import org.easycassandra.persistence.cassandra.ResultAsyncCallBack;
import org.junit.Assert;
import org.junit.Test;
|
package org.easycassandra.bean;
/**
*
* @author otavio
*/
public class PersonDAOASyncTest {
private static final long SAMPLE_ID = 32L;
private static final int TEN = 10;
private static final int YEAR = 20;
private static final long FOUR = 4L;
private static final String NAME = "otavio teste";
private PersistenceDaoAsync<Person, Long> dao = new PersistenceDaoAsync<>(
Person.class);
/**
* run the test.
*/
@Test
public void insertTest() {
Person person = getPerson();
person.setName(NAME);
person.setId(FOUR);
person.setYear(YEAR);
|
// Path: src/test/java/org/easycassandra/bean/model/Address.java
// public class Address implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Column(name = "state")
// private String state;
//
// @Column(name = "cyte")
// private String city;
//
// @Column(name = "street")
// private String street;
//
// @Column(name = "cep")
// private String cep;
//
// public String getCep() {
// return cep;
// }
//
// public void setCep(String cep) {
// this.cep = cep;
// }
//
// public String getStreet() {
// return street;
// }
//
// public void setStreet(String street) {
// this.street = street;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Address) {
// Address other = Address.class.cast(obj);
// return new EqualsBuilder().append(city, other.city).append(cep, other.cep).isEquals();
// }
// return false;
//
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder().append(city).append(cep).toHashCode();
// }
// }
// Path: src/test/java/org/easycassandra/bean/PersonDAOASyncTest.java
import java.util.List;
import org.easycassandra.bean.dao.PersistenceDaoAsync;
import org.easycassandra.bean.model.Address;
import org.easycassandra.bean.model.Person;
import org.easycassandra.bean.model.Sex;
import org.easycassandra.persistence.cassandra.ResultAsyncCallBack;
import org.junit.Assert;
import org.junit.Test;
package org.easycassandra.bean;
/**
*
* @author otavio
*/
public class PersonDAOASyncTest {
private static final long SAMPLE_ID = 32L;
private static final int TEN = 10;
private static final int YEAR = 20;
private static final long FOUR = 4L;
private static final String NAME = "otavio teste";
private PersistenceDaoAsync<Person, Long> dao = new PersistenceDaoAsync<>(
Person.class);
/**
* run the test.
*/
@Test
public void insertTest() {
Person person = getPerson();
person.setName(NAME);
person.setId(FOUR);
person.setYear(YEAR);
|
Address address = getAddress();
|
otaviojava/Easy-Cassandra
|
src/main/java/org/easycassandra/CustomData.java
|
// Path: src/main/java/org/easycassandra/persistence/cassandra/Customizable.java
// class DefaultCustmomizable implements Customizable {
//
// public ByteBuffer read(Object object) {
//
// try {
// isSerializable(object);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// ObjectOutputStream storeObject = new ObjectOutputStream(stream);
// storeObject.writeObject(object);
// storeObject.flush();
// storeObject.close();
//
// return ByteBuffer.wrap(stream.toByteArray());
// } catch (IOException exception) {
// Logger.getLogger(DefaultCustmomizable.class.getName()).severe(
// "An error heppend when DefaultCustmomizable try read or "
// + "serialize the object "
// + object.getClass().getName() + " "
// + exception.getMessage());
// }
//
// return null;
// }
//
// private void isSerializable(Object object) {
// if (!(object instanceof Serializable)) {
// StringBuilder mensageErro = new StringBuilder();
// mensageErro.append("the class ").append(
// object.getClass().getName());
// mensageErro.append(" should implements java.io.Serializable");
// throw new DefaultCustmomizableException(mensageErro.toString());
// }
//
// }
//
// public Object write(ByteBuffer byteBuffer) {
//
// try {
// byte[] result = new byte[byteBuffer.remaining()];
// byteBuffer.get(result);
// InputStream inputStream = new ByteArrayInputStream(result);
// ObjectInputStream objLeitura = new ObjectInputStream(
// inputStream);
// return objLeitura.readObject();
// } catch (Exception exception) {
// Logger.getLogger(DefaultCustmomizable.class.getName())
// .severe("An error heppend when DefaultCustmomizable "
// + "try write and deserialize an object "
// + exception.getMessage());
// }
// return null;
// }
// }
|
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.easycassandra.persistence.cassandra.Customizable.DefaultCustmomizable;
|
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra;
/**
* This notation indicates which the field has a storage's way custom.
* @author osantana
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomData {
/**
* The class to custom a storage, the class should implements the
* Customizable and has default constructor. the default is
* {@link DefaultCustmomizable}
* the class whose implements Customizable interface
*/
|
// Path: src/main/java/org/easycassandra/persistence/cassandra/Customizable.java
// class DefaultCustmomizable implements Customizable {
//
// public ByteBuffer read(Object object) {
//
// try {
// isSerializable(object);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// ObjectOutputStream storeObject = new ObjectOutputStream(stream);
// storeObject.writeObject(object);
// storeObject.flush();
// storeObject.close();
//
// return ByteBuffer.wrap(stream.toByteArray());
// } catch (IOException exception) {
// Logger.getLogger(DefaultCustmomizable.class.getName()).severe(
// "An error heppend when DefaultCustmomizable try read or "
// + "serialize the object "
// + object.getClass().getName() + " "
// + exception.getMessage());
// }
//
// return null;
// }
//
// private void isSerializable(Object object) {
// if (!(object instanceof Serializable)) {
// StringBuilder mensageErro = new StringBuilder();
// mensageErro.append("the class ").append(
// object.getClass().getName());
// mensageErro.append(" should implements java.io.Serializable");
// throw new DefaultCustmomizableException(mensageErro.toString());
// }
//
// }
//
// public Object write(ByteBuffer byteBuffer) {
//
// try {
// byte[] result = new byte[byteBuffer.remaining()];
// byteBuffer.get(result);
// InputStream inputStream = new ByteArrayInputStream(result);
// ObjectInputStream objLeitura = new ObjectInputStream(
// inputStream);
// return objLeitura.readObject();
// } catch (Exception exception) {
// Logger.getLogger(DefaultCustmomizable.class.getName())
// .severe("An error heppend when DefaultCustmomizable "
// + "try write and deserialize an object "
// + exception.getMessage());
// }
// return null;
// }
// }
// Path: src/main/java/org/easycassandra/CustomData.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.easycassandra.persistence.cassandra.Customizable.DefaultCustmomizable;
/*
* Copyright 2013 Otávio Gonçalves de Santana (otaviojava)
* 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.easycassandra;
/**
* This notation indicates which the field has a storage's way custom.
* @author osantana
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomData {
/**
* The class to custom a storage, the class should implements the
* Customizable and has default constructor. the default is
* {@link DefaultCustmomizable}
* the class whose implements Customizable interface
*/
|
Class<?> classCustmo() default DefaultCustmomizable.class;
|
GoogleCloudPlatform/functions-framework-java
|
invoker/testfunction/src/test/java/com/example/functionjar/Background.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
|
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
|
// Copyright 2020 Google LLC
//
// 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.example.functionjar;
/**
* @author emcmanus@google.com (Éamonn McManus)
*/
public class Background implements RawBackgroundFunction {
@Override
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
// Path: invoker/testfunction/src/test/java/com/example/functionjar/Background.java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
// Copyright 2020 Google LLC
//
// 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.example.functionjar;
/**
* @author emcmanus@google.com (Éamonn McManus)
*/
public class Background implements RawBackgroundFunction {
@Override
|
public void accept(String json, Context context) {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/BackgroundSnoop.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
|
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
|
package com.google.cloud.functions.invoker.testfunctions;
/**
* Extract the targetFile property from the data of the JSON payload, and write to it a JSON
* encoding of this payload and the context. The JSON format is chosen to be identical to the
* EventFlow format that we currently use in GCF, and the file that we write should in fact be
* identical to the JSON payload that the Functions Framework received from the client in the test.
* This will need to be rewritten when we switch to CloudEvents.
*/
public class BackgroundSnoop implements RawBackgroundFunction {
@Override
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/BackgroundSnoop.java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
package com.google.cloud.functions.invoker.testfunctions;
/**
* Extract the targetFile property from the data of the JSON payload, and write to it a JSON
* encoding of this payload and the context. The JSON format is chosen to be identical to the
* EventFlow format that we currently use in GCF, and the file that we write should in fact be
* identical to the JSON payload that the Functions Framework received from the client in the test.
* This will need to be rewritten when we switch to CloudEvents.
*/
public class BackgroundSnoop implements RawBackgroundFunction {
@Override
|
public void accept(String json, Context context) {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/TypedBackgroundSnoop.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
|
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
|
package com.google.cloud.functions.invoker.testfunctions;
/**
* Extract the targetFile property from the data of the JSON payload, and write to it a JSON
* encoding of this payload and the context. The JSON format is chosen to be identical to the
* EventFlow format that we currently use in GCF, and the file that we write should in fact be
* identical to the JSON payload that the Functions Framework received from the client in the test.
* This will need to be rewritten when we switch to CloudEvents.
*/
public class TypedBackgroundSnoop implements BackgroundFunction<TypedBackgroundSnoop.Payload> {
public static class Payload {
public int a;
public int b;
public String targetFile;
}
@Override
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/TypedBackgroundSnoop.java
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
package com.google.cloud.functions.invoker.testfunctions;
/**
* Extract the targetFile property from the data of the JSON payload, and write to it a JSON
* encoding of this payload and the context. The JSON format is chosen to be identical to the
* EventFlow format that we currently use in GCF, and the file that we write should in fact be
* identical to the JSON payload that the Functions Framework received from the client in the test.
* This will need to be rewritten when we switch to CloudEvents.
*/
public class TypedBackgroundSnoop implements BackgroundFunction<TypedBackgroundSnoop.Payload> {
public static class Payload {
public int a;
public int b;
public String targetFile;
}
@Override
|
public void accept(Payload payload, Context context) {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/conformance/src/main/java/com/google/cloud/functions/conformance/BackgroundEventConformanceFunction.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
|
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.BufferedWriter;
import java.io.FileWriter;
|
package com.google.cloud.functions.conformance;
/**
* This class is used by the Functions Framework Conformance Tools to validate the framework's
* Background Event API. It can be run with the following command:
*
* <pre>{@code
* $ functions-framework-conformance-client \
* -cmd="mvn function:run -Drun.functionTarget=com.google.cloud.functions.conformance.BackgroundEventConformanceFunction" \
* -type=legacyevent \
* -buildpacks=false \
* -validate-mapping=false \
* -start-delay=10
* }</pre>
*/
public class BackgroundEventConformanceFunction implements RawBackgroundFunction {
private static final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
@Override
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
// Path: invoker/conformance/src/main/java/com/google/cloud/functions/conformance/BackgroundEventConformanceFunction.java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.BufferedWriter;
import java.io.FileWriter;
package com.google.cloud.functions.conformance;
/**
* This class is used by the Functions Framework Conformance Tools to validate the framework's
* Background Event API. It can be run with the following command:
*
* <pre>{@code
* $ functions-framework-conformance-client \
* -cmd="mvn function:run -Drun.functionTarget=com.google.cloud.functions.conformance.BackgroundEventConformanceFunction" \
* -type=legacyevent \
* -buildpacks=false \
* -validate-mapping=false \
* -start-delay=10
* }</pre>
*/
public class BackgroundEventConformanceFunction implements RawBackgroundFunction {
private static final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
@Override
|
public void accept(String data, Context context) throws Exception {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
|
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
|
private static class PubSubFunction implements BackgroundFunction<PubSubMessage> {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
|
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
private static class PubSubFunction implements BackgroundFunction<PubSubMessage> {
@Override
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
private static class PubSubFunction implements BackgroundFunction<PubSubMessage> {
@Override
|
public void accept(PubSubMessage payload, Context context) {}
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
|
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
|
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
private static class PubSubFunction implements BackgroundFunction<PubSubMessage> {
@Override
public void accept(PubSubMessage payload, Context context) {}
}
@Test
public void backgroundFunctionTypeArgument_simple() {
|
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
// static Optional<Type> backgroundFunctionTypeArgument(
// Class<? extends BackgroundFunction<?>> functionClass) {
// // If this is BackgroundFunction<Foo> then the user must have implemented a method
// // accept(Foo, Context), so we look for that method and return the type of its first argument.
// // We must be careful because the compiler will also have added a synthetic method
// // accept(Object, Context).
// return Arrays.stream(functionClass.getMethods())
// .filter(
// m ->
// m.getName().equals("accept")
// && m.getParameterCount() == 2
// && m.getParameterTypes()[1] == Context.class
// && m.getParameterTypes()[0] != Object.class)
// .map(m -> m.getGenericParameterTypes()[0])
// .findFirst();
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutorTest.java
import static com.google.cloud.functions.invoker.BackgroundFunctionExecutor.backgroundFunctionTypeArgument;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
package com.google.cloud.functions.invoker;
@RunWith(JUnit4.class)
public class BackgroundFunctionExecutorTest {
private static class PubSubMessage {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}
private static class PubSubFunction implements BackgroundFunction<PubSubMessage> {
@Override
public void accept(PubSubMessage payload, Context context) {}
}
@Test
public void backgroundFunctionTypeArgument_simple() {
|
assertThat(backgroundFunctionTypeArgument(PubSubFunction.class)).hasValue(PubSubMessage.class);
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/ExceptionBackground.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
|
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
|
package com.google.cloud.functions.invoker.testfunctions;
public class ExceptionBackground implements RawBackgroundFunction {
@Override
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
// Path: invoker/core/src/test/java/com/google/cloud/functions/invoker/testfunctions/ExceptionBackground.java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
package com.google.cloud.functions.invoker.testfunctions;
public class ExceptionBackground implements RawBackgroundFunction {
@Override
|
public void accept(String json, Context context) {
|
GoogleCloudPlatform/functions-framework-java
|
invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/CloudEventsFunction.java
// @FunctionalInterface
// public interface CloudEventsFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param event the event.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(CloudEvent event) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
|
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.CloudEventsFunction;
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import io.cloudevents.CloudEvent;
import io.cloudevents.core.message.MessageReader;
import io.cloudevents.http.HttpMessageFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
|
"Could not determine the payload type for BackgroundFunction of type "
+ instance.getClass().getName()
+ "; must implement BackgroundFunction<T> for some T");
}
executor = new TypedFunctionExecutor<>(maybeTargetType.get(), backgroundFunction);
break;
case CLOUD_EVENTS:
executor = new CloudEventFunctionExecutor((CloudEventsFunction) instance);
break;
default: // can't happen, we've listed all the FunctionKind values already.
throw new AssertionError(functionKind);
}
return new BackgroundFunctionExecutor(executor);
}
/**
* Returns the {@code T} of a concrete class that implements {@link BackgroundFunction
* BackgroundFunction<T>}. Returns an empty {@link Optional} if {@code T} can't be determined.
*/
static Optional<Type> backgroundFunctionTypeArgument(
Class<? extends BackgroundFunction<?>> functionClass) {
// If this is BackgroundFunction<Foo> then the user must have implemented a method
// accept(Foo, Context), so we look for that method and return the type of its first argument.
// We must be careful because the compiler will also have added a synthetic method
// accept(Object, Context).
return Arrays.stream(functionClass.getMethods())
.filter(
m ->
m.getName().equals("accept")
&& m.getParameterCount() == 2
|
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/BackgroundFunction.java
// @FunctionalInterface
// public interface BackgroundFunction<T> {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param payload the payload of the event, deserialized from the original JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(T payload, Context context) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/CloudEventsFunction.java
// @FunctionalInterface
// public interface CloudEventsFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param event the event.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(CloudEvent event) throws Exception;
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/Context.java
// public interface Context {
// /**
// * Returns event ID.
// *
// * @return event ID
// */
// String eventId();
//
// /**
// * Returns event timestamp.
// *
// * @return event timestamp
// */
// String timestamp();
//
// /**
// * Returns event type.
// *
// * @return event type
// */
// String eventType();
//
// /**
// * Returns event resource.
// *
// * @return event resource
// */
// String resource();
//
// /**
// * Returns additional attributes from this event. For CloudEvents, the entries in this map will
// * include the <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">required
// * attributes</a> and may include <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#required-attributes">optional
// * attributes</a> and <a
// * href="https://github.com/cloudevents/spec/blob/v1.0/spec.md#extension-context-attributes">
// * extension attributes</a>.
// *
// * <p>The map returned by this method may be empty but is never null.
// *
// * @return additional attributes form this event.
// */
// default Map<String, String> attributes() {
// return Collections.emptyMap();
// }
// }
//
// Path: functions-framework-api/src/main/java/com/google/cloud/functions/RawBackgroundFunction.java
// @FunctionalInterface
// public interface RawBackgroundFunction {
// /**
// * Called to service an incoming event. This interface is implemented by user code to provide the
// * action for a given background function. If this method throws any exception (including any
// * {@link Error}) then the HTTP response will have a 500 status code.
// *
// * @param json the payload of the event, as a JSON string.
// * @param context the context of the event. This is a set of values that every event has,
// * separately from the payload, such as timestamp and event type.
// * @throws Exception to produce a 500 status code in the HTTP response.
// */
// void accept(String json, Context context) throws Exception;
// }
// Path: invoker/core/src/main/java/com/google/cloud/functions/invoker/BackgroundFunctionExecutor.java
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.CloudEventsFunction;
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import io.cloudevents.CloudEvent;
import io.cloudevents.core.message.MessageReader;
import io.cloudevents.http.HttpMessageFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
"Could not determine the payload type for BackgroundFunction of type "
+ instance.getClass().getName()
+ "; must implement BackgroundFunction<T> for some T");
}
executor = new TypedFunctionExecutor<>(maybeTargetType.get(), backgroundFunction);
break;
case CLOUD_EVENTS:
executor = new CloudEventFunctionExecutor((CloudEventsFunction) instance);
break;
default: // can't happen, we've listed all the FunctionKind values already.
throw new AssertionError(functionKind);
}
return new BackgroundFunctionExecutor(executor);
}
/**
* Returns the {@code T} of a concrete class that implements {@link BackgroundFunction
* BackgroundFunction<T>}. Returns an empty {@link Optional} if {@code T} can't be determined.
*/
static Optional<Type> backgroundFunctionTypeArgument(
Class<? extends BackgroundFunction<?>> functionClass) {
// If this is BackgroundFunction<Foo> then the user must have implemented a method
// accept(Foo, Context), so we look for that method and return the type of its first argument.
// We must be careful because the compiler will also have added a synthetic method
// accept(Object, Context).
return Arrays.stream(functionClass.getMethods())
.filter(
m ->
m.getName().equals("accept")
&& m.getParameterCount() == 2
|
&& m.getParameterTypes()[1] == Context.class
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Goal.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Goal extends BaseClinicalObject{
private long goalDate = BaseObject.maxDate;
private String value;
private String unit;
public Goal(String id){
super(id);
}
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Goal.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Goal extends BaseClinicalObject{
private long goalDate = BaseObject.maxDate;
private String value;
private String unit;
public Goal(String id){
super(id);
}
|
public Goal(String id, ArrayList<CodedValue> type, ArrayList<CodedValue> description,
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Condition.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author swaldren
*/
public class Condition extends BaseClinicalObject{
/*
* This is the date (seconds from epoch) that is
* the known date that the condition started
*/
private long onset = BaseObject.minDate;
/*
* This is the date (seconds from epoch) that is
* the known date that the condition was resolved
*/
private long resolution = BaseObject.maxDate;
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Condition.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author swaldren
*/
public class Condition extends BaseClinicalObject{
/*
* This is the date (seconds from epoch) that is
* the known date that the condition started
*/
private long onset = BaseObject.minDate;
/*
* This is the date (seconds from epoch) that is
* the known date that the condition was resolved
*/
private long resolution = BaseObject.maxDate;
|
private ArrayList<CodedValue> status;
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/api/ValidatonErrorHandler.java
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
|
import java.io.IOException;
import java.util.ArrayList;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
|
handleError(saxpe);
}
public void fatalError(SAXParseException saxpe) throws SAXException {
handleError(saxpe);
}
private void handleError(SAXParseException ex){
Error e = new Error();
e.setMessage(ex.getLocalizedMessage());
e.setLineNumber(ex.getLineNumber());
e.setColumnNumber(ex.getColumnNumber());
errors.add(e);
}
public ArrayList<Error> getErrors() {
return errors;
}
public void resetErrors(){
errors.clear();
}
public boolean hasErrors(){
return !errors.isEmpty();
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
if (hasErrors()){
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
// Path: src/java/org/ohd/pophealth/api/ValidatonErrorHandler.java
import java.io.IOException;
import java.util.ArrayList;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
handleError(saxpe);
}
public void fatalError(SAXParseException saxpe) throws SAXException {
handleError(saxpe);
}
private void handleError(SAXParseException ex){
Error e = new Error();
e.setMessage(ex.getLocalizedMessage());
e.setLineNumber(ex.getLineNumber());
e.setColumnNumber(ex.getColumnNumber());
errors.add(e);
}
public ArrayList<Error> getErrors() {
return errors;
}
public void resetErrors(){
errors.clear();
}
public boolean hasErrors(){
return !errors.isEmpty();
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
if (hasErrors()){
|
return JsonMapper.toJson(this, prettyPrint);
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/ccr/importer/TermSet.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.ohd.pophealth.json.measuremodel.CodedValue;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.ccr.importer;
/**
*
* @author ohdohd
*/
@JsonPropertyOrder({"id", "terms", "codes"})
public class TermSet {
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/ccr/importer/TermSet.java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.ohd.pophealth.json.measuremodel.CodedValue;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.ccr.importer;
/**
*
* @author ohdohd
*/
@JsonPropertyOrder({"id", "terms", "codes"})
public class TermSet {
|
private ArrayList<CodedValue> codes;
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Order.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Order extends BaseClinicalObject{
private long orderDate = BaseObject.maxDate;
private ArrayList<Goal> goals;
private ArrayList<BaseClinicalObject> orderRequests;
public Order (String id){
super(id);
goals = new ArrayList<Goal>();
orderRequests = new ArrayList<BaseClinicalObject>();
}
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Order.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Order extends BaseClinicalObject{
private long orderDate = BaseObject.maxDate;
private ArrayList<Goal> goals;
private ArrayList<BaseClinicalObject> orderRequests;
public Order (String id){
super(id);
goals = new ArrayList<Goal>();
orderRequests = new ArrayList<BaseClinicalObject>();
}
|
public Order(String id, ArrayList<CodedValue> type, ArrayList<CodedValue> description,
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/BaseObject.java
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
|
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class BaseObject {
@JsonIgnore
public static long minDate = -9223372036854775808L;
@JsonIgnore
public static long maxDate = 9223372036854775807L;
private String id;
public BaseObject(String id) {
this.id = id;
}
protected String getCategory() {
return "base";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/BaseObject.java
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class BaseObject {
@JsonIgnore
public static long minDate = -9223372036854775808L;
@JsonIgnore
public static long maxDate = 9223372036854775807L;
private String id;
public BaseObject(String id) {
this.id = id;
}
protected String getCategory() {
return "base";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
|
return JsonMapper.toJson(this, prettyPrint);
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Procedure.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Procedure extends Encounter{
public Procedure(String id){
super(id);
}
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Procedure.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Procedure extends Encounter{
public Procedure(String id){
super(id);
}
|
public Procedure(String id, ArrayList<CodedValue> type, ArrayList<CodedValue> description, long occurred, ArrayList<String> providers, CodedValue indication) {
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Encounter.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Encounter extends BaseClinicalObject{
private long occurred = BaseObject.minDate;
private long ended = BaseObject.maxDate;
private ArrayList<String> providers;
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Encounter.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Encounter extends BaseClinicalObject{
private long occurred = BaseObject.minDate;
private long ended = BaseObject.maxDate;
private ArrayList<String> providers;
|
private CodedValue indication;
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Medication.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import java.util.Collection;
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Medication extends BaseClinicalObject{
private long started = BaseObject.minDate;
private long stopped = BaseObject.maxDate;
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Medication.java
import java.util.Collection;
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Medication extends BaseClinicalObject{
private long started = BaseObject.minDate;
private long stopped = BaseObject.maxDate;
|
private ArrayList<CodedValue> status;
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Patient.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author swaldren
*/
public class Patient {
private long birthdate; // milliseconds from epoch
private String gender;
private String first; // First Name
private String last; // Last Name
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Patient.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author swaldren
*/
public class Patient {
private long birthdate; // milliseconds from epoch
private String gender;
private String first; // First Name
private String last; // Last Name
|
private ArrayList<CodedValue> race;
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Test.java
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
|
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Test extends BaseClinicalObject{
private long collectionTime = BaseObject.minDate;
private String value ="";
private String units ="";
public Test (String id){
super(id);
}
|
// Path: src/java/org/ohd/pophealth/json/measuremodel/CodedValue.java
// @JsonPropertyOrder({"codingSystem", "version", "values"})
// public class CodedValue {
//
// private String codingSystem;
// private String version;
// private ArrayList<String> values;
//
// public CodedValue() {
// this.values = new ArrayList<String>();
// }
//
// public CodedValue(String codingSystem, String version, ArrayList<String> values) {
// this.codingSystem = codingSystem;
// this.version = version;
// this.values = values;
// }
//
// public String getCodingSystem() {
// return codingSystem;
// }
//
// public void setCodingSystem(String codingSystem) {
// this.codingSystem = codingSystem;
// }
//
// public ArrayList<String> getValues() {
// return values;
// }
//
// public void setValues(ArrayList<String> values) {
// this.values = values;
// }
//
// public String getVersion() {
// return version;
// }
//
// public void setVersion(String version) {
// this.version = version;
// }
//
// public void addValue(String v){
// values.add(v);
// }
//
// /**
// * Checks equality between two <code>CodedValue</code> objects which means:
// * <ol>
// * <li>The Coding Systems are the same and</li>
// * <li>The Version of the Coding Systems are the same and</li>
// * <li>Both code lists are not empty and
// * <li>That there is at least one code value in common</li>
// * </ol>
// *
// * @param obj The <code>CodedValue</code> object to compare to
// * @return true only if they are the same c
// */
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final CodedValue other = (CodedValue) obj;
// if ((this.codingSystem == null) ? (other.codingSystem != null) : !this.codingSystem.equals(other.codingSystem)) {
// return false;
// }
// if ((this.version == null) ? (other.version != null) : !this.version.equals(other.version)) {
// return false;
// }
// if (this.values.isEmpty() || other.values.isEmpty()) {
// return false;
// }
// for (String t : this.values){
// if (other.values.contains(t)){
// return true;
// }
// }
// return false;
// }
//
//
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 13 * hash + (this.codingSystem != null ? this.codingSystem.hashCode() : 0);
// hash = 13 * hash + (this.version != null ? this.version.hashCode() : 0);
// hash = 13 * hash + (this.values != null ? this.values.hashCode() : 0);
// return hash;
// }
//
// @Override
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append(this.codingSystem);
// sb.append(" [");
// sb.append(this.version);
// sb.append("] ");
// sb.append("{");
// for (int x=0; x<this.values.size();x++){
// sb.append(this.values.get(x));
// if (x < this.values.size()-1){
// sb.append(", ");
// }
// }
// sb.append("}");
// return sb.toString();
// }
//
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Test.java
import org.ohd.pophealth.json.measuremodel.CodedValue;
import java.util.ArrayList;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ohd.pophealth.json.clinicalmodel;
/**
*
* @author ohdohd
*/
public class Test extends BaseClinicalObject{
private long collectionTime = BaseObject.minDate;
private String value ="";
private String units ="";
public Test (String id){
super(id);
}
|
public Test(String id, long collectionTime, ArrayList<CodedValue>type,
|
eedrummer/ccr-importer
|
src/java/org/ohd/pophealth/json/clinicalmodel/Record.java
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
|
import java.io.IOException;
import java.util.ArrayList;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
|
public void setAllergies(ArrayList<Allergy> allergies) {
this.allergies = allergies;
}
public ArrayList<Procedure> getProcedures() {
return procedures;
}
public void setProcedures(ArrayList<Procedure> procedures) {
this.procedures = procedures;
}
public ArrayList<Order> getOrders() {
return orders;
}
public void setOrders(ArrayList<Order> orders) {
this.orders = orders;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
|
// Path: src/java/org/ohd/pophealth/json/JsonMapper.java
// public class JsonMapper {
//
// private static ObjectMapper m = new ObjectMapper();
// private static JsonFactory jf = new JsonFactory();
//
// static {
// jf.configure(Feature.ALLOW_COMMENTS, true);
// m.configure(Feature.ALLOW_COMMENTS, true);
// }
//
// /**
// * Create object of type <T> from the JSON string
// * @param <T> The type to try to map to and return
// * @param jsonAsString the JSON String
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
// throws JsonMappingException, JsonParseException, IOException {
// return m.readValue(jsonAsString, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in a file
// * @param <T> The type to try to map to and return
// * @param fr The filereader of the file containing the JSON string
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(FileReader fr, Class<T> pojoClass)
// throws JsonParseException, IOException
// {
// return m.readValue(fr, pojoClass);
// }
//
// /**
// * Create object of type <T> from JSON in an InputStream
// * @param <T> The type to try to map to and return
// * @param is The InputStream containing the JSON
// * @param pojoClass The class to map to
// * @return return object of type <T>
// * @throws JsonParseException
// * @throws IOException
// */
// public static <T> Object fromJson(InputStream is, Class<T> pojoClass)
// throws JsonParseException, IOException{
// return m.readValue(is, pojoClass);
// }
//
// /**
// * Converts the data in the POJO to JSON
// * @param pojo The object to extract
// * @param prettyPrint Should the resulting String be indented
// * @return JSON String
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static String toJson(Object pojo, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// StringWriter sw = new StringWriter();
// JsonGenerator jg = jf.createJsonGenerator(sw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// return sw.toString();
// }
//
// /**
// * Writes the data in the POJO to a file as JSON
// * @param pojo The object to extract
// * @param fw The filewriter to write to
// * @param prettyPrint Should the resulting file text be indented
// * @throws JsonMappingException
// * @throws JsonGenerationException
// * @throws IOException
// */
// public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
// throws JsonMappingException, JsonGenerationException, IOException {
// JsonGenerator jg = jf.createJsonGenerator(fw);
// if (prettyPrint) {
// jg.useDefaultPrettyPrinter();
// }
// m.writeValue(jg, pojo);
// }
// }
// Path: src/java/org/ohd/pophealth/json/clinicalmodel/Record.java
import java.io.IOException;
import java.util.ArrayList;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.ohd.pophealth.json.JsonMapper;
public void setAllergies(ArrayList<Allergy> allergies) {
this.allergies = allergies;
}
public ArrayList<Procedure> getProcedures() {
return procedures;
}
public void setProcedures(ArrayList<Procedure> procedures) {
this.procedures = procedures;
}
public ArrayList<Order> getOrders() {
return orders;
}
public void setOrders(ArrayList<Order> orders) {
this.orders = orders;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String toJson(boolean prettyPrint) throws JsonMappingException,
JsonGenerationException, IOException {
|
return JsonMapper.toJson(this, prettyPrint);
|
google/android-arscblamer
|
java/com/google/devrel/gmscore/tools/apk/arsc/ResourceEntryStatsCollector.java
|
// Path: java/com/google/devrel/gmscore/tools/apk/arsc/ArscBlamer.java
// @AutoValue
// public abstract static class ResourceEntry {
// public abstract String packageName();
// public abstract String typeName();
// public abstract String entryName();
//
// static ResourceEntry create(TypeChunk.Entry entry) {
// PackageChunk packageChunk = Preconditions.checkNotNull(entry.parent().getPackageChunk());
// String packageName = packageChunk.getPackageName();
// String typeName = entry.typeName();
// String entryName = entry.key();
// return new AutoValue_ArscBlamer_ResourceEntry(packageName, typeName, entryName);
// }
// }
|
import com.google.common.base.Preconditions;
import com.google.devrel.gmscore.tools.apk.arsc.ArscBlamer.ResourceEntry;
import com.google.inject.Inject;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
|
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
/**
* Calculates extra information about an {@link ArscBlamer.ResourceEntry}, such as the total
* APK size the entry is responsible for.
*
* This class is not thread-safe.
*/
public class ResourceEntryStatsCollector {
/** The size in bytes of an offset in a chunk. */
private static final int OFFSET_SIZE = 4;
/** The size in bytes of overhead for styles, if present, in {@link StringPoolChunk}. */
private static final int STYLE_OVERHEAD = 8;
/**
* The number of bytes, in addition to the header, that the {@link PackageChunk} has in overhead
* excluding the chunks it contains.
*/
private static final int PACKAGE_CHUNK_OVERHEAD = 8;
|
// Path: java/com/google/devrel/gmscore/tools/apk/arsc/ArscBlamer.java
// @AutoValue
// public abstract static class ResourceEntry {
// public abstract String packageName();
// public abstract String typeName();
// public abstract String entryName();
//
// static ResourceEntry create(TypeChunk.Entry entry) {
// PackageChunk packageChunk = Preconditions.checkNotNull(entry.parent().getPackageChunk());
// String packageName = packageChunk.getPackageName();
// String typeName = entry.typeName();
// String entryName = entry.key();
// return new AutoValue_ArscBlamer_ResourceEntry(packageName, typeName, entryName);
// }
// }
// Path: java/com/google/devrel/gmscore/tools/apk/arsc/ResourceEntryStatsCollector.java
import com.google.common.base.Preconditions;
import com.google.devrel.gmscore.tools.apk.arsc.ArscBlamer.ResourceEntry;
import com.google.inject.Inject;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
/**
* Calculates extra information about an {@link ArscBlamer.ResourceEntry}, such as the total
* APK size the entry is responsible for.
*
* This class is not thread-safe.
*/
public class ResourceEntryStatsCollector {
/** The size in bytes of an offset in a chunk. */
private static final int OFFSET_SIZE = 4;
/** The size in bytes of overhead for styles, if present, in {@link StringPoolChunk}. */
private static final int STYLE_OVERHEAD = 8;
/**
* The number of bytes, in addition to the header, that the {@link PackageChunk} has in overhead
* excluding the chunks it contains.
*/
private static final int PACKAGE_CHUNK_OVERHEAD = 8;
|
private final Map<ResourceEntry, ResourceStatistics> stats = new HashMap<>();
|
dmfs/xmlobjects
|
test/org/dmfs/xml/objectpull/QualifiedNameTest.java
|
// Path: src/org/dmfs/xmlobjects/QualifiedName.java
// public final class QualifiedName
// {
// /**
// * A cache of all known {@link QualifiedName}s. This is a map of namespaces to a map of names (in the respective name space) to the {@link QualifiedName}
// * object.
// */
// private final static Map<String, Map<String, QualifiedName>> QUALIFIED_NAME_CACHE = new HashMap<String, Map<String, QualifiedName>>(64);
//
// /**
// * The namespace of this qualified name.
// */
// public final String namespace;
//
// /**
// * The name part of this qualified name.
// */
// public final String name;
//
// /**
// * The cached hash code.
// */
// private final int mHashCode;
//
//
// /**
// * Returns a {@link QualifiedName} with an empty name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise it's
// * created.
// *
// * @param name
// * The name of the {@link QualifiedName}.
// * @return The {@link QualifiedName} instance.
// */
// public static QualifiedName get(String name)
// {
// return get(null, name);
// }
//
//
// /**
// * Returns a {@link QualifiedName} with a specific name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise
// * it's created.
// *
// * @param namespace
// * The namespace of the {@link QualifiedName}.
// * @param name
// * The name of the {@link QualifiedName}.
// * @return The {@link QualifiedName} instance.
// */
// public static QualifiedName get(String namespace, String name)
// {
// if (namespace != null && namespace.length() == 0)
// {
// namespace = null;
// }
//
// synchronized (QUALIFIED_NAME_CACHE)
// {
// Map<String, QualifiedName> qualifiedNameMap = QUALIFIED_NAME_CACHE.get(namespace);
// QualifiedName qualifiedName;
// if (qualifiedNameMap == null)
// {
// qualifiedNameMap = new HashMap<String, QualifiedName>();
// qualifiedName = new QualifiedName(namespace, name);
// qualifiedNameMap.put(name, qualifiedName);
// QUALIFIED_NAME_CACHE.put(namespace, qualifiedNameMap);
// }
// else
// {
// qualifiedName = qualifiedNameMap.get(name);
// if (qualifiedName == null)
// {
// qualifiedName = new QualifiedName(namespace, name);
// qualifiedNameMap.put(name, qualifiedName);
// }
// }
// return qualifiedName;
// }
// }
//
//
// /**
// * Instantiate a new {@link QualifiedName} with the given name and namespace.
// *
// * @param namespace
// * The namespace of the qualified name.
// * @param name
// * The name part of the qualified name.
// */
// private QualifiedName(String namespace, String name)
// {
// if (name == null)
// {
// throw new IllegalArgumentException("name part of a qualified name must not be null");
// }
//
// this.namespace = namespace;
// this.name = name;
//
// mHashCode = namespace == null ? name.hashCode() : namespace.hashCode() * 31 + name.hashCode();
// }
//
//
// @Override
// public int hashCode()
// {
// return mHashCode;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// return o == this;
// }
//
//
// @Override
// public String toString()
// {
// return namespace == null ? name : namespace + ":" + name;
// }
//
//
// /**
// * Returns the qualified name in Clark notation.
// *
// * @return A {@link String} representing the qualified name.
// *
// * @see <a href="https://tools.ietf.org/html/draft-saintandre-json-namespaces-00">JavaScript Object Notation (JSON) Namespaces</a>
// */
// public String toClarkString()
// {
// return namespace == null ? name : "{" + namespace + "}" + name;
// }
// }
|
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.dmfs.xmlobjects.QualifiedName;
import org.junit.Test;
|
package org.dmfs.xml.objectpull;
/**
* Test {@link QualifiedName}s.
* <p>
* The test makes sure that {@link QualifiedName#get(String)} and {@link QualifiedName#get(String, String)} always return the same instance for the same
* parameters and that the instances are different for different parameters.
* </p>
* <p>
* The test assumes that the results are independed of the actual parameter values, since it's impossible to test with every combination of characters.
* </p>
*
* @author Marten Gajda <marten@dmfs.org>
*/
public class QualifiedNameTest
{
@Test(expected = IllegalArgumentException.class)
public void testGetNull1()
{
|
// Path: src/org/dmfs/xmlobjects/QualifiedName.java
// public final class QualifiedName
// {
// /**
// * A cache of all known {@link QualifiedName}s. This is a map of namespaces to a map of names (in the respective name space) to the {@link QualifiedName}
// * object.
// */
// private final static Map<String, Map<String, QualifiedName>> QUALIFIED_NAME_CACHE = new HashMap<String, Map<String, QualifiedName>>(64);
//
// /**
// * The namespace of this qualified name.
// */
// public final String namespace;
//
// /**
// * The name part of this qualified name.
// */
// public final String name;
//
// /**
// * The cached hash code.
// */
// private final int mHashCode;
//
//
// /**
// * Returns a {@link QualifiedName} with an empty name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise it's
// * created.
// *
// * @param name
// * The name of the {@link QualifiedName}.
// * @return The {@link QualifiedName} instance.
// */
// public static QualifiedName get(String name)
// {
// return get(null, name);
// }
//
//
// /**
// * Returns a {@link QualifiedName} with a specific name space. If the {@link QualifiedName} already exists, the existing instance is returned, otherwise
// * it's created.
// *
// * @param namespace
// * The namespace of the {@link QualifiedName}.
// * @param name
// * The name of the {@link QualifiedName}.
// * @return The {@link QualifiedName} instance.
// */
// public static QualifiedName get(String namespace, String name)
// {
// if (namespace != null && namespace.length() == 0)
// {
// namespace = null;
// }
//
// synchronized (QUALIFIED_NAME_CACHE)
// {
// Map<String, QualifiedName> qualifiedNameMap = QUALIFIED_NAME_CACHE.get(namespace);
// QualifiedName qualifiedName;
// if (qualifiedNameMap == null)
// {
// qualifiedNameMap = new HashMap<String, QualifiedName>();
// qualifiedName = new QualifiedName(namespace, name);
// qualifiedNameMap.put(name, qualifiedName);
// QUALIFIED_NAME_CACHE.put(namespace, qualifiedNameMap);
// }
// else
// {
// qualifiedName = qualifiedNameMap.get(name);
// if (qualifiedName == null)
// {
// qualifiedName = new QualifiedName(namespace, name);
// qualifiedNameMap.put(name, qualifiedName);
// }
// }
// return qualifiedName;
// }
// }
//
//
// /**
// * Instantiate a new {@link QualifiedName} with the given name and namespace.
// *
// * @param namespace
// * The namespace of the qualified name.
// * @param name
// * The name part of the qualified name.
// */
// private QualifiedName(String namespace, String name)
// {
// if (name == null)
// {
// throw new IllegalArgumentException("name part of a qualified name must not be null");
// }
//
// this.namespace = namespace;
// this.name = name;
//
// mHashCode = namespace == null ? name.hashCode() : namespace.hashCode() * 31 + name.hashCode();
// }
//
//
// @Override
// public int hashCode()
// {
// return mHashCode;
// }
//
//
// @Override
// public boolean equals(Object o)
// {
// return o == this;
// }
//
//
// @Override
// public String toString()
// {
// return namespace == null ? name : namespace + ":" + name;
// }
//
//
// /**
// * Returns the qualified name in Clark notation.
// *
// * @return A {@link String} representing the qualified name.
// *
// * @see <a href="https://tools.ietf.org/html/draft-saintandre-json-namespaces-00">JavaScript Object Notation (JSON) Namespaces</a>
// */
// public String toClarkString()
// {
// return namespace == null ? name : "{" + namespace + "}" + name;
// }
// }
// Path: test/org/dmfs/xml/objectpull/QualifiedNameTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.dmfs.xmlobjects.QualifiedName;
import org.junit.Test;
package org.dmfs.xml.objectpull;
/**
* Test {@link QualifiedName}s.
* <p>
* The test makes sure that {@link QualifiedName#get(String)} and {@link QualifiedName#get(String, String)} always return the same instance for the same
* parameters and that the instances are different for different parameters.
* </p>
* <p>
* The test assumes that the results are independed of the actual parameter values, since it's impossible to test with every combination of characters.
* </p>
*
* @author Marten Gajda <marten@dmfs.org>
*/
public class QualifiedNameTest
{
@Test(expected = IllegalArgumentException.class)
public void testGetNull1()
{
|
QualifiedName.get(null);
|
dmfs/xmlobjects
|
src/org/dmfs/xmlobjects/serializer/SerializerContext.java
|
// Path: src/org/dmfs/xmlobjects/XmlContext.java
// public class XmlContext
// {
// final Map<QualifiedName, ElementDescriptor<?>> DESCRIPTOR_MAP = new HashMap<QualifiedName, ElementDescriptor<?>>(32);
// }
|
import java.util.Set;
import org.dmfs.xmlobjects.XmlContext;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
|
/*
* Copyright (C) 2014 Marten Gajda <marten@dmfs.org>
*
* 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.dmfs.xmlobjects.serializer;
/**
* The context of the {@link XmlObjectSerializer}. Subclass it to provide additional information to your serializers.
*
* @author Marten Gajda <marten@dmfs.org>
*/
public class SerializerContext
{
/**
* The {@link XmlContext}.
*/
|
// Path: src/org/dmfs/xmlobjects/XmlContext.java
// public class XmlContext
// {
// final Map<QualifiedName, ElementDescriptor<?>> DESCRIPTOR_MAP = new HashMap<QualifiedName, ElementDescriptor<?>>(32);
// }
// Path: src/org/dmfs/xmlobjects/serializer/SerializerContext.java
import java.util.Set;
import org.dmfs.xmlobjects.XmlContext;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
/*
* Copyright (C) 2014 Marten Gajda <marten@dmfs.org>
*
* 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.dmfs.xmlobjects.serializer;
/**
* The context of the {@link XmlObjectSerializer}. Subclass it to provide additional information to your serializers.
*
* @author Marten Gajda <marten@dmfs.org>
*/
public class SerializerContext
{
/**
* The {@link XmlContext}.
*/
|
XmlContext xmlContext;
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/TestClassesCustom.java
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/TestClassesWithProp.java
// static class WithObsList {
// ObservableList<CustomObject> list;
//
// WithObsList() {
// }
//
// WithObsList(ObservableList<CustomObject> value) {
// this.list = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// WithObsList that = (WithObsList) o;
// return Objects.equals(list, that.list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(list);
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/properties/ListPropertyTypeAdapter.java
// public class ListPropertyTypeAdapter<T> extends PropertyTypeAdapter<ObservableList<T>, ListProperty<T>> {
//
// /**
// * Creates a new ListPropertyTypeAdapter.
// *
// * @param delegate
// * a delegate adapter to use for the inner list value of the property
// * @param throwOnNullProperty
// * if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
// * serialize
// */
// public ListPropertyTypeAdapter(TypeAdapter<ObservableList<T>> delegate, boolean throwOnNullProperty) {
// super(delegate, throwOnNullProperty);
// }
//
// @NotNull
// @Override
// protected ListProperty<T> createProperty(ObservableList<T> deserializedValue) {
// return new SimpleListProperty<>(deserializedValue);
// }
// }
|
import java.util.Objects;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.ObservableList;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
import org.hildan.fxgson.TestClassesWithProp.WithObsList;
import org.hildan.fxgson.adapters.properties.ListPropertyTypeAdapter;
import org.jetbrains.annotations.NotNull;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
|
package org.hildan.fxgson;
class TestClassesCustom {
static class CustomListProperty extends SimpleListProperty<CustomObject> {
CustomListProperty() {
}
CustomListProperty(ObservableList<CustomObject> initialValue) {
super(initialValue);
}
}
static class WithCustomListProp {
CustomListProperty prop = new CustomListProperty();
WithCustomListProp() {
}
WithCustomListProp(CustomListProperty value) {
this.prop = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/TestClassesWithProp.java
// static class WithObsList {
// ObservableList<CustomObject> list;
//
// WithObsList() {
// }
//
// WithObsList(ObservableList<CustomObject> value) {
// this.list = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// WithObsList that = (WithObsList) o;
// return Objects.equals(list, that.list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(list);
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/properties/ListPropertyTypeAdapter.java
// public class ListPropertyTypeAdapter<T> extends PropertyTypeAdapter<ObservableList<T>, ListProperty<T>> {
//
// /**
// * Creates a new ListPropertyTypeAdapter.
// *
// * @param delegate
// * a delegate adapter to use for the inner list value of the property
// * @param throwOnNullProperty
// * if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
// * serialize
// */
// public ListPropertyTypeAdapter(TypeAdapter<ObservableList<T>> delegate, boolean throwOnNullProperty) {
// super(delegate, throwOnNullProperty);
// }
//
// @NotNull
// @Override
// protected ListProperty<T> createProperty(ObservableList<T> deserializedValue) {
// return new SimpleListProperty<>(deserializedValue);
// }
// }
// Path: src/test/java/org/hildan/fxgson/TestClassesCustom.java
import java.util.Objects;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.ObservableList;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
import org.hildan.fxgson.TestClassesWithProp.WithObsList;
import org.hildan.fxgson.adapters.properties.ListPropertyTypeAdapter;
import org.jetbrains.annotations.NotNull;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
package org.hildan.fxgson;
class TestClassesCustom {
static class CustomListProperty extends SimpleListProperty<CustomObject> {
CustomListProperty() {
}
CustomListProperty(ObservableList<CustomObject> initialValue) {
super(initialValue);
}
}
static class WithCustomListProp {
CustomListProperty prop = new CustomListProperty();
WithCustomListProp() {
}
WithCustomListProp(CustomListProperty value) {
this.prop = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
WithObsList that = (WithObsList) o;
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/TestClassesCustom.java
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/TestClassesWithProp.java
// static class WithObsList {
// ObservableList<CustomObject> list;
//
// WithObsList() {
// }
//
// WithObsList(ObservableList<CustomObject> value) {
// this.list = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// WithObsList that = (WithObsList) o;
// return Objects.equals(list, that.list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(list);
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/properties/ListPropertyTypeAdapter.java
// public class ListPropertyTypeAdapter<T> extends PropertyTypeAdapter<ObservableList<T>, ListProperty<T>> {
//
// /**
// * Creates a new ListPropertyTypeAdapter.
// *
// * @param delegate
// * a delegate adapter to use for the inner list value of the property
// * @param throwOnNullProperty
// * if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
// * serialize
// */
// public ListPropertyTypeAdapter(TypeAdapter<ObservableList<T>> delegate, boolean throwOnNullProperty) {
// super(delegate, throwOnNullProperty);
// }
//
// @NotNull
// @Override
// protected ListProperty<T> createProperty(ObservableList<T> deserializedValue) {
// return new SimpleListProperty<>(deserializedValue);
// }
// }
|
import java.util.Objects;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.ObservableList;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
import org.hildan.fxgson.TestClassesWithProp.WithObsList;
import org.hildan.fxgson.adapters.properties.ListPropertyTypeAdapter;
import org.jetbrains.annotations.NotNull;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithObsList that = (WithObsList) o;
return Objects.equals(prop, that.list);
}
@Override
public int hashCode() {
return Objects.hash(prop);
}
}
public static class CustomFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (CustomListProperty.class.equals(type.getRawType())) {
TypeToken<ObservableList<CustomObject>> obsListType = new TypeToken<ObservableList<CustomObject>>() {};
TypeAdapter<ObservableList<CustomObject>> delegate = gson.getAdapter(obsListType);
return (TypeAdapter<T>) new CustomListPropertyAdapter(delegate, false);
}
return null;
}
}
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/TestClassesWithProp.java
// static class WithObsList {
// ObservableList<CustomObject> list;
//
// WithObsList() {
// }
//
// WithObsList(ObservableList<CustomObject> value) {
// this.list = value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// WithObsList that = (WithObsList) o;
// return Objects.equals(list, that.list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(list);
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/properties/ListPropertyTypeAdapter.java
// public class ListPropertyTypeAdapter<T> extends PropertyTypeAdapter<ObservableList<T>, ListProperty<T>> {
//
// /**
// * Creates a new ListPropertyTypeAdapter.
// *
// * @param delegate
// * a delegate adapter to use for the inner list value of the property
// * @param throwOnNullProperty
// * if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
// * serialize
// */
// public ListPropertyTypeAdapter(TypeAdapter<ObservableList<T>> delegate, boolean throwOnNullProperty) {
// super(delegate, throwOnNullProperty);
// }
//
// @NotNull
// @Override
// protected ListProperty<T> createProperty(ObservableList<T> deserializedValue) {
// return new SimpleListProperty<>(deserializedValue);
// }
// }
// Path: src/test/java/org/hildan/fxgson/TestClassesCustom.java
import java.util.Objects;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.ObservableList;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
import org.hildan.fxgson.TestClassesWithProp.WithObsList;
import org.hildan.fxgson.adapters.properties.ListPropertyTypeAdapter;
import org.jetbrains.annotations.NotNull;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithObsList that = (WithObsList) o;
return Objects.equals(prop, that.list);
}
@Override
public int hashCode() {
return Objects.hash(prop);
}
}
public static class CustomFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (CustomListProperty.class.equals(type.getRawType())) {
TypeToken<ObservableList<CustomObject>> obsListType = new TypeToken<ObservableList<CustomObject>>() {};
TypeAdapter<ObservableList<CustomObject>> delegate = gson.getAdapter(obsListType);
return (TypeAdapter<T>) new CustomListPropertyAdapter(delegate, false);
}
return null;
}
}
|
private static class CustomListPropertyAdapter extends ListPropertyTypeAdapter<CustomObject> {
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/adapters/extras/FontTypeAdapterTest.java
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
|
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
|
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class FontTypeAdapterTest {
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
// Path: src/test/java/org/hildan/fxgson/adapters/extras/FontTypeAdapterTest.java
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class FontTypeAdapterTest {
|
private static class FontExpectation extends Expectation<Font> {
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/adapters/extras/FontTypeAdapterTest.java
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
|
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
|
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class FontTypeAdapterTest {
private static class FontExpectation extends Expectation<Font> {
FontExpectation(Font value, String json) {
super(value, json);
}
}
@DataPoints
public static FontExpectation[] expectations() {
// no exotic fonts as the test must pass on most machines
return new FontExpectation[]{
new FontExpectation(Font.font("System", FontWeight.NORMAL, 12.0), "\"System,Regular,12.0\""),
new FontExpectation(Font.font("SansSerif", FontWeight.BOLD, 10.0), "\"SansSerif,Bold,10.0\""),
new FontExpectation(Font.font("System", FontPosture.ITALIC, 10.0), "\"System,Italic,10.0\""),
new FontExpectation(Font.font("System", FontWeight.BOLD, FontPosture.ITALIC, 10.0),
"\"System,Bold Italic,10.0\""),
new FontExpectation(Font.font("SansSerif", FontWeight.BOLD, FontPosture.ITALIC, 20.0),
"\"SansSerif,Bold Italic,20.0\""),
new FontExpectation(null, "null"),
};
}
@Theory
public void write(FontExpectation expectation) throws IOException {
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
// Path: src/test/java/org/hildan/fxgson/adapters/extras/FontTypeAdapterTest.java
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class FontTypeAdapterTest {
private static class FontExpectation extends Expectation<Font> {
FontExpectation(Font value, String json) {
super(value, json);
}
}
@DataPoints
public static FontExpectation[] expectations() {
// no exotic fonts as the test must pass on most machines
return new FontExpectation[]{
new FontExpectation(Font.font("System", FontWeight.NORMAL, 12.0), "\"System,Regular,12.0\""),
new FontExpectation(Font.font("SansSerif", FontWeight.BOLD, 10.0), "\"SansSerif,Bold,10.0\""),
new FontExpectation(Font.font("System", FontPosture.ITALIC, 10.0), "\"System,Italic,10.0\""),
new FontExpectation(Font.font("System", FontWeight.BOLD, FontPosture.ITALIC, 10.0),
"\"System,Bold Italic,10.0\""),
new FontExpectation(Font.font("SansSerif", FontWeight.BOLD, FontPosture.ITALIC, 20.0),
"\"SansSerif,Bold Italic,20.0\""),
new FontExpectation(null, "null"),
};
}
@Theory
public void write(FontExpectation expectation) throws IOException {
|
TestUtils.testWrite(new FontTypeAdapter(), expectation);
|
joffrey-bion/fx-gson
|
src/main/java/org/hildan/fxgson/adapters/properties/primitives/PrimitivePropertyTypeAdapter.java
|
// Path: src/main/java/org/hildan/fxgson/adapters/properties/NullPropertyException.java
// public class NullPropertyException extends RuntimeException {
//
// /**
// * Constructs a new NullPropertyException.
// */
// public NullPropertyException() {
// super("Null properties are forbidden");
// }
// }
|
import java.io.IOException;
import javafx.beans.property.Property;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.hildan.fxgson.adapters.properties.NullPropertyException;
import org.jetbrains.annotations.NotNull;
|
package org.hildan.fxgson.adapters.properties.primitives;
/**
* An abstract base for {@link TypeAdapter}s of primitive values. By default, it throws {@link NullPrimitiveException}
* when used to deserialize a null JSON value (which is illegal for a primitive). It can be configured to instantiate a
* default value instead in this case.
*
* @param <I>
* the primitive type inside the property
* @param <P>
* the type that this adapter can serialize/deserialize
*/
public abstract class PrimitivePropertyTypeAdapter<I, P extends Property<?>> extends TypeAdapter<P> {
private final TypeAdapter<I> delegate;
private final boolean throwOnNullProperty;
private final boolean crashOnNullValue;
/**
* Creates a new PrimitivePropertyTypeAdapter.
*
* @param innerValueTypeAdapter
* a delegate adapter to use for the inner value of the property
* @param throwOnNullProperty
* if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
* serialize
* @param crashOnNullValue
* if true, this adapter will throw {@link NullPrimitiveException} when reading a null value. If false, this
* adapter will call {@link #createDefaultProperty()} instead.
*/
public PrimitivePropertyTypeAdapter(TypeAdapter<I> innerValueTypeAdapter, boolean throwOnNullProperty,
boolean crashOnNullValue) {
this.delegate = innerValueTypeAdapter;
this.throwOnNullProperty = throwOnNullProperty;
this.crashOnNullValue = crashOnNullValue;
}
@Override
public void write(JsonWriter out, P property) throws IOException {
if (property == null) {
if (throwOnNullProperty) {
|
// Path: src/main/java/org/hildan/fxgson/adapters/properties/NullPropertyException.java
// public class NullPropertyException extends RuntimeException {
//
// /**
// * Constructs a new NullPropertyException.
// */
// public NullPropertyException() {
// super("Null properties are forbidden");
// }
// }
// Path: src/main/java/org/hildan/fxgson/adapters/properties/primitives/PrimitivePropertyTypeAdapter.java
import java.io.IOException;
import javafx.beans.property.Property;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.hildan.fxgson.adapters.properties.NullPropertyException;
import org.jetbrains.annotations.NotNull;
package org.hildan.fxgson.adapters.properties.primitives;
/**
* An abstract base for {@link TypeAdapter}s of primitive values. By default, it throws {@link NullPrimitiveException}
* when used to deserialize a null JSON value (which is illegal for a primitive). It can be configured to instantiate a
* default value instead in this case.
*
* @param <I>
* the primitive type inside the property
* @param <P>
* the type that this adapter can serialize/deserialize
*/
public abstract class PrimitivePropertyTypeAdapter<I, P extends Property<?>> extends TypeAdapter<P> {
private final TypeAdapter<I> delegate;
private final boolean throwOnNullProperty;
private final boolean crashOnNullValue;
/**
* Creates a new PrimitivePropertyTypeAdapter.
*
* @param innerValueTypeAdapter
* a delegate adapter to use for the inner value of the property
* @param throwOnNullProperty
* if true, this adapter will throw {@link NullPropertyException} when given a null {@link Property} to
* serialize
* @param crashOnNullValue
* if true, this adapter will throw {@link NullPrimitiveException} when reading a null value. If false, this
* adapter will call {@link #createDefaultProperty()} instead.
*/
public PrimitivePropertyTypeAdapter(TypeAdapter<I> innerValueTypeAdapter, boolean throwOnNullProperty,
boolean crashOnNullValue) {
this.delegate = innerValueTypeAdapter;
this.throwOnNullProperty = throwOnNullProperty;
this.crashOnNullValue = crashOnNullValue;
}
@Override
public void write(JsonWriter out, P property) throws IOException {
if (property == null) {
if (throwOnNullProperty) {
|
throw new NullPropertyException();
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/TestClassesWithProp.java
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
|
import java.util.Objects;
import java.util.function.BiFunction;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.LongProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SetProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleMapProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleSetProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
|
static class WithStringProp {
StringProperty prop = new SimpleStringProperty();
WithStringProp() {
}
WithStringProp(String value) {
this.prop = new SimpleStringProperty(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithStringProp that = (WithStringProp) o;
return propEquals(prop, that.prop);
}
@Override
public int hashCode() {
return Objects.hash(prop);
}
}
static class WithObjectProp {
|
// Path: src/test/java/org/hildan/fxgson/TestClassesSimple.java
// static class CustomObject {
//
// String name;
//
// CustomObject(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// CustomObject that = (CustomObject) o;
// return Objects.equals(name, that.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name);
// }
// }
// Path: src/test/java/org/hildan/fxgson/TestClassesWithProp.java
import java.util.Objects;
import java.util.function.BiFunction;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.LongProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SetProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleMapProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleSetProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import org.hildan.fxgson.TestClassesSimple.CustomObject;
static class WithStringProp {
StringProperty prop = new SimpleStringProperty();
WithStringProp() {
}
WithStringProp(String value) {
this.prop = new SimpleStringProperty(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WithStringProp that = (WithStringProp) o;
return propEquals(prop, that.prop);
}
@Override
public int hashCode() {
return Objects.hash(prop);
}
}
static class WithObjectProp {
|
ObjectProperty<CustomObject> prop = new SimpleObjectProperty<>();
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapterTest.java
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
|
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.paint.Color;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
|
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class ColorTypeAdapterTest {
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
// Path: src/test/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapterTest.java
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.paint.Color;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class ColorTypeAdapterTest {
|
private static class ColorExpectation extends Expectation<Color> {
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapterTest.java
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
|
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.paint.Color;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
|
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class ColorTypeAdapterTest {
private static class ColorExpectation extends Expectation<Color> {
ColorExpectation(Color value, String json) {
super(value, json);
}
}
@DataPoints
public static Expectation<Color>[] expectations() {
return new ColorExpectation[]{
new ColorExpectation(Color.BLUE, "\"#0000ffff\""),
new ColorExpectation(Color.RED, "\"#ff0000ff\""),
new ColorExpectation(null, "null"),
};
}
@Theory
public void write(ColorExpectation expectation) throws IOException {
|
// Path: src/test/java/org/hildan/fxgson/test/Expectation.java
// public class Expectation<T> {
//
// public final T object;
//
// public final String json;
//
// public Expectation(T object, String json) {
// this.object = object;
// this.json = json;
// }
//
// @Override
// public String toString() {
// return "Expectation{" + "object=" + object + ", json='" + json + '\'' + '}';
// }
// }
//
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
// Path: src/test/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapterTest.java
import java.io.IOException;
import java.io.StringReader;
import javafx.scene.paint.Color;
import com.google.gson.stream.JsonReader;
import org.hildan.fxgson.test.Expectation;
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
package org.hildan.fxgson.adapters.extras;
@RunWith(Theories.class)
public class ColorTypeAdapterTest {
private static class ColorExpectation extends Expectation<Color> {
ColorExpectation(Color value, String json) {
super(value, json);
}
}
@DataPoints
public static Expectation<Color>[] expectations() {
return new ColorExpectation[]{
new ColorExpectation(Color.BLUE, "\"#0000ffff\""),
new ColorExpectation(Color.RED, "\"#ff0000ff\""),
new ColorExpectation(null, "null"),
};
}
@Theory
public void write(ColorExpectation expectation) throws IOException {
|
TestUtils.testWrite(new ColorTypeAdapter(), expectation);
|
joffrey-bion/fx-gson
|
src/main/java/org/hildan/fxgson/factories/JavaFxExtraTypeAdapterFactory.java
|
// Path: src/main/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapter.java
// public class ColorTypeAdapter extends TypeAdapter<Color> {
//
// @Override
// public void write(JsonWriter out, Color value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// int red = (int) Math.round(value.getRed() * 255.0);
// int green = (int) Math.round(value.getGreen() * 255.0);
// int blue = (int) Math.round(value.getBlue() * 255.0);
// int opacity = (int) Math.round(value.getOpacity() * 255.0);
// String colorStr = String.format("#%02x%02x%02x%02x", red, green, blue, opacity);
// out.value(colorStr);
// }
//
// @Override
// public Color read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// try {
// return Color.web(value);
// } catch (IllegalArgumentException e) {
// throw new InvalidColorException(value, in.getPath(), e);
// }
// }
//
// public static class InvalidColorException extends RuntimeException {
//
// private static final String MSG_TEMPLATE =
// "Invalid color format '%s' at path %s, please use a format supported by Color.web()";
//
// InvalidColorException(String value, String path, Throwable cause) {
// super(String.format(MSG_TEMPLATE, value, path), cause);
// }
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/extras/FontTypeAdapter.java
// public class FontTypeAdapter extends TypeAdapter<Font> {
//
// @Override
// public void write(JsonWriter out, Font value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// String family = value.getFamily();
// String style = value.getStyle();
// double size = value.getSize();
// out.value(family + "," + style + "," + size);
// }
//
// @Override
// public Font read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// String path = in.getPath();
//
// String[] components = splitComponents(value, path);
// String family = components[0];
// String style = components[1];
// String sizeStr = components[2];
//
// FontWeight weight = extractWeight(style);
// FontPosture posture = extractPosture(style);
// double size = extractSize(sizeStr, path);
//
// return Font.font(family, weight, posture, size);
// }
//
// private static String[] splitComponents(String value, String path) {
// String[] font = value.split(",");
// if (font.length < 3) {
// throw InvalidFontException.missingComponent(value, path);
// }
// return font;
// }
//
// private static FontWeight extractWeight(String style) {
// for (String styleWord : style.split("\\s")) {
// FontWeight weight = FontWeight.findByName(styleWord);
// if (weight != null && weight != FontWeight.NORMAL) {
// return weight;
// }
// }
// return FontWeight.NORMAL;
// }
//
// private static FontPosture extractPosture(String style) {
// for (String styleWord : style.split("\\s")) {
// FontPosture posture = FontPosture.findByName(styleWord);
// if (posture != null && posture != FontPosture.REGULAR) {
// return posture;
// }
// }
// return FontPosture.REGULAR;
// }
//
// private static double extractSize(String size, String path) {
// try {
// return Double.parseDouble(size);
// } catch (NumberFormatException e) {
// throw InvalidFontException.invalidSize(size, path, e);
// }
// }
//
// public static class InvalidFontException extends RuntimeException {
//
// InvalidFontException(String message) {
// super(message);
// }
//
// InvalidFontException(String message, Throwable cause) {
// super(message, cause);
// }
//
// static InvalidFontException missingComponent(String value, String path) {
// return new InvalidFontException("Missing component in the font at path " + path + ", got '" + value + "'");
// }
//
// static InvalidFontException invalidSize(String value, String path, Throwable cause) {
// return new InvalidFontException("Invalid size for the font at path " + path + ", got '" + value + "'",
// cause);
// }
// }
// }
|
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import org.hildan.fxgson.adapters.extras.ColorTypeAdapter;
import org.hildan.fxgson.adapters.extras.FontTypeAdapter;
|
package org.hildan.fxgson.factories;
/**
* A {@link TypeAdapterFactory} for JavaFX's {@link Color} and {@link Font} classes.
*/
public class JavaFxExtraTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> clazz = type.getRawType();
if (Color.class.isAssignableFrom(clazz)) {
|
// Path: src/main/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapter.java
// public class ColorTypeAdapter extends TypeAdapter<Color> {
//
// @Override
// public void write(JsonWriter out, Color value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// int red = (int) Math.round(value.getRed() * 255.0);
// int green = (int) Math.round(value.getGreen() * 255.0);
// int blue = (int) Math.round(value.getBlue() * 255.0);
// int opacity = (int) Math.round(value.getOpacity() * 255.0);
// String colorStr = String.format("#%02x%02x%02x%02x", red, green, blue, opacity);
// out.value(colorStr);
// }
//
// @Override
// public Color read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// try {
// return Color.web(value);
// } catch (IllegalArgumentException e) {
// throw new InvalidColorException(value, in.getPath(), e);
// }
// }
//
// public static class InvalidColorException extends RuntimeException {
//
// private static final String MSG_TEMPLATE =
// "Invalid color format '%s' at path %s, please use a format supported by Color.web()";
//
// InvalidColorException(String value, String path, Throwable cause) {
// super(String.format(MSG_TEMPLATE, value, path), cause);
// }
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/extras/FontTypeAdapter.java
// public class FontTypeAdapter extends TypeAdapter<Font> {
//
// @Override
// public void write(JsonWriter out, Font value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// String family = value.getFamily();
// String style = value.getStyle();
// double size = value.getSize();
// out.value(family + "," + style + "," + size);
// }
//
// @Override
// public Font read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// String path = in.getPath();
//
// String[] components = splitComponents(value, path);
// String family = components[0];
// String style = components[1];
// String sizeStr = components[2];
//
// FontWeight weight = extractWeight(style);
// FontPosture posture = extractPosture(style);
// double size = extractSize(sizeStr, path);
//
// return Font.font(family, weight, posture, size);
// }
//
// private static String[] splitComponents(String value, String path) {
// String[] font = value.split(",");
// if (font.length < 3) {
// throw InvalidFontException.missingComponent(value, path);
// }
// return font;
// }
//
// private static FontWeight extractWeight(String style) {
// for (String styleWord : style.split("\\s")) {
// FontWeight weight = FontWeight.findByName(styleWord);
// if (weight != null && weight != FontWeight.NORMAL) {
// return weight;
// }
// }
// return FontWeight.NORMAL;
// }
//
// private static FontPosture extractPosture(String style) {
// for (String styleWord : style.split("\\s")) {
// FontPosture posture = FontPosture.findByName(styleWord);
// if (posture != null && posture != FontPosture.REGULAR) {
// return posture;
// }
// }
// return FontPosture.REGULAR;
// }
//
// private static double extractSize(String size, String path) {
// try {
// return Double.parseDouble(size);
// } catch (NumberFormatException e) {
// throw InvalidFontException.invalidSize(size, path, e);
// }
// }
//
// public static class InvalidFontException extends RuntimeException {
//
// InvalidFontException(String message) {
// super(message);
// }
//
// InvalidFontException(String message, Throwable cause) {
// super(message, cause);
// }
//
// static InvalidFontException missingComponent(String value, String path) {
// return new InvalidFontException("Missing component in the font at path " + path + ", got '" + value + "'");
// }
//
// static InvalidFontException invalidSize(String value, String path, Throwable cause) {
// return new InvalidFontException("Invalid size for the font at path " + path + ", got '" + value + "'",
// cause);
// }
// }
// }
// Path: src/main/java/org/hildan/fxgson/factories/JavaFxExtraTypeAdapterFactory.java
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import org.hildan.fxgson.adapters.extras.ColorTypeAdapter;
import org.hildan.fxgson.adapters.extras.FontTypeAdapter;
package org.hildan.fxgson.factories;
/**
* A {@link TypeAdapterFactory} for JavaFX's {@link Color} and {@link Font} classes.
*/
public class JavaFxExtraTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> clazz = type.getRawType();
if (Color.class.isAssignableFrom(clazz)) {
|
return (TypeAdapter<T>) new ColorTypeAdapter();
|
joffrey-bion/fx-gson
|
src/main/java/org/hildan/fxgson/factories/JavaFxExtraTypeAdapterFactory.java
|
// Path: src/main/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapter.java
// public class ColorTypeAdapter extends TypeAdapter<Color> {
//
// @Override
// public void write(JsonWriter out, Color value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// int red = (int) Math.round(value.getRed() * 255.0);
// int green = (int) Math.round(value.getGreen() * 255.0);
// int blue = (int) Math.round(value.getBlue() * 255.0);
// int opacity = (int) Math.round(value.getOpacity() * 255.0);
// String colorStr = String.format("#%02x%02x%02x%02x", red, green, blue, opacity);
// out.value(colorStr);
// }
//
// @Override
// public Color read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// try {
// return Color.web(value);
// } catch (IllegalArgumentException e) {
// throw new InvalidColorException(value, in.getPath(), e);
// }
// }
//
// public static class InvalidColorException extends RuntimeException {
//
// private static final String MSG_TEMPLATE =
// "Invalid color format '%s' at path %s, please use a format supported by Color.web()";
//
// InvalidColorException(String value, String path, Throwable cause) {
// super(String.format(MSG_TEMPLATE, value, path), cause);
// }
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/extras/FontTypeAdapter.java
// public class FontTypeAdapter extends TypeAdapter<Font> {
//
// @Override
// public void write(JsonWriter out, Font value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// String family = value.getFamily();
// String style = value.getStyle();
// double size = value.getSize();
// out.value(family + "," + style + "," + size);
// }
//
// @Override
// public Font read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// String path = in.getPath();
//
// String[] components = splitComponents(value, path);
// String family = components[0];
// String style = components[1];
// String sizeStr = components[2];
//
// FontWeight weight = extractWeight(style);
// FontPosture posture = extractPosture(style);
// double size = extractSize(sizeStr, path);
//
// return Font.font(family, weight, posture, size);
// }
//
// private static String[] splitComponents(String value, String path) {
// String[] font = value.split(",");
// if (font.length < 3) {
// throw InvalidFontException.missingComponent(value, path);
// }
// return font;
// }
//
// private static FontWeight extractWeight(String style) {
// for (String styleWord : style.split("\\s")) {
// FontWeight weight = FontWeight.findByName(styleWord);
// if (weight != null && weight != FontWeight.NORMAL) {
// return weight;
// }
// }
// return FontWeight.NORMAL;
// }
//
// private static FontPosture extractPosture(String style) {
// for (String styleWord : style.split("\\s")) {
// FontPosture posture = FontPosture.findByName(styleWord);
// if (posture != null && posture != FontPosture.REGULAR) {
// return posture;
// }
// }
// return FontPosture.REGULAR;
// }
//
// private static double extractSize(String size, String path) {
// try {
// return Double.parseDouble(size);
// } catch (NumberFormatException e) {
// throw InvalidFontException.invalidSize(size, path, e);
// }
// }
//
// public static class InvalidFontException extends RuntimeException {
//
// InvalidFontException(String message) {
// super(message);
// }
//
// InvalidFontException(String message, Throwable cause) {
// super(message, cause);
// }
//
// static InvalidFontException missingComponent(String value, String path) {
// return new InvalidFontException("Missing component in the font at path " + path + ", got '" + value + "'");
// }
//
// static InvalidFontException invalidSize(String value, String path, Throwable cause) {
// return new InvalidFontException("Invalid size for the font at path " + path + ", got '" + value + "'",
// cause);
// }
// }
// }
|
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import org.hildan.fxgson.adapters.extras.ColorTypeAdapter;
import org.hildan.fxgson.adapters.extras.FontTypeAdapter;
|
package org.hildan.fxgson.factories;
/**
* A {@link TypeAdapterFactory} for JavaFX's {@link Color} and {@link Font} classes.
*/
public class JavaFxExtraTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> clazz = type.getRawType();
if (Color.class.isAssignableFrom(clazz)) {
return (TypeAdapter<T>) new ColorTypeAdapter();
}
if (Font.class.isAssignableFrom(clazz)) {
|
// Path: src/main/java/org/hildan/fxgson/adapters/extras/ColorTypeAdapter.java
// public class ColorTypeAdapter extends TypeAdapter<Color> {
//
// @Override
// public void write(JsonWriter out, Color value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// int red = (int) Math.round(value.getRed() * 255.0);
// int green = (int) Math.round(value.getGreen() * 255.0);
// int blue = (int) Math.round(value.getBlue() * 255.0);
// int opacity = (int) Math.round(value.getOpacity() * 255.0);
// String colorStr = String.format("#%02x%02x%02x%02x", red, green, blue, opacity);
// out.value(colorStr);
// }
//
// @Override
// public Color read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// try {
// return Color.web(value);
// } catch (IllegalArgumentException e) {
// throw new InvalidColorException(value, in.getPath(), e);
// }
// }
//
// public static class InvalidColorException extends RuntimeException {
//
// private static final String MSG_TEMPLATE =
// "Invalid color format '%s' at path %s, please use a format supported by Color.web()";
//
// InvalidColorException(String value, String path, Throwable cause) {
// super(String.format(MSG_TEMPLATE, value, path), cause);
// }
// }
// }
//
// Path: src/main/java/org/hildan/fxgson/adapters/extras/FontTypeAdapter.java
// public class FontTypeAdapter extends TypeAdapter<Font> {
//
// @Override
// public void write(JsonWriter out, Font value) throws IOException {
// if (value == null) {
// out.nullValue();
// return;
// }
// String family = value.getFamily();
// String style = value.getStyle();
// double size = value.getSize();
// out.value(family + "," + style + "," + size);
// }
//
// @Override
// public Font read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// }
// String value = in.nextString();
// String path = in.getPath();
//
// String[] components = splitComponents(value, path);
// String family = components[0];
// String style = components[1];
// String sizeStr = components[2];
//
// FontWeight weight = extractWeight(style);
// FontPosture posture = extractPosture(style);
// double size = extractSize(sizeStr, path);
//
// return Font.font(family, weight, posture, size);
// }
//
// private static String[] splitComponents(String value, String path) {
// String[] font = value.split(",");
// if (font.length < 3) {
// throw InvalidFontException.missingComponent(value, path);
// }
// return font;
// }
//
// private static FontWeight extractWeight(String style) {
// for (String styleWord : style.split("\\s")) {
// FontWeight weight = FontWeight.findByName(styleWord);
// if (weight != null && weight != FontWeight.NORMAL) {
// return weight;
// }
// }
// return FontWeight.NORMAL;
// }
//
// private static FontPosture extractPosture(String style) {
// for (String styleWord : style.split("\\s")) {
// FontPosture posture = FontPosture.findByName(styleWord);
// if (posture != null && posture != FontPosture.REGULAR) {
// return posture;
// }
// }
// return FontPosture.REGULAR;
// }
//
// private static double extractSize(String size, String path) {
// try {
// return Double.parseDouble(size);
// } catch (NumberFormatException e) {
// throw InvalidFontException.invalidSize(size, path, e);
// }
// }
//
// public static class InvalidFontException extends RuntimeException {
//
// InvalidFontException(String message) {
// super(message);
// }
//
// InvalidFontException(String message, Throwable cause) {
// super(message, cause);
// }
//
// static InvalidFontException missingComponent(String value, String path) {
// return new InvalidFontException("Missing component in the font at path " + path + ", got '" + value + "'");
// }
//
// static InvalidFontException invalidSize(String value, String path, Throwable cause) {
// return new InvalidFontException("Invalid size for the font at path " + path + ", got '" + value + "'",
// cause);
// }
// }
// }
// Path: src/main/java/org/hildan/fxgson/factories/JavaFxExtraTypeAdapterFactory.java
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import org.hildan.fxgson.adapters.extras.ColorTypeAdapter;
import org.hildan.fxgson.adapters.extras.FontTypeAdapter;
package org.hildan.fxgson.factories;
/**
* A {@link TypeAdapterFactory} for JavaFX's {@link Color} and {@link Font} classes.
*/
public class JavaFxExtraTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<? super T> clazz = type.getRawType();
if (Color.class.isAssignableFrom(clazz)) {
return (TypeAdapter<T>) new ColorTypeAdapter();
}
if (Font.class.isAssignableFrom(clazz)) {
|
return (TypeAdapter<T>) new FontTypeAdapter();
|
joffrey-bion/fx-gson
|
src/test/java/org/hildan/fxgson/factories/TypeHelperTest.java
|
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
|
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
|
package org.hildan.fxgson.factories;
public class TypeHelperTest {
@Test
public void typeHelper_cantBeInstantiated() {
|
// Path: src/test/java/org/hildan/fxgson/test/TestUtils.java
// public class TestUtils {
//
// public static <T> void testWrite(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringWriter strWriter = new StringWriter();
// JsonWriter jsonWriter = new JsonWriter(strWriter);
// adapter.write(jsonWriter, expectation.object);
// assertEquals(expectation.json, strWriter.toString());
// }
//
// public static <T> void testRead(TypeAdapter<T> adapter, Expectation<T> expectation) throws IOException {
// StringReader strReader = new StringReader(expectation.json);
// JsonReader jsonReader = new JsonReader(strReader);
// T deserializedValue = adapter.read(jsonReader);
// assertEquals(expectation.object, deserializedValue);
// }
//
// public static void assertCannotBeInstantiated(Class<?> cls) {
// try {
// final Constructor<?> c = cls.getDeclaredConstructors()[0];
// c.setAccessible(true);
// c.newInstance();
// fail();
// } catch (InvocationTargetException ite) {
// Throwable targetException = ite.getTargetException();
// assertNotNull(targetException);
// assertEquals(targetException.getClass(), InstantiationException.class);
// } catch (IllegalAccessException e) {
// fail("the constructor is made accessible in the test, this should not happen");
// } catch (InstantiationException e) {
// fail("this test is not expected to be run on abstract classes");
// }
// }
// }
// Path: src/test/java/org/hildan/fxgson/factories/TypeHelperTest.java
import org.hildan.fxgson.test.TestUtils;
import org.junit.Test;
package org.hildan.fxgson.factories;
public class TypeHelperTest {
@Test
public void typeHelper_cantBeInstantiated() {
|
TestUtils.assertCannotBeInstantiated(TypeHelper.class);
|
fireshort/spring-boot-quickstart
|
src/main/java/org/springside/examples/quickstart/config/ActiveMQConfiguration.java
|
// Path: src/main/java/org/springside/examples/quickstart/jms/NotifyMessageListener.java
// public class NotifyMessageListener implements MessageListener {
//
// private static Logger logger = LoggerFactory.getLogger(NotifyMessageListener.class);
//
// // @Autowired(required = false)
// // private SimpleMailService simpleMailService;
//
// /**
// * MessageListener回调函数.
// */
// @Override
// public void onMessage(Message message) {
// try {
// MapMessage mapMessage = (MapMessage) message;
// // 打印消息详情
// logger.info("UserName:{}, Email:{}", mapMessage.getString("userName"), mapMessage.getString("email"));
//
// // 发送邮件
// // if (simpleMailService != null) {
// // simpleMailService.sendNotificationMail(mapMessage.getString("userName"));
// // }
// } catch (Exception e) {
// logger.error("处理消息时发生异常.", e);
// }
// }
// }
|
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springside.examples.quickstart.jms.NotifyMessageListener;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Topic;
|
public Queue queue() {
return new ActiveMQQueue("q.notify");
}
@Bean(name = "notifyTopic")
public Topic topic() {
return new ActiveMQTopic("t.notify");
}
@Bean
public DefaultMessageListenerContainer queueContainer() {
DefaultMessageListenerContainer queueContainer = new DefaultMessageListenerContainer();
queueContainer.setConnectionFactory(connectionFactory());
queueContainer.setDestination(queue());
queueContainer.setMessageListener(notifyMessageListener());
queueContainer.setConcurrentConsumers(10);
return queueContainer;
}
@Bean
public DefaultMessageListenerContainer topicContainer() {
DefaultMessageListenerContainer topicContainer = new DefaultMessageListenerContainer();
topicContainer.setConnectionFactory(connectionFactory());
topicContainer.setDestination(topic());
topicContainer.setMessageListener(notifyMessageListener());
return topicContainer;
}
@Bean
public MessageListener notifyMessageListener() {
|
// Path: src/main/java/org/springside/examples/quickstart/jms/NotifyMessageListener.java
// public class NotifyMessageListener implements MessageListener {
//
// private static Logger logger = LoggerFactory.getLogger(NotifyMessageListener.class);
//
// // @Autowired(required = false)
// // private SimpleMailService simpleMailService;
//
// /**
// * MessageListener回调函数.
// */
// @Override
// public void onMessage(Message message) {
// try {
// MapMessage mapMessage = (MapMessage) message;
// // 打印消息详情
// logger.info("UserName:{}, Email:{}", mapMessage.getString("userName"), mapMessage.getString("email"));
//
// // 发送邮件
// // if (simpleMailService != null) {
// // simpleMailService.sendNotificationMail(mapMessage.getString("userName"));
// // }
// } catch (Exception e) {
// logger.error("处理消息时发生异常.", e);
// }
// }
// }
// Path: src/main/java/org/springside/examples/quickstart/config/ActiveMQConfiguration.java
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springside.examples.quickstart.jms.NotifyMessageListener;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Topic;
public Queue queue() {
return new ActiveMQQueue("q.notify");
}
@Bean(name = "notifyTopic")
public Topic topic() {
return new ActiveMQTopic("t.notify");
}
@Bean
public DefaultMessageListenerContainer queueContainer() {
DefaultMessageListenerContainer queueContainer = new DefaultMessageListenerContainer();
queueContainer.setConnectionFactory(connectionFactory());
queueContainer.setDestination(queue());
queueContainer.setMessageListener(notifyMessageListener());
queueContainer.setConcurrentConsumers(10);
return queueContainer;
}
@Bean
public DefaultMessageListenerContainer topicContainer() {
DefaultMessageListenerContainer topicContainer = new DefaultMessageListenerContainer();
topicContainer.setConnectionFactory(connectionFactory());
topicContainer.setDestination(topic());
topicContainer.setMessageListener(notifyMessageListener());
return topicContainer;
}
@Bean
public MessageListener notifyMessageListener() {
|
return new NotifyMessageListener();
|
fireshort/spring-boot-quickstart
|
src/main/java/org/springside/examples/quickstart/Application.java
|
// Path: src/main/java/org/springside/examples/quickstart/config/MySiteMeshFilter.java
// public class MySiteMeshFilter extends ConfigurableSiteMeshFilter {
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
// builder.addDecoratorPath("/*", "/WEB-INF/layouts/default.jsp");
// builder.addExcludedPath("/static/*");
// builder.addExcludedPath("/api/*");
// }
// }
|
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springside.examples.quickstart.config.MySiteMeshFilter;
import javax.servlet.Filter;
import javax.validation.Validator;
import java.io.FileNotFoundException;
|
package org.springside.examples.quickstart;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
//@Configuration定义配置类
//you can use @ComponentScan to automatically pickup all Spring components, including @Configuration classes.
public class Application {
public static void main(String[] args) throws FileNotFoundException {
new SpringApplication(Application.class).run(args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/WEB-INF/views/error/401.jsp");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/WEB-INF/views/error/404.jsp");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/WEB-INF/views/error/500.jsp");
container.addErrorPages(error401Page, error404Page, error500Page);
}
};
}
@Bean
//JSR303 Validator定义
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
// @Bean
// public FilterRegistrationBean sitemeshFilter() {
// FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(new SiteMeshFilter());
// registration.addInitParameter("sitemesh.configfile","classpath:sitemesh/sitemesh.xml");
// registration.addUrlPatterns("/*");
// registration.setOrder(Ordered.LOWEST_PRECEDENCE);
// return registration;
// }
@Bean
public Filter sitemeshFilter() {
|
// Path: src/main/java/org/springside/examples/quickstart/config/MySiteMeshFilter.java
// public class MySiteMeshFilter extends ConfigurableSiteMeshFilter {
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
// builder.addDecoratorPath("/*", "/WEB-INF/layouts/default.jsp");
// builder.addExcludedPath("/static/*");
// builder.addExcludedPath("/api/*");
// }
// }
// Path: src/main/java/org/springside/examples/quickstart/Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springside.examples.quickstart.config.MySiteMeshFilter;
import javax.servlet.Filter;
import javax.validation.Validator;
import java.io.FileNotFoundException;
package org.springside.examples.quickstart;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
//@Configuration定义配置类
//you can use @ComponentScan to automatically pickup all Spring components, including @Configuration classes.
public class Application {
public static void main(String[] args) throws FileNotFoundException {
new SpringApplication(Application.class).run(args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/WEB-INF/views/error/401.jsp");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/WEB-INF/views/error/404.jsp");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/WEB-INF/views/error/500.jsp");
container.addErrorPages(error401Page, error404Page, error500Page);
}
};
}
@Bean
//JSR303 Validator定义
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
// @Bean
// public FilterRegistrationBean sitemeshFilter() {
// FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(new SiteMeshFilter());
// registration.addInitParameter("sitemesh.configfile","classpath:sitemesh/sitemesh.xml");
// registration.addUrlPatterns("/*");
// registration.setOrder(Ordered.LOWEST_PRECEDENCE);
// return registration;
// }
@Bean
public Filter sitemeshFilter() {
|
return new MySiteMeshFilter();
|
fireshort/spring-boot-quickstart
|
src/main/java/org/springside/examples/quickstart/service/account/UserService.java
|
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java
// @Entity
// @Table(name = "ss_user")
// public class User extends IdEntity implements Serializable {
// private String loginName;
// private String name;
// private String plainPassword;
// private String password;
// private String salt;
// private String roles;
// private Date registerDate;
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// private String email;
//
// public User() {
// }
//
// public User(Long id) {
// this.id = id;
// }
//
// @NotBlank
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// @NotBlank
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// // 不持久化到数据库,也不显示在Restful接口的属性.
// @Transient
// @JsonIgnore
// public String getPlainPassword() {
// return plainPassword;
// }
//
// public void setPlainPassword(String plainPassword) {
// this.plainPassword = plainPassword;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public void setSalt(String salt) {
// this.salt = salt;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Transient
// @JsonIgnore
// public List<String> getRoleList() {
// // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
// return ImmutableList.copyOf(StringUtils.split(roles, ","));
// }
//
// // 设定JSON序列化时的日期格式
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
//
// Path: src/main/java/org/springside/examples/quickstart/repository/UserDao.java
// public interface UserDao extends PagingAndSortingRepository<User, Long> {
// User findByLoginName(String loginName);
// }
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springside.examples.quickstart.entity.User;
import org.springside.examples.quickstart.repository.UserDao;
import java.util.Date;
|
package org.springside.examples.quickstart.service.account;
/**
* Created by Ivan on 2016/1/19.
* @Cacheable 同时和 @Transactional 在一起的话不生效,所以缓存方法单独放到这个类。
*/
@Component
public class UserService {
private static Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
private AccountService accountService;
@Cacheable(value = "userCache", key = "'user'+#id")
|
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java
// @Entity
// @Table(name = "ss_user")
// public class User extends IdEntity implements Serializable {
// private String loginName;
// private String name;
// private String plainPassword;
// private String password;
// private String salt;
// private String roles;
// private Date registerDate;
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// private String email;
//
// public User() {
// }
//
// public User(Long id) {
// this.id = id;
// }
//
// @NotBlank
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// @NotBlank
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// // 不持久化到数据库,也不显示在Restful接口的属性.
// @Transient
// @JsonIgnore
// public String getPlainPassword() {
// return plainPassword;
// }
//
// public void setPlainPassword(String plainPassword) {
// this.plainPassword = plainPassword;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public void setSalt(String salt) {
// this.salt = salt;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Transient
// @JsonIgnore
// public List<String> getRoleList() {
// // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
// return ImmutableList.copyOf(StringUtils.split(roles, ","));
// }
//
// // 设定JSON序列化时的日期格式
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
//
// Path: src/main/java/org/springside/examples/quickstart/repository/UserDao.java
// public interface UserDao extends PagingAndSortingRepository<User, Long> {
// User findByLoginName(String loginName);
// }
// Path: src/main/java/org/springside/examples/quickstart/service/account/UserService.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springside.examples.quickstart.entity.User;
import org.springside.examples.quickstart.repository.UserDao;
import java.util.Date;
package org.springside.examples.quickstart.service.account;
/**
* Created by Ivan on 2016/1/19.
* @Cacheable 同时和 @Transactional 在一起的话不生效,所以缓存方法单独放到这个类。
*/
@Component
public class UserService {
private static Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
private AccountService accountService;
@Cacheable(value = "userCache", key = "'user'+#id")
|
public User getUser(Long id) {
|
fireshort/spring-boot-quickstart
|
src/test/java/org/springside/examples/quickstart/data/TaskData.java
|
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java
// @Entity
// @Table(name = "ss_task")
// public class Task extends IdEntity {
//
// private String title;
// private String description;
// private User user;
//
// // JSR303 BeanValidator的校验规则
// @NotBlank
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// // JPA 基于USER_ID列的多对一关系定义
// @ManyToOne
// @JoinColumn(name = "user_id")
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
//
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java
// @Entity
// @Table(name = "ss_user")
// public class User extends IdEntity implements Serializable {
// private String loginName;
// private String name;
// private String plainPassword;
// private String password;
// private String salt;
// private String roles;
// private Date registerDate;
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// private String email;
//
// public User() {
// }
//
// public User(Long id) {
// this.id = id;
// }
//
// @NotBlank
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// @NotBlank
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// // 不持久化到数据库,也不显示在Restful接口的属性.
// @Transient
// @JsonIgnore
// public String getPlainPassword() {
// return plainPassword;
// }
//
// public void setPlainPassword(String plainPassword) {
// this.plainPassword = plainPassword;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public void setSalt(String salt) {
// this.salt = salt;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Transient
// @JsonIgnore
// public List<String> getRoleList() {
// // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
// return ImmutableList.copyOf(StringUtils.split(roles, ","));
// }
//
// // 设定JSON序列化时的日期格式
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
|
import org.springside.examples.quickstart.entity.User;
import org.springside.modules.test.data.RandomData;
import org.springside.examples.quickstart.entity.Task;
|
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.examples.quickstart.data;
/**
* Task相关实体测试数据生成.
*
* @author calvin
*/
public class TaskData {
public static Task randomTask() {
Task task = new Task();
task.setTitle(randomTitle());
|
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java
// @Entity
// @Table(name = "ss_task")
// public class Task extends IdEntity {
//
// private String title;
// private String description;
// private User user;
//
// // JSR303 BeanValidator的校验规则
// @NotBlank
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// // JPA 基于USER_ID列的多对一关系定义
// @ManyToOne
// @JoinColumn(name = "user_id")
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
//
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java
// @Entity
// @Table(name = "ss_user")
// public class User extends IdEntity implements Serializable {
// private String loginName;
// private String name;
// private String plainPassword;
// private String password;
// private String salt;
// private String roles;
// private Date registerDate;
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// private String email;
//
// public User() {
// }
//
// public User(Long id) {
// this.id = id;
// }
//
// @NotBlank
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// @NotBlank
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// // 不持久化到数据库,也不显示在Restful接口的属性.
// @Transient
// @JsonIgnore
// public String getPlainPassword() {
// return plainPassword;
// }
//
// public void setPlainPassword(String plainPassword) {
// this.plainPassword = plainPassword;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public String getSalt() {
// return salt;
// }
//
// public void setSalt(String salt) {
// this.salt = salt;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Transient
// @JsonIgnore
// public List<String> getRoleList() {
// // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
// return ImmutableList.copyOf(StringUtils.split(roles, ","));
// }
//
// // 设定JSON序列化时的日期格式
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
// }
// Path: src/test/java/org/springside/examples/quickstart/data/TaskData.java
import org.springside.examples.quickstart.entity.User;
import org.springside.modules.test.data.RandomData;
import org.springside.examples.quickstart.entity.Task;
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package org.springside.examples.quickstart.data;
/**
* Task相关实体测试数据生成.
*
* @author calvin
*/
public class TaskData {
public static Task randomTask() {
Task task = new Task();
task.setTitle(randomTitle());
|
User user = new User(1L);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.