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
|
---|---|---|---|---|---|---|
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/AllMapValuesTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.StringValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Timestamp;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAllMapValues;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.EnumProto3; | package com.hubspot.jackson.datatype.protobuf.proto3;
public class AllMapValuesTest {
@Test
public void itWritesAllMapValuesWhenPopulated() throws IOException {
HasAllMapValues message = hasAllMapValues(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/AllMapValuesTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.StringValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Timestamp;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAllMapValues;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.EnumProto3;
package com.hubspot.jackson.datatype.protobuf.proto3;
public class AllMapValuesTest {
@Test
public void itWritesAllMapValuesWhenPopulated() throws IOException {
HasAllMapValues message = hasAllMapValues(); | String json = camelCase(Include.NON_DEFAULT).writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/WrappedPrimitiveTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasWrappedPrimitives; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class WrappedPrimitiveTest {
private static final DoubleValue DOUBLE_WRAPPER = DoubleValue.newBuilder().setValue(1.0d).build();
private static final FloatValue FLOAT_WRAPPER = FloatValue.newBuilder().setValue(2.0f).build();
private static final Int64Value INT64_WRAPPER = Int64Value.newBuilder().setValue(3).build();
private static final UInt64Value UINT64_WRAPPER = UInt64Value.newBuilder().setValue(4).build();
private static final Int32Value INT32_WRAPPER = Int32Value.newBuilder().setValue(5).build();
private static final UInt32Value UINT32_WRAPPER = UInt32Value.newBuilder().setValue(6).build();
private static final BoolValue BOOL_WRAPPER = BoolValue.newBuilder().setValue(true).build();
private static final StringValue STRING_WRAPPER = StringValue.newBuilder().setValue("test_string").build();
private static final BytesValue BYTES_WRAPPER = BytesValue.newBuilder().setValue(ByteString.copyFromUtf8("test_bytes")).build();
@Test
public void itWritesFieldsWhenSetWithDefaultInclusion() throws IOException {
HasWrappedPrimitives message = fullyPopulatedMessage(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/WrappedPrimitiveTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasWrappedPrimitives;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class WrappedPrimitiveTest {
private static final DoubleValue DOUBLE_WRAPPER = DoubleValue.newBuilder().setValue(1.0d).build();
private static final FloatValue FLOAT_WRAPPER = FloatValue.newBuilder().setValue(2.0f).build();
private static final Int64Value INT64_WRAPPER = Int64Value.newBuilder().setValue(3).build();
private static final UInt64Value UINT64_WRAPPER = UInt64Value.newBuilder().setValue(4).build();
private static final Int32Value INT32_WRAPPER = Int32Value.newBuilder().setValue(5).build();
private static final UInt32Value UINT32_WRAPPER = UInt32Value.newBuilder().setValue(6).build();
private static final BoolValue BOOL_WRAPPER = BoolValue.newBuilder().setValue(true).build();
private static final StringValue STRING_WRAPPER = StringValue.newBuilder().setValue("test_string").build();
private static final BytesValue BYTES_WRAPPER = BytesValue.newBuilder().setValue(ByteString.copyFromUtf8("test_bytes")).build();
@Test
public void itWritesFieldsWhenSetWithDefaultInclusion() throws IOException {
HasWrappedPrimitives message = fullyPopulatedMessage(); | JsonNode json = toNode(message, camelCase()); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/util/ProtobufCreator.java | // Path: src/main/java/com/hubspot/jackson/datatype/protobuf/ExtensionRegistryWrapper.java
// public class ExtensionRegistryWrapper {
// private final Function<Descriptor, Set<ExtensionInfo>> extensionFunction;
//
// private ExtensionRegistryWrapper() {
// this.extensionFunction = new Function<Descriptor, Set<ExtensionInfo>>() {
//
// @Override
// public Set<ExtensionInfo> apply(Descriptor descriptor) {
// return Collections.emptySet();
// }
// };
// }
//
// private ExtensionRegistryWrapper(final ExtensionRegistry extensionRegistry) {
// this.extensionFunction = new Function<Descriptor, Set<ExtensionInfo>>() {
// private final Map<Descriptor, Set<ExtensionInfo>> extensionCache = new ConcurrentHashMap<>();
//
// @Override
// public Set<ExtensionInfo> apply(Descriptor descriptor) {
// Set<ExtensionInfo> cached = extensionCache.get(descriptor);
// if (cached != null) {
// return cached;
// }
//
// Set<ExtensionInfo> extensions =
// extensionRegistry.getAllImmutableExtensionsByExtendedType(descriptor.getFullName());
// extensionCache.put(descriptor, extensions);
// return extensions;
// }
// };
// }
//
// public static ExtensionRegistryWrapper wrap(ExtensionRegistry extensionRegistry) {
// return new ExtensionRegistryWrapper(extensionRegistry);
// }
//
// public static ExtensionRegistryWrapper empty() {
// return new ExtensionRegistryWrapper();
// }
//
// /**
// * @deprecated use {@link #getExtensionsByDescriptor(Descriptor)}
// */
// @Deprecated
// public List<ExtensionInfo> findExtensionsByDescriptor(Descriptor descriptor) {
// return new ArrayList<>(getExtensionsByDescriptor(descriptor));
// }
//
// public Set<ExtensionInfo> getExtensionsByDescriptor(Descriptor descriptor) {
// return extensionFunction.apply(descriptor);
// }
//
// private interface Function<T, V> {
// V apply(T t);
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.hubspot.jackson.datatype.protobuf.ExtensionRegistryWrapper; | }
@SuppressWarnings("unchecked")
public static <T extends Builder> T createBuilder(Class<T> builderType, ExtensionRegistry extensionRegistry) {
Class<? extends Message> messageType = (Class<? extends Message>) builderType.getDeclaringClass();
return (T) create(messageType, extensionRegistry).toBuilder();
}
public static <T extends Builder> List<T> createBuilder(Class<T> builderType, int count) {
return createBuilder(builderType, ExtensionRegistry.getEmptyRegistry(), count);
}
public static <T extends Builder> List<T> createBuilder(Class<T> builderType, ExtensionRegistry extensionRegistry, int count) {
List<T> builders = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
builders.add(createBuilder(builderType, extensionRegistry));
}
return builders;
}
private static class Creator {
private final Map<Class<? extends Message>, Builder> partiallyBuilt = new HashMap<>();
private <T extends Message> T create(Class<T> messageType) {
return create(messageType, ExtensionRegistry.getEmptyRegistry());
}
private <T extends Message> T create(Class<T> messageType, ExtensionRegistry extensionRegistry) { | // Path: src/main/java/com/hubspot/jackson/datatype/protobuf/ExtensionRegistryWrapper.java
// public class ExtensionRegistryWrapper {
// private final Function<Descriptor, Set<ExtensionInfo>> extensionFunction;
//
// private ExtensionRegistryWrapper() {
// this.extensionFunction = new Function<Descriptor, Set<ExtensionInfo>>() {
//
// @Override
// public Set<ExtensionInfo> apply(Descriptor descriptor) {
// return Collections.emptySet();
// }
// };
// }
//
// private ExtensionRegistryWrapper(final ExtensionRegistry extensionRegistry) {
// this.extensionFunction = new Function<Descriptor, Set<ExtensionInfo>>() {
// private final Map<Descriptor, Set<ExtensionInfo>> extensionCache = new ConcurrentHashMap<>();
//
// @Override
// public Set<ExtensionInfo> apply(Descriptor descriptor) {
// Set<ExtensionInfo> cached = extensionCache.get(descriptor);
// if (cached != null) {
// return cached;
// }
//
// Set<ExtensionInfo> extensions =
// extensionRegistry.getAllImmutableExtensionsByExtendedType(descriptor.getFullName());
// extensionCache.put(descriptor, extensions);
// return extensions;
// }
// };
// }
//
// public static ExtensionRegistryWrapper wrap(ExtensionRegistry extensionRegistry) {
// return new ExtensionRegistryWrapper(extensionRegistry);
// }
//
// public static ExtensionRegistryWrapper empty() {
// return new ExtensionRegistryWrapper();
// }
//
// /**
// * @deprecated use {@link #getExtensionsByDescriptor(Descriptor)}
// */
// @Deprecated
// public List<ExtensionInfo> findExtensionsByDescriptor(Descriptor descriptor) {
// return new ArrayList<>(getExtensionsByDescriptor(descriptor));
// }
//
// public Set<ExtensionInfo> getExtensionsByDescriptor(Descriptor descriptor) {
// return extensionFunction.apply(descriptor);
// }
//
// private interface Function<T, V> {
// V apply(T t);
// }
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ProtobufCreator.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.hubspot.jackson.datatype.protobuf.ExtensionRegistryWrapper;
}
@SuppressWarnings("unchecked")
public static <T extends Builder> T createBuilder(Class<T> builderType, ExtensionRegistry extensionRegistry) {
Class<? extends Message> messageType = (Class<? extends Message>) builderType.getDeclaringClass();
return (T) create(messageType, extensionRegistry).toBuilder();
}
public static <T extends Builder> List<T> createBuilder(Class<T> builderType, int count) {
return createBuilder(builderType, ExtensionRegistry.getEmptyRegistry(), count);
}
public static <T extends Builder> List<T> createBuilder(Class<T> builderType, ExtensionRegistry extensionRegistry, int count) {
List<T> builders = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
builders.add(createBuilder(builderType, extensionRegistry));
}
return builders;
}
private static class Creator {
private final Map<Class<? extends Message>, Builder> partiallyBuilt = new HashMap<>();
private <T extends Message> T create(Class<T> messageType) {
return create(messageType, ExtensionRegistry.getEmptyRegistry());
}
private <T extends Message> T create(Class<T> messageType, ExtensionRegistry extensionRegistry) { | return create(messageType, ExtensionRegistryWrapper.wrap(extensionRegistry)); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/OneofTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.Duration;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasOneof;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.EnumProto3; | private static final HasOneof STRING = HasOneof.newBuilder().setString("test").build();
private static final HasOneof DEFAULT_DURATION = HasOneof
.newBuilder()
.setDuration(Duration.getDefaultInstance())
.build();
private static final HasOneof DURATION = HasOneof
.newBuilder()
.setDuration(Duration.newBuilder().setSeconds(30).build())
.build();
private static final HasOneof DEFAULT_ENUM = HasOneof.newBuilder().setEnum(EnumProto3.DEFAULT).build();
private static final HasOneof ENUM = HasOneof.newBuilder().setEnum(EnumProto3.FIRST).build();
private static final HasOneof DEFAULT_PROTO2_MESSAGE = HasOneof
.newBuilder()
.setProto2Message(AllFields.getDefaultInstance())
.build();
private static final HasOneof PROTO2_MESSAGE = HasOneof
.newBuilder()
.setProto2Message(AllFields.newBuilder().setString("proto2").build())
.build();
private static final HasOneof DEFAULT_PROTO3_MESSAGE = HasOneof
.newBuilder()
.setProto3Message(AllFieldsProto3.getDefaultInstance())
.build();
private static final HasOneof PROTO3_MESSAGE = HasOneof
.newBuilder()
.setProto3Message(AllFieldsProto3.newBuilder().setString("proto3").build())
.build();
@Test
public void itOmitsOneofWhenNotSetWithDefaultInclusion() throws IOException { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/OneofTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.protobuf.Duration;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasOneof;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.EnumProto3;
private static final HasOneof STRING = HasOneof.newBuilder().setString("test").build();
private static final HasOneof DEFAULT_DURATION = HasOneof
.newBuilder()
.setDuration(Duration.getDefaultInstance())
.build();
private static final HasOneof DURATION = HasOneof
.newBuilder()
.setDuration(Duration.newBuilder().setSeconds(30).build())
.build();
private static final HasOneof DEFAULT_ENUM = HasOneof.newBuilder().setEnum(EnumProto3.DEFAULT).build();
private static final HasOneof ENUM = HasOneof.newBuilder().setEnum(EnumProto3.FIRST).build();
private static final HasOneof DEFAULT_PROTO2_MESSAGE = HasOneof
.newBuilder()
.setProto2Message(AllFields.getDefaultInstance())
.build();
private static final HasOneof PROTO2_MESSAGE = HasOneof
.newBuilder()
.setProto2Message(AllFields.newBuilder().setString("proto2").build())
.build();
private static final HasOneof DEFAULT_PROTO3_MESSAGE = HasOneof
.newBuilder()
.setProto3Message(AllFieldsProto3.getDefaultInstance())
.build();
private static final HasOneof PROTO3_MESSAGE = HasOneof
.newBuilder()
.setProto3Message(AllFieldsProto3.newBuilder().setString("proto3").build())
.build();
@Test
public void itOmitsOneofWhenNotSetWithDefaultInclusion() throws IOException { | String json = camelCase().writeValueAsString(EMPTY); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/AllMapKeysTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAllMapKeys; | package com.hubspot.jackson.datatype.protobuf.proto3;
public class AllMapKeysTest {
@Test
public void itWritesAllMapKeysWhenPopulated() throws IOException {
HasAllMapKeys message = hasAllMapKeys(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/proto3/AllMapKeysTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAllMapKeys;
package com.hubspot.jackson.datatype.protobuf.proto3;
public class AllMapKeysTest {
@Test
public void itWritesAllMapKeysWhenPopulated() throws IOException {
HasAllMapKeys message = hasAllMapKeys(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/ValueTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasValue; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class ValueTest {
@Test
public void itWritesNullValue() throws IOException {
HasValue message = HasValue
.newBuilder()
.setValue(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/ValueTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasValue;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class ValueTest {
@Test
public void itWritesNullValue() throws IOException {
HasValue message = HasValue
.newBuilder()
.setValue(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/DurationTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.Duration;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasDuration; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class DurationTest {
private static final Duration DURATION = Duration.newBuilder().setSeconds(30).build();
@Test
public void itWritesDurationWhenSetWithDefaultInclusion() throws IOException {
HasDuration message = HasDuration.newBuilder().setDuration(DURATION).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/DurationTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.Duration;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasDuration;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class DurationTest {
private static final Duration DURATION = Duration.newBuilder().setSeconds(30).build();
@Test
public void itWritesDurationWhenSetWithDefaultInclusion() throws IOException {
HasDuration message = HasDuration.newBuilder().setDuration(DURATION).build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/NullValueTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.NullValue;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasNullValue; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class NullValueTest {
@Test
public void itWritesNullValueWhenSetWithDefaultInclusion() throws IOException {
HasNullValue message = HasNullValue.newBuilder().setNullValue(NullValue.NULL_VALUE).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/NullValueTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.NullValue;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasNullValue;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class NullValueTest {
@Test
public void itWritesNullValueWhenSetWithDefaultInclusion() throws IOException {
HasNullValue message = HasNullValue.newBuilder().setNullValue(NullValue.NULL_VALUE).build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/ListValueTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasListValue; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class ListValueTest {
private static final Value VALUE = Value.newBuilder().setStringValue("test").build();
private static final ListValue LIST_VALUE = ListValue.newBuilder().addValues(VALUE).build();
@Test
public void itWritesListValueWhenSetWithDefaultInclusion() throws IOException {
HasListValue message = HasListValue.newBuilder().setListValue(LIST_VALUE).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/ListValueTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasListValue;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class ListValueTest {
private static final Value VALUE = Value.newBuilder().setStringValue("test").build();
private static final ListValue LIST_VALUE = ListValue.newBuilder().addValues(VALUE).build();
@Test
public void itWritesListValueWhenSetWithDefaultInclusion() throws IOException {
HasListValue message = HasListValue.newBuilder().setListValue(LIST_VALUE).build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/main/java/com/hubspot/jackson/datatype/protobuf/internal/PropertyNamingCache.java | // Path: src/main/java/com/hubspot/jackson/datatype/protobuf/PropertyNamingStrategyWrapper.java
// @SuppressWarnings("serial")
// public class PropertyNamingStrategyWrapper extends PropertyNamingStrategyBase {
// private static final PropertyNamingStrategyBase SNAKE_TO_CAMEL = new SnakeToCamelNamingStrategy();
// private static final PropertyNamingStrategyBase NO_OP = new NoOpNamingStrategy();
//
// private final PropertyNamingStrategyBase delegate;
//
// public PropertyNamingStrategyWrapper(PropertyNamingStrategy delegate) {
// if (delegate instanceof PropertyNamingStrategyBase) {
// this.delegate = (PropertyNamingStrategyBase) delegate;
// } else if (NamingBaseAdapter.extendsNamingBase(delegate)) {
// this.delegate = new NamingBaseAdapter(delegate);
// } else if (delegate == PropertyNamingStrategy.LOWER_CAMEL_CASE) {
// this.delegate = NO_OP;
// } else {
// this.delegate = SNAKE_TO_CAMEL;
// }
// }
//
// @Override
// public String translate(String fieldName) {
// return delegate.translate(fieldName);
// }
//
// private static class SnakeToCamelNamingStrategy extends PropertyNamingStrategyBase {
//
// @Override
// public String translate(String fieldName) {
// return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldName);
// }
//
// }
//
// private static class NoOpNamingStrategy extends PropertyNamingStrategyBase {
//
// @Override
// public String translate(String fieldName) {
// return fieldName;
// }
// }
//
// private static class NamingBaseAdapter extends PropertyNamingStrategyBase {
// private static final Class<?> NAMING_BASE = tryToLoadNamingBase();
// private static final Method TRANSLATE_METHOD = tryToLoadTranslateMethod(NAMING_BASE);
//
// private final PropertyNamingStrategy delegate;
//
// private NamingBaseAdapter(PropertyNamingStrategy delegate) {
// this.delegate = delegate;
// }
//
// public static boolean extendsNamingBase(PropertyNamingStrategy namingStrategy) {
// return NAMING_BASE != null && NAMING_BASE.isInstance(namingStrategy);
// }
//
// @Override
// public String translate(String fieldName) {
// try {
// return (String) TRANSLATE_METHOD.invoke(delegate, fieldName);
// } catch (ReflectiveOperationException e) {
// throw new RuntimeException("Unable to invoke translate method", e);
// }
// }
//
// private static Class<?> tryToLoadNamingBase() {
// try {
// return Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategies$NamingBase");
// } catch (ClassNotFoundException e) {
// return null;
// }
// }
//
// private static Method tryToLoadTranslateMethod(Class<?> namingBase) {
// if (namingBase == null) {
// return null;
// } else {
// try {
// return namingBase.getMethod("translate", String.class);
// } catch (NoSuchMethodException e) {
// throw new RuntimeException("Unable to find translate method on class: " + namingBase);
// }
// }
// }
// }
// }
//
// Path: src/main/java/com/hubspot/jackson/datatype/protobuf/ProtobufJacksonConfig.java
// public class ProtobufJacksonConfig {
// private final ExtensionRegistryWrapper extensionRegistry;
// private final boolean acceptLiteralFieldnames;
//
// private ProtobufJacksonConfig(ExtensionRegistryWrapper extensionRegistry, boolean acceptLiteralFieldnames) {
// this.extensionRegistry = extensionRegistry;
// this.acceptLiteralFieldnames = acceptLiteralFieldnames;
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public ExtensionRegistryWrapper extensionRegistry() {
// return extensionRegistry;
// }
//
// public boolean acceptLiteralFieldnames() {
// return acceptLiteralFieldnames;
// }
//
// public static class Builder {
// private ExtensionRegistryWrapper extensionRegistry = ExtensionRegistryWrapper.empty();
// private boolean acceptLiteralFieldnames = false;
//
// private Builder() {}
//
// public Builder extensionRegistry(ExtensionRegistry extensionRegistry) {
// return extensionRegistry(ExtensionRegistryWrapper.wrap(extensionRegistry));
// }
//
// public Builder extensionRegistry(ExtensionRegistryWrapper extensionRegistry) {
// this.extensionRegistry = extensionRegistry;
// return this;
// }
//
// public Builder acceptLiteralFieldnames(boolean acceptLiteralFieldnames) {
// this.acceptLiteralFieldnames = acceptLiteralFieldnames;
// return this;
// }
//
// public ProtobufJacksonConfig build() {
// return new ProtobufJacksonConfig(extensionRegistry, acceptLiteralFieldnames);
// }
// }
// }
| import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.PropertyNamingStrategyBase;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.hubspot.jackson.datatype.protobuf.PropertyNamingStrategyWrapper;
import com.hubspot.jackson.datatype.protobuf.ProtobufJacksonConfig; | package com.hubspot.jackson.datatype.protobuf.internal;
public class PropertyNamingCache {
private final Descriptor descriptor; | // Path: src/main/java/com/hubspot/jackson/datatype/protobuf/PropertyNamingStrategyWrapper.java
// @SuppressWarnings("serial")
// public class PropertyNamingStrategyWrapper extends PropertyNamingStrategyBase {
// private static final PropertyNamingStrategyBase SNAKE_TO_CAMEL = new SnakeToCamelNamingStrategy();
// private static final PropertyNamingStrategyBase NO_OP = new NoOpNamingStrategy();
//
// private final PropertyNamingStrategyBase delegate;
//
// public PropertyNamingStrategyWrapper(PropertyNamingStrategy delegate) {
// if (delegate instanceof PropertyNamingStrategyBase) {
// this.delegate = (PropertyNamingStrategyBase) delegate;
// } else if (NamingBaseAdapter.extendsNamingBase(delegate)) {
// this.delegate = new NamingBaseAdapter(delegate);
// } else if (delegate == PropertyNamingStrategy.LOWER_CAMEL_CASE) {
// this.delegate = NO_OP;
// } else {
// this.delegate = SNAKE_TO_CAMEL;
// }
// }
//
// @Override
// public String translate(String fieldName) {
// return delegate.translate(fieldName);
// }
//
// private static class SnakeToCamelNamingStrategy extends PropertyNamingStrategyBase {
//
// @Override
// public String translate(String fieldName) {
// return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldName);
// }
//
// }
//
// private static class NoOpNamingStrategy extends PropertyNamingStrategyBase {
//
// @Override
// public String translate(String fieldName) {
// return fieldName;
// }
// }
//
// private static class NamingBaseAdapter extends PropertyNamingStrategyBase {
// private static final Class<?> NAMING_BASE = tryToLoadNamingBase();
// private static final Method TRANSLATE_METHOD = tryToLoadTranslateMethod(NAMING_BASE);
//
// private final PropertyNamingStrategy delegate;
//
// private NamingBaseAdapter(PropertyNamingStrategy delegate) {
// this.delegate = delegate;
// }
//
// public static boolean extendsNamingBase(PropertyNamingStrategy namingStrategy) {
// return NAMING_BASE != null && NAMING_BASE.isInstance(namingStrategy);
// }
//
// @Override
// public String translate(String fieldName) {
// try {
// return (String) TRANSLATE_METHOD.invoke(delegate, fieldName);
// } catch (ReflectiveOperationException e) {
// throw new RuntimeException("Unable to invoke translate method", e);
// }
// }
//
// private static Class<?> tryToLoadNamingBase() {
// try {
// return Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategies$NamingBase");
// } catch (ClassNotFoundException e) {
// return null;
// }
// }
//
// private static Method tryToLoadTranslateMethod(Class<?> namingBase) {
// if (namingBase == null) {
// return null;
// } else {
// try {
// return namingBase.getMethod("translate", String.class);
// } catch (NoSuchMethodException e) {
// throw new RuntimeException("Unable to find translate method on class: " + namingBase);
// }
// }
// }
// }
// }
//
// Path: src/main/java/com/hubspot/jackson/datatype/protobuf/ProtobufJacksonConfig.java
// public class ProtobufJacksonConfig {
// private final ExtensionRegistryWrapper extensionRegistry;
// private final boolean acceptLiteralFieldnames;
//
// private ProtobufJacksonConfig(ExtensionRegistryWrapper extensionRegistry, boolean acceptLiteralFieldnames) {
// this.extensionRegistry = extensionRegistry;
// this.acceptLiteralFieldnames = acceptLiteralFieldnames;
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// public ExtensionRegistryWrapper extensionRegistry() {
// return extensionRegistry;
// }
//
// public boolean acceptLiteralFieldnames() {
// return acceptLiteralFieldnames;
// }
//
// public static class Builder {
// private ExtensionRegistryWrapper extensionRegistry = ExtensionRegistryWrapper.empty();
// private boolean acceptLiteralFieldnames = false;
//
// private Builder() {}
//
// public Builder extensionRegistry(ExtensionRegistry extensionRegistry) {
// return extensionRegistry(ExtensionRegistryWrapper.wrap(extensionRegistry));
// }
//
// public Builder extensionRegistry(ExtensionRegistryWrapper extensionRegistry) {
// this.extensionRegistry = extensionRegistry;
// return this;
// }
//
// public Builder acceptLiteralFieldnames(boolean acceptLiteralFieldnames) {
// this.acceptLiteralFieldnames = acceptLiteralFieldnames;
// return this;
// }
//
// public ProtobufJacksonConfig build() {
// return new ProtobufJacksonConfig(extensionRegistry, acceptLiteralFieldnames);
// }
// }
// }
// Path: src/main/java/com/hubspot/jackson/datatype/protobuf/internal/PropertyNamingCache.java
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.PropertyNamingStrategyBase;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.hubspot.jackson.datatype.protobuf.PropertyNamingStrategyWrapper;
import com.hubspot.jackson.datatype.protobuf.ProtobufJacksonConfig;
package com.hubspot.jackson.datatype.protobuf.internal;
public class PropertyNamingCache {
private final Descriptor descriptor; | private final ProtobufJacksonConfig config; |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnNumbersForEnumsTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat; | package com.hubspot.jackson.datatype.protobuf;
public class FailOnNumbersForEnumsTest {
@Test(expected = JsonMappingException.class)
public void testEnabled() throws JsonProcessingException {
ObjectMapper mapper = objectMapper(true);
mapper.treeToValue(buildNode(), AllFields.class);
}
@Test
public void testDisabled() throws JsonProcessingException {
ObjectMapper mapper = objectMapper(false);
AllFields parsed = mapper.treeToValue(buildNode(), AllFields.class);
assertThat(parsed.hasEnum()).isTrue();
assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
}
private static JsonNode buildNode() { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnNumbersForEnumsTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.jackson.datatype.protobuf;
public class FailOnNumbersForEnumsTest {
@Test(expected = JsonMappingException.class)
public void testEnabled() throws JsonProcessingException {
ObjectMapper mapper = objectMapper(true);
mapper.treeToValue(buildNode(), AllFields.class);
}
@Test
public void testDisabled() throws JsonProcessingException {
ObjectMapper mapper = objectMapper(false);
AllFields parsed = mapper.treeToValue(buildNode(), AllFields.class);
assertThat(parsed.hasEnum()).isTrue();
assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
}
private static JsonNode buildNode() { | return camelCase().createObjectNode().put("enum", 2); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnNullPrimitivesTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat; | assertThat(parsed.hasDouble()).isFalse();
}
@Test(expected = JsonMappingException.class)
public void testBooleanEnabled() throws JsonProcessingException {
ObjectNode node = buildNode("bool");
objectMapper(true).treeToValue(node, AllFields.class);
}
@Test
public void testBooleanDisabled() throws JsonProcessingException {
ObjectNode node = buildNode("bool");
AllFields parsed = objectMapper(false).treeToValue(node, AllFields.class);
assertThat(parsed.hasBool()).isFalse();
}
@Test
public void testOnlyAffectsPrimitives() throws JsonProcessingException {
ObjectNode node = buildNode("string", "bytes", "enum", "nested");
AllFields parsed = objectMapper(true).treeToValue(node, AllFields.class);
assertThat(parsed.hasString()).isFalse();
assertThat(parsed.hasBytes()).isFalse();
assertThat(parsed.hasEnum()).isFalse();
assertThat(parsed.hasNested()).isFalse();
}
private ObjectNode buildNode(String... fieldNames) { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnNullPrimitivesTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
assertThat(parsed.hasDouble()).isFalse();
}
@Test(expected = JsonMappingException.class)
public void testBooleanEnabled() throws JsonProcessingException {
ObjectNode node = buildNode("bool");
objectMapper(true).treeToValue(node, AllFields.class);
}
@Test
public void testBooleanDisabled() throws JsonProcessingException {
ObjectNode node = buildNode("bool");
AllFields parsed = objectMapper(false).treeToValue(node, AllFields.class);
assertThat(parsed.hasBool()).isFalse();
}
@Test
public void testOnlyAffectsPrimitives() throws JsonProcessingException {
ObjectNode node = buildNode("string", "bytes", "enum", "nested");
AllFields parsed = objectMapper(true).treeToValue(node, AllFields.class);
assertThat(parsed.hasString()).isFalse();
assertThat(parsed.hasBytes()).isFalse();
assertThat(parsed.hasEnum()).isFalse();
assertThat(parsed.hasNested()).isFalse();
}
private ObjectNode buildNode(String... fieldNames) { | ObjectNode node = camelCase().createObjectNode(); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/WriteSingleElementArraysUnwrappedTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.RepeatedFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat; | package com.hubspot.jackson.datatype.protobuf;
public class WriteSingleElementArraysUnwrappedTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("bool")).isTrue();
assertThat(node.get("bool").isBoolean()).isTrue();
assertThat(node.get("bool").booleanValue()).isFalse();
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("bool")).isTrue();
assertThat(node.get("bool").isArray()).isTrue();
assertThat(node.get("bool").size()).isEqualTo(1);
assertThat(node.get("bool").get(0).isBoolean()).isTrue();
assertThat(node.get("bool").get(0).booleanValue()).isFalse();
}
private static RepeatedFields getObject() {
return RepeatedFields.newBuilder().addBool(false).build();
}
private static ObjectMapper objectMapper(boolean enabled) {
if (enabled) { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/WriteSingleElementArraysUnwrappedTest.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.RepeatedFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.jackson.datatype.protobuf;
public class WriteSingleElementArraysUnwrappedTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("bool")).isTrue();
assertThat(node.get("bool").isBoolean()).isTrue();
assertThat(node.get("bool").booleanValue()).isFalse();
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("bool")).isTrue();
assertThat(node.get("bool").isArray()).isTrue();
assertThat(node.get("bool").size()).isEqualTo(1);
assertThat(node.get("bool").get(0).isBoolean()).isTrue();
assertThat(node.get("bool").get(0).booleanValue()).isFalse();
}
private static RepeatedFields getObject() {
return RepeatedFields.newBuilder().addBool(false).build();
}
private static ObjectMapper objectMapper(boolean enabled) {
if (enabled) { | return camelCase().enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/StructTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Map;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasStruct; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class StructTest {
@Test
public void itWritesAllStructValueTypes() throws IOException {
Value nestedValue = Value.newBuilder().setStringValue("nested").build();
Struct nestedStruct = Struct.newBuilder().putFields("key", nestedValue).build();
ListValue list = ListValue.newBuilder().addValues(nestedValue).build();
Struct struct = Struct
.newBuilder()
.putFields("null", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.putFields("number", Value.newBuilder().setNumberValue(1.5d).build())
.putFields("string", Value.newBuilder().setStringValue("test").build())
.putFields("boolean", Value.newBuilder().setBoolValue(true).build())
.putFields("struct", Value.newBuilder().setStructValue(nestedStruct).build())
.putFields("list", Value.newBuilder().setListValue(list).build())
.build();
HasStruct message = HasStruct
.newBuilder()
.setStruct(struct)
.build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/StructTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Map;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasStruct;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class StructTest {
@Test
public void itWritesAllStructValueTypes() throws IOException {
Value nestedValue = Value.newBuilder().setStringValue("nested").build();
Struct nestedStruct = Struct.newBuilder().putFields("key", nestedValue).build();
ListValue list = ListValue.newBuilder().addValues(nestedValue).build();
Struct struct = Struct
.newBuilder()
.putFields("null", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.putFields("number", Value.newBuilder().setNumberValue(1.5d).build())
.putFields("string", Value.newBuilder().setStringValue("test").build())
.putFields("boolean", Value.newBuilder().setBoolValue(true).build())
.putFields("struct", Value.newBuilder().setStructValue(nestedStruct).build())
.putFields("list", Value.newBuilder().setListValue(list).build())
.build();
HasStruct message = HasStruct
.newBuilder()
.setStruct(struct)
.build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/WriteEnumsUsingIndexTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// @SuppressWarnings("unchecked")
// public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
// TreeNode tree = toTree(mapper, value);
//
// try {
// return (T) mapper.treeToValue(tree, value.getClass());
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e);
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.writeAndReadBack;
import static org.assertj.core.api.Assertions.assertThat; | package com.hubspot.jackson.datatype.protobuf;
public class WriteEnumsUsingIndexTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isInt()).isTrue();
assertThat(node.get("enum").intValue()).isEqualTo(2);
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isTextual()).isTrue();
assertThat(node.get("enum").textValue()).isEqualTo("TWO");
}
@Test
public void testRoundTrip() { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// @SuppressWarnings("unchecked")
// public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
// TreeNode tree = toTree(mapper, value);
//
// try {
// return (T) mapper.treeToValue(tree, value.getClass());
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e);
// }
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/WriteEnumsUsingIndexTest.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.writeAndReadBack;
import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.jackson.datatype.protobuf;
public class WriteEnumsUsingIndexTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isInt()).isTrue();
assertThat(node.get("enum").intValue()).isEqualTo(2);
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isTextual()).isTrue();
assertThat(node.get("enum").textValue()).isEqualTo("TWO");
}
@Test
public void testRoundTrip() { | AllFields parsed = writeAndReadBack(objectMapper(true), getObject()); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/WriteEnumsUsingIndexTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// @SuppressWarnings("unchecked")
// public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
// TreeNode tree = toTree(mapper, value);
//
// try {
// return (T) mapper.treeToValue(tree, value.getClass());
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e);
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.writeAndReadBack;
import static org.assertj.core.api.Assertions.assertThat; | package com.hubspot.jackson.datatype.protobuf;
public class WriteEnumsUsingIndexTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isInt()).isTrue();
assertThat(node.get("enum").intValue()).isEqualTo(2);
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isTextual()).isTrue();
assertThat(node.get("enum").textValue()).isEqualTo("TWO");
}
@Test
public void testRoundTrip() {
AllFields parsed = writeAndReadBack(objectMapper(true), getObject());
assertThat(parsed.hasEnum()).isTrue();
assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
}
private static AllFields getObject() {
return AllFields.newBuilder().setEnum(TestProtobuf.Enum.TWO).build();
}
private static ObjectMapper objectMapper(boolean enabled) {
if (enabled) { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// @SuppressWarnings("unchecked")
// public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
// TreeNode tree = toTree(mapper, value);
//
// try {
// return (T) mapper.treeToValue(tree, value.getClass());
// } catch (JsonProcessingException e) {
// throw new RuntimeException(e);
// }
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/WriteEnumsUsingIndexTest.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
import org.junit.Test;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.writeAndReadBack;
import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.jackson.datatype.protobuf;
public class WriteEnumsUsingIndexTest {
@Test
public void testEnabled() {
ObjectMapper mapper = objectMapper(true);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isInt()).isTrue();
assertThat(node.get("enum").intValue()).isEqualTo(2);
}
@Test
public void testDisabled() {
ObjectMapper mapper = objectMapper(false);
JsonNode node = mapper.valueToTree(getObject());
assertThat(node.has("enum")).isTrue();
assertThat(node.get("enum").isTextual()).isTrue();
assertThat(node.get("enum").textValue()).isEqualTo("TWO");
}
@Test
public void testRoundTrip() {
AllFields parsed = writeAndReadBack(objectMapper(true), getObject());
assertThat(parsed.hasEnum()).isTrue();
assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
}
private static AllFields getObject() {
return AllFields.newBuilder().setEnum(TestProtobuf.Enum.TWO).build();
}
private static ObjectMapper objectMapper(boolean enabled) {
if (enabled) { | return camelCase().enable(SerializationFeature.WRITE_ENUMS_USING_INDEX); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnMismatchedJsonTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasTimestamp;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3; | package com.hubspot.jackson.datatype.protobuf;
public class FailOnMismatchedJsonTest {
@Test(expected = MismatchedInputException.class)
public void itFailsOnJsonArrayForNonRepeatedPrimitive() throws IOException {
String json = "{\"double\":[1.5]}"; | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/FailOnMismatchedJsonTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasTimestamp;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf3.AllFieldsProto3;
package com.hubspot.jackson.datatype.protobuf;
public class FailOnMismatchedJsonTest {
@Test(expected = MismatchedInputException.class)
public void itFailsOnJsonArrayForNonRepeatedPrimitive() throws IOException {
String json = "{\"double\":[1.5]}"; | camelCase().readValue(json, AllFieldsProto3.class); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/FieldMaskTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.FieldMask;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasFieldMask; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class FieldMaskTest {
private static final FieldMask FIELD_MASK = FieldMask.newBuilder().addPaths("path_one").addPaths("path_two").build();
@Test
public void itWritesFieldMaskWhenSetWithDefaultInclusion() throws IOException {
HasFieldMask message = HasFieldMask.newBuilder().setFieldMask(FIELD_MASK).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/FieldMaskTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.FieldMask;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasFieldMask;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class FieldMaskTest {
private static final FieldMask FIELD_MASK = FieldMask.newBuilder().addPaths("path_one").addPaths("path_two").build();
@Test
public void itWritesFieldMaskWhenSetWithDefaultInclusion() throws IOException {
HasFieldMask message = HasFieldMask.newBuilder().setFieldMask(FIELD_MASK).build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/JsonInclusionTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/TestExtensionRegistry.java
// public class TestExtensionRegistry {
//
// public static ExtensionRegistry getInstance() {
// ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
// Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
// AllExtensions.getDescriptor().getExtensions(),
// RepeatedExtensions.getDescriptor().getExtensions()
// );
//
// for (FieldDescriptor extension : extensionDescriptors) {
// if (extension.getJavaType() == JavaType.MESSAGE) {
// extensionRegistry.add(extension, Nested.getDefaultInstance());
// } else {
// extensionRegistry.add(extension);
// }
// }
//
// return extensionRegistry;
// }
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CaseFormat;
import com.google.common.base.Enums;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.hubspot.jackson.datatype.protobuf.util.TestExtensionRegistry;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields; | package com.hubspot.jackson.datatype.protobuf;
public class JsonInclusionTest {
private static final EnumSet<Include> EXCLUDED_VALUES = presentValues("ALWAYS", "USE_DEFAULTS", "CUSTOM"); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/TestExtensionRegistry.java
// public class TestExtensionRegistry {
//
// public static ExtensionRegistry getInstance() {
// ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
// Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
// AllExtensions.getDescriptor().getExtensions(),
// RepeatedExtensions.getDescriptor().getExtensions()
// );
//
// for (FieldDescriptor extension : extensionDescriptors) {
// if (extension.getJavaType() == JavaType.MESSAGE) {
// extensionRegistry.add(extension, Nested.getDefaultInstance());
// } else {
// extensionRegistry.add(extension);
// }
// }
//
// return extensionRegistry;
// }
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/JsonInclusionTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CaseFormat;
import com.google.common.base.Enums;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.hubspot.jackson.datatype.protobuf.util.TestExtensionRegistry;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
package com.hubspot.jackson.datatype.protobuf;
public class JsonInclusionTest {
private static final EnumSet<Include> EXCLUDED_VALUES = presentValues("ALWAYS", "USE_DEFAULTS", "CUSTOM"); | private static final ExtensionRegistry EXTENSION_REGISTRY = TestExtensionRegistry.getInstance(); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/JsonInclusionTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/TestExtensionRegistry.java
// public class TestExtensionRegistry {
//
// public static ExtensionRegistry getInstance() {
// ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
// Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
// AllExtensions.getDescriptor().getExtensions(),
// RepeatedExtensions.getDescriptor().getExtensions()
// );
//
// for (FieldDescriptor extension : extensionDescriptors) {
// if (extension.getJavaType() == JavaType.MESSAGE) {
// extensionRegistry.add(extension, Nested.getDefaultInstance());
// } else {
// extensionRegistry.add(extension);
// }
// }
//
// return extensionRegistry;
// }
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CaseFormat;
import com.google.common.base.Enums;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.hubspot.jackson.datatype.protobuf.util.TestExtensionRegistry;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields; | assertThat(node.get(field).isArray());
} else {
assertThat(node.get(field).isNull());
}
}
}
@Test
public void itOnlyWritesArrayExtensionFieldsWhenSerializationIncludeIsNotAlways() {
AllFields message = AllFields.getDefaultInstance();
for (Include inclusion : EnumSet.complementOf(EXCLUDED_VALUES)) {
JsonNode node = mapper(inclusion, EXTENSION_REGISTRY).valueToTree(message);
for (String field : allExtensionFields) {
if (arrayExtensionFields.contains(field)) {
assertThat(node.has(field)).isTrue();
assertThat(node.get(field).isArray());
} else {
assertThat(node.has(field)).isFalse();
}
}
}
}
private static String translate(String fieldName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldName);
}
private static ObjectMapper mapper(Include inclusion) { | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
//
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/TestExtensionRegistry.java
// public class TestExtensionRegistry {
//
// public static ExtensionRegistry getInstance() {
// ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
// Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
// AllExtensions.getDescriptor().getExtensions(),
// RepeatedExtensions.getDescriptor().getExtensions()
// );
//
// for (FieldDescriptor extension : extensionDescriptors) {
// if (extension.getJavaType() == JavaType.MESSAGE) {
// extensionRegistry.add(extension, Nested.getDefaultInstance());
// } else {
// extensionRegistry.add(extension);
// }
// }
//
// return extensionRegistry;
// }
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/JsonInclusionTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CaseFormat;
import com.google.common.base.Enums;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.ExtensionRegistry.ExtensionInfo;
import com.hubspot.jackson.datatype.protobuf.util.TestExtensionRegistry;
import com.hubspot.jackson.datatype.protobuf.util.TestProtobuf.AllFields;
assertThat(node.get(field).isArray());
} else {
assertThat(node.get(field).isNull());
}
}
}
@Test
public void itOnlyWritesArrayExtensionFieldsWhenSerializationIncludeIsNotAlways() {
AllFields message = AllFields.getDefaultInstance();
for (Include inclusion : EnumSet.complementOf(EXCLUDED_VALUES)) {
JsonNode node = mapper(inclusion, EXTENSION_REGISTRY).valueToTree(message);
for (String field : allExtensionFields) {
if (arrayExtensionFields.contains(field)) {
assertThat(node.has(field)).isTrue();
assertThat(node.get(field).isArray());
} else {
assertThat(node.has(field)).isFalse();
}
}
}
}
private static String translate(String fieldName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldName);
}
private static ObjectMapper mapper(Include inclusion) { | return camelCase().copy().setSerializationInclusion(inclusion); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/AnyTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.Any;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAny; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class AnyTest {
private static final String TYPE_URL = "type.googleapis.com/google.protobuf.Value";
private static final Value VALUE = Value.newBuilder().setStringValue("test").build();
private static final Any ANY = Any
.newBuilder()
.setTypeUrl(TYPE_URL)
.setValue(VALUE.toByteString())
.build();
@Test
public void itWritesDurationWhenSetWithDefaultInclusion() throws IOException {
HasAny message = HasAny.newBuilder().setAny(ANY).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/AnyTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.Any;
import com.google.protobuf.Value;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasAny;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class AnyTest {
private static final String TYPE_URL = "type.googleapis.com/google.protobuf.Value";
private static final Value VALUE = Value.newBuilder().setStringValue("test").build();
private static final Any ANY = Any
.newBuilder()
.setTypeUrl(TYPE_URL)
.setValue(VALUE.toByteString())
.build();
@Test
public void itWritesDurationWhenSetWithDefaultInclusion() throws IOException {
HasAny message = HasAny.newBuilder().setAny(ANY).build(); | String json = camelCase().writeValueAsString(message); |
HubSpot/jackson-datatype-protobuf | src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/TimestampTest.java | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
| import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.Timestamp;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasTimestamp; | package com.hubspot.jackson.datatype.protobuf.builtin;
public class TimestampTest {
private static final Timestamp TIMESTAMP = Timestamp.newBuilder().setSeconds(946684800).build();
@Test
public void itWritesTimestampWhenSetWithDefaultInclusion() throws IOException {
HasTimestamp message = HasTimestamp.newBuilder().setTimestamp(TIMESTAMP).build(); | // Path: src/test/java/com/hubspot/jackson/datatype/protobuf/util/ObjectMapperHelper.java
// public static ObjectMapper camelCase() {
// return DEFAULT;
// }
// Path: src/test/java/com/hubspot/jackson/datatype/protobuf/builtin/TimestampTest.java
import static com.hubspot.jackson.datatype.protobuf.util.ObjectMapperHelper.camelCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.protobuf.Timestamp;
import com.hubspot.jackson.datatype.protobuf.util.BuiltInProtobufs.HasTimestamp;
package com.hubspot.jackson.datatype.protobuf.builtin;
public class TimestampTest {
private static final Timestamp TIMESTAMP = Timestamp.newBuilder().setSeconds(946684800).build();
@Test
public void itWritesTimestampWhenSetWithDefaultInclusion() throws IOException {
HasTimestamp message = HasTimestamp.newBuilder().setTimestamp(TIMESTAMP).build(); | String json = camelCase().writeValueAsString(message); |
lishid/OpenInv | api/src/main/java/com/lishid/openinv/util/InventoryAccess.java | // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
} catch (ClassNotFoundException ignored) {}
try {
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
| // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: api/src/main/java/com/lishid/openinv/util/InventoryAccess.java
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
} catch (ClassNotFoundException ignored) {}
try {
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
| public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) { |
lishid/OpenInv | api/src/main/java/com/lishid/openinv/util/InventoryAccess.java | // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
} catch (ClassNotFoundException ignored) {}
try {
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
| // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: api/src/main/java/com/lishid/openinv/util/InventoryAccess.java
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
} catch (ClassNotFoundException ignored) {}
try {
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
| public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) { |
lishid/OpenInv | api/src/main/java/com/lishid/openinv/util/InventoryAccess.java | // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | }
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialEnderChest.class, inventory);
}
| // Path: api/src/main/java/com/lishid/openinv/internal/IInventoryAccess.java
// @Deprecated
// public interface IInventoryAccess {
//
// /**
// * Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
// * ISpecialEnderChest.
// *
// * @param inventory the Inventory
// * @return the ISpecialEnderChest or null
// */
// @Deprecated
// @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
// * an ISpecialPlayerInventory.
// *
// * @param inventory the Inventory
// * @return the ISpecialPlayerInventory or null
// */
// @Deprecated
// @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialEnderChest implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialEnderChest
// */
// @Deprecated
// boolean isSpecialEnderChest(@NotNull Inventory inventory);
//
// /**
// * Check if an Inventory is an ISpecialPlayerInventory implementation.
// *
// * @param inventory the Inventory
// * @return true if the Inventory is backed by an ISpecialPlayerInventory
// */
// @Deprecated
// boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: api/src/main/java/com/lishid/openinv/util/InventoryAccess.java
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialEnderChest.class, inventory);
}
| private static <T extends ISpecialInventory> @Nullable T getSpecialInventory(@NotNull Class<T> expected, @NotNull Inventory inventory) { |
lishid/OpenInv | internal/v1_16_R3/src/main/java/com/lishid/openinv/internal/v1_16_R3/PlayerDataManager.java | // Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/OpenInventoryView.java
// public class OpenInventoryView extends InventoryView {
//
// private final Player player;
// private final ISpecialInventory inventory;
// private final String titleKey;
// private final String titleDefaultSuffix;
// private String title;
//
// public OpenInventoryView(Player player, ISpecialInventory inventory, String titleKey, String titleDefaultSuffix) {
// this.player = player;
// this.inventory = inventory;
// this.titleKey = titleKey;
// this.titleDefaultSuffix = titleDefaultSuffix;
// }
//
// @Override
// public @NotNull Inventory getTopInventory() {
// return inventory.getBukkitInventory();
// }
//
// @Override
// public @NotNull Inventory getBottomInventory() {
// return getPlayer().getInventory();
// }
//
// @Override
// public @NotNull HumanEntity getPlayer() {
// return player;
// }
//
// @Override
// public @NotNull InventoryType getType() {
// return inventory.getBukkitInventory().getType();
// }
//
// @Override
// public @NotNull String getTitle() {
// if (title == null) {
// HumanEntity owner = getPlayer();
//
// String localTitle = OpenInv.getPlugin(OpenInv.class)
// .getLocalizedMessage(
// owner,
// titleKey,
// "%player%",
// owner.getName());
// if (localTitle != null) {
// title = localTitle;
// } else {
// title = owner.getName() + titleDefaultSuffix;
// }
// }
//
// return title;
// }
//
// }
| import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import java.lang.reflect.Field;
import net.minecraft.server.v1_16_R3.ChatComponentText;
import net.minecraft.server.v1_16_R3.Container;
import net.minecraft.server.v1_16_R3.Containers;
import net.minecraft.server.v1_16_R3.Entity;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.MinecraftServer;
import net.minecraft.server.v1_16_R3.PacketPlayOutOpenWindow;
import net.minecraft.server.v1_16_R3.PlayerInteractManager;
import net.minecraft.server.v1_16_R3.World;
import net.minecraft.server.v1_16_R3.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.craftbukkit.v1_16_R3.CraftServer;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_16_R3.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | }
// Return the entity
return target;
}
void injectPlayer(EntityPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@NotNull
@Override
public Player inject(@NotNull Player player) {
try {
EntityPlayer nmsPlayer = getHandle(player);
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
e.printStackTrace();
return player;
}
}
@Nullable
@Override | // Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialInventory.java
// public interface ISpecialInventory {
//
// /**
// * Gets the Inventory associated with this ISpecialInventory.
// *
// * @return the Inventory
// */
// @NotNull Inventory getBukkitInventory();
//
// /**
// * Sets the Player associated with this ISpecialInventory online.
// *
// * @param player the Player coming online
// */
// void setPlayerOnline(@NotNull Player player);
//
// /**
// * Sets the Player associated with this ISpecialInventory offline.
// */
// void setPlayerOffline();
//
// /**
// * Gets whether or not this ISpecialInventory is in use.
// *
// * @return true if the ISpecialInventory is in use
// */
// boolean isInUse();
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/OpenInventoryView.java
// public class OpenInventoryView extends InventoryView {
//
// private final Player player;
// private final ISpecialInventory inventory;
// private final String titleKey;
// private final String titleDefaultSuffix;
// private String title;
//
// public OpenInventoryView(Player player, ISpecialInventory inventory, String titleKey, String titleDefaultSuffix) {
// this.player = player;
// this.inventory = inventory;
// this.titleKey = titleKey;
// this.titleDefaultSuffix = titleDefaultSuffix;
// }
//
// @Override
// public @NotNull Inventory getTopInventory() {
// return inventory.getBukkitInventory();
// }
//
// @Override
// public @NotNull Inventory getBottomInventory() {
// return getPlayer().getInventory();
// }
//
// @Override
// public @NotNull HumanEntity getPlayer() {
// return player;
// }
//
// @Override
// public @NotNull InventoryType getType() {
// return inventory.getBukkitInventory().getType();
// }
//
// @Override
// public @NotNull String getTitle() {
// if (title == null) {
// HumanEntity owner = getPlayer();
//
// String localTitle = OpenInv.getPlugin(OpenInv.class)
// .getLocalizedMessage(
// owner,
// titleKey,
// "%player%",
// owner.getName());
// if (localTitle != null) {
// title = localTitle;
// } else {
// title = owner.getName() + titleDefaultSuffix;
// }
// }
//
// return title;
// }
//
// }
// Path: internal/v1_16_R3/src/main/java/com/lishid/openinv/internal/v1_16_R3/PlayerDataManager.java
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import java.lang.reflect.Field;
import net.minecraft.server.v1_16_R3.ChatComponentText;
import net.minecraft.server.v1_16_R3.Container;
import net.minecraft.server.v1_16_R3.Containers;
import net.minecraft.server.v1_16_R3.Entity;
import net.minecraft.server.v1_16_R3.EntityPlayer;
import net.minecraft.server.v1_16_R3.MinecraftServer;
import net.minecraft.server.v1_16_R3.PacketPlayOutOpenWindow;
import net.minecraft.server.v1_16_R3.PlayerInteractManager;
import net.minecraft.server.v1_16_R3.World;
import net.minecraft.server.v1_16_R3.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.craftbukkit.v1_16_R3.CraftServer;
import org.bukkit.craftbukkit.v1_16_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_16_R3.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
}
// Return the entity
return target;
}
void injectPlayer(EntityPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@NotNull
@Override
public Player inject(@NotNull Player player) {
try {
EntityPlayer nmsPlayer = getHandle(player);
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
e.printStackTrace();
return player;
}
}
@Nullable
@Override | public InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) { |
lishid/OpenInv | plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | /*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false; | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false; | private IPlayerDataManager playerDataManager; |
lishid/OpenInv | plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | /*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false;
private IPlayerDataManager playerDataManager; | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
/*
* Copyright (C) 2011-2020 lishid. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class InternalAccessor {
private final Plugin plugin;
private final String version;
private boolean supported = false;
private IPlayerDataManager playerDataManager; | private IAnySilentContainer anySilentContainer; |
lishid/OpenInv | plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | }
/**
* Gets the server implementation version. If not initialized, returns the string "null"
* instead.
*
* @return the version, or "null"
*/
public String getVersion() {
return this.version != null ? this.version : "null";
}
/**
* Checks if the server implementation is supported.
*
* @return true if initialized for a supported server version
*/
public boolean isSupported() {
return this.supported;
}
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/ | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
}
/**
* Gets the server implementation version. If not initialized, returns the string "null"
* instead.
*
* @return the version, or "null"
*/
public String getVersion() {
return this.version != null ? this.version : "null";
}
/**
* Checks if the server implementation is supported.
*
* @return true if initialized for a supported server version
*/
public boolean isSupported() {
return this.supported;
}
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/ | public ISpecialEnderChest newSpecialEnderChest(final Player player, final boolean online) throws InstantiationException { |
lishid/OpenInv | plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
| import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | }
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/
public ISpecialEnderChest newSpecialEnderChest(final Player player, final boolean online) throws InstantiationException {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
try {
return this.createObject(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
} catch (Exception e) {
throw new InstantiationException(String.format("Unable to create a new ISpecialEnderChest: %s", e.getMessage()));
}
}
/**
* Creates an instance of the ISpecialPlayerInventory implementation for the given Player..
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialPlayerInventory created
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
*/ | // Path: api/src/main/java/com/lishid/openinv/internal/IAnySilentContainer.java
// public interface IAnySilentContainer {
//
// /**
// * Opens the container at the given coordinates for the Player. If you do not want blocked
// * containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
// * first.
// *
// * @param player the Player opening the container
// * @param silent whether the container's noise is to be silenced
// * @param block the Block
// * @return true if the container can be opened
// */
// boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
//
// /**
// * Closes the Player's currently open container silently, if necessary.
// *
// * @param player the Player closing a container
// */
// void deactivateContainer(@NotNull Player player);
//
// /**
// * Checks if the container at the given coordinates is blocked.
// *
// * @param player the Player opening the container
// * @param block the Block
// * @return true if the container is blocked
// */
// boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block);
//
// /**
// * Checks if the given block is a container which can be unblocked or silenced.
// *
// * @param block the BlockState
// * @return true if the Block is a supported container
// */
// boolean isAnySilentContainer(@NotNull Block block);
//
// }
//
// Path: plugin/src/main/java/com/lishid/openinv/internal/IPlayerDataManager.java
// public interface IPlayerDataManager {
//
// /**
// * Loads a Player for an OfflinePlayer.
// * </p>
// * This method is potentially blocking, and should not be called on the main thread.
// *
// * @param offline the OfflinePlayer
// * @return the Player loaded
// */
// @Nullable Player loadPlayer(@NotNull OfflinePlayer offline);
//
// /**
// * Creates a new Player from an existing one that will function slightly better offline.
// *
// * @return the Player
// */
// @NotNull Player inject(@NotNull Player player);
//
// /**
// * Opens an ISpecialInventory for a Player.
// *
// * @param player the Player opening the ISpecialInventory
// * @param inventory the Inventory
// *`
// * @return the InventoryView opened
// */
// @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
//
// /**
// * Convert a raw slot number into a player inventory slot number.
// *
// * <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
// * player inventory slot number.
// *
// * @param view the open inventory view
// * @param rawSlot the raw slot in the view
// * @return the converted slot number
// */
// int convertToPlayerSlot(InventoryView view, int rawSlot);
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialEnderChest.java
// public interface ISpecialEnderChest extends ISpecialInventory {
//
// }
//
// Path: api/src/main/java/com/lishid/openinv/internal/ISpecialPlayerInventory.java
// public interface ISpecialPlayerInventory extends ISpecialInventory {
//
// }
// Path: plugin/src/main/java/com/lishid/openinv/util/InternalAccessor.java
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
}
/**
* Creates an instance of the ISpecialEnderChest implementation for the given Player, or
* null if the current version is unsupported.
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialEnderChest created
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/
public ISpecialEnderChest newSpecialEnderChest(final Player player, final boolean online) throws InstantiationException {
if (!this.supported) {
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
}
try {
return this.createObject(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
} catch (Exception e) {
throw new InstantiationException(String.format("Unable to create a new ISpecialEnderChest: %s", e.getMessage()));
}
}
/**
* Creates an instance of the ISpecialPlayerInventory implementation for the given Player..
*
* @param player the Player
* @param online true if the Player is online
* @return the ISpecialPlayerInventory created
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
*/ | public ISpecialPlayerInventory newSpecialPlayerInventory(final Player player, final boolean online) throws InstantiationException { |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/tt/service/mapper/JsonMappingExceptionMapper.java | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionType.java
// public enum ExceptionType {
//
// BAD_USAGE_GENERIC(new ExceptionBean("4000", "Bad Usage")),
// BAD_USAGE_SEARCH_QUERY(new ExceptionBean("4001", "Search query is not valid")),
// BAD_USAGE_STATUS_TRANSITION(new ExceptionBean("4002", "The status transition is not allowed")),
// BAD_USAGE_MANDATORY_FIELDS(new ExceptionBean("4003", "Missing mandatory field")),
// BAD_USAGE_UNKNOWN_VALUE(new ExceptionBean("4004", "Unknown value")),
// UNKNOWN_RESOURCE(new ExceptionBean("4041", "Unknown resource"));
// private ExceptionBean info;
//
// ExceptionType(ExceptionBean info) {
// this.info = info;
// }
//
// @Override
// public String toString() {
// String out = String.format("%1$ - %2$ - %3$", this.getInfo().getCode(), this.name(), this.getInfo().getTitle());
// return out;
// }
//
// public ExceptionBean getInfo() {
// return info;
// }
// }
| import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.JsonMappingException;
import tmf.org.dsmapi.commons.exceptions.ExceptionType; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException ex) { | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionType.java
// public enum ExceptionType {
//
// BAD_USAGE_GENERIC(new ExceptionBean("4000", "Bad Usage")),
// BAD_USAGE_SEARCH_QUERY(new ExceptionBean("4001", "Search query is not valid")),
// BAD_USAGE_STATUS_TRANSITION(new ExceptionBean("4002", "The status transition is not allowed")),
// BAD_USAGE_MANDATORY_FIELDS(new ExceptionBean("4003", "Missing mandatory field")),
// BAD_USAGE_UNKNOWN_VALUE(new ExceptionBean("4004", "Unknown value")),
// UNKNOWN_RESOURCE(new ExceptionBean("4041", "Unknown resource"));
// private ExceptionBean info;
//
// ExceptionType(ExceptionBean info) {
// this.info = info;
// }
//
// @Override
// public String toString() {
// String out = String.format("%1$ - %2$ - %3$", this.getInfo().getCode(), this.name(), this.getInfo().getTitle());
// return out;
// }
//
// public ExceptionBean getInfo() {
// return info;
// }
// }
// Path: src/java/tmf/org/dsmapi/tt/service/mapper/JsonMappingExceptionMapper.java
import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.JsonMappingException;
import tmf.org.dsmapi.commons.exceptions.ExceptionType;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException ex) { | JsonFault error = new JsonFault(ExceptionType.BAD_USAGE_UNKNOWN_VALUE.getInfo(), ex.getMessage()); |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/tt/service/mapper/JsonMappingExceptionMapper.java | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionType.java
// public enum ExceptionType {
//
// BAD_USAGE_GENERIC(new ExceptionBean("4000", "Bad Usage")),
// BAD_USAGE_SEARCH_QUERY(new ExceptionBean("4001", "Search query is not valid")),
// BAD_USAGE_STATUS_TRANSITION(new ExceptionBean("4002", "The status transition is not allowed")),
// BAD_USAGE_MANDATORY_FIELDS(new ExceptionBean("4003", "Missing mandatory field")),
// BAD_USAGE_UNKNOWN_VALUE(new ExceptionBean("4004", "Unknown value")),
// UNKNOWN_RESOURCE(new ExceptionBean("4041", "Unknown resource"));
// private ExceptionBean info;
//
// ExceptionType(ExceptionBean info) {
// this.info = info;
// }
//
// @Override
// public String toString() {
// String out = String.format("%1$ - %2$ - %3$", this.getInfo().getCode(), this.name(), this.getInfo().getTitle());
// return out;
// }
//
// public ExceptionBean getInfo() {
// return info;
// }
// }
| import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.JsonMappingException;
import tmf.org.dsmapi.commons.exceptions.ExceptionType; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException ex) { | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionType.java
// public enum ExceptionType {
//
// BAD_USAGE_GENERIC(new ExceptionBean("4000", "Bad Usage")),
// BAD_USAGE_SEARCH_QUERY(new ExceptionBean("4001", "Search query is not valid")),
// BAD_USAGE_STATUS_TRANSITION(new ExceptionBean("4002", "The status transition is not allowed")),
// BAD_USAGE_MANDATORY_FIELDS(new ExceptionBean("4003", "Missing mandatory field")),
// BAD_USAGE_UNKNOWN_VALUE(new ExceptionBean("4004", "Unknown value")),
// UNKNOWN_RESOURCE(new ExceptionBean("4041", "Unknown resource"));
// private ExceptionBean info;
//
// ExceptionType(ExceptionBean info) {
// this.info = info;
// }
//
// @Override
// public String toString() {
// String out = String.format("%1$ - %2$ - %3$", this.getInfo().getCode(), this.name(), this.getInfo().getTitle());
// return out;
// }
//
// public ExceptionBean getInfo() {
// return info;
// }
// }
// Path: src/java/tmf/org/dsmapi/tt/service/mapper/JsonMappingExceptionMapper.java
import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.JsonMappingException;
import tmf.org.dsmapi.commons.exceptions.ExceptionType;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException ex) { | JsonFault error = new JsonFault(ExceptionType.BAD_USAGE_UNKNOWN_VALUE.getInfo(), ex.getMessage()); |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/tt/service/mapper/BadUsageExceptionMapper.java | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/BadUsageException.java
// public class BadUsageException extends FunctionalException {
//
// public BadUsageException(ExceptionType type) {
// super(type);
// }
//
// public BadUsageException(ExceptionType type, String message) {
// super(type, message);
// }
//
// }
| import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import tmf.org.dsmapi.commons.exceptions.BadUsageException; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class BadUsageExceptionMapper implements ExceptionMapper<BadUsageException> {
@Override
public Response toResponse(BadUsageException ex) { | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/BadUsageException.java
// public class BadUsageException extends FunctionalException {
//
// public BadUsageException(ExceptionType type) {
// super(type);
// }
//
// public BadUsageException(ExceptionType type, String message) {
// super(type, message);
// }
//
// }
// Path: src/java/tmf/org/dsmapi/tt/service/mapper/BadUsageExceptionMapper.java
import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import tmf.org.dsmapi.commons.exceptions.BadUsageException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class BadUsageExceptionMapper implements ExceptionMapper<BadUsageException> {
@Override
public Response toResponse(BadUsageException ex) { | JsonFault error = new JsonFault(ex.getType().getInfo(),ex.getMessage()); |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/hub/service/RESTEventPublisher.java | // Path: src/java/tmf/org/dsmapi/hub/Hub.java
// @Entity
// @XmlRootElement
// public class Hub implements Serializable {
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String callback;
// private String query;
//
// public String getCallback() {
// return callback;
// }
//
// public void setCallback(String callback) {
// this.callback = callback;
// }
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fields are not set
// if (!(object instanceof Hub)) {
// return false;
// }
// Hub other = (Hub) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmapi.hub.Hub[ id=" + id + " ]";
// }
// }
| import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import tmf.org.dsmapi.hub.Hub; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Stateless
public class RESTEventPublisher implements RESTEventPublisherLocal {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Override
@Asynchronous | // Path: src/java/tmf/org/dsmapi/hub/Hub.java
// @Entity
// @XmlRootElement
// public class Hub implements Serializable {
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String callback;
// private String query;
//
// public String getCallback() {
// return callback;
// }
//
// public void setCallback(String callback) {
// this.callback = callback;
// }
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fields are not set
// if (!(object instanceof Hub)) {
// return false;
// }
// Hub other = (Hub) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmapi.hub.Hub[ id=" + id + " ]";
// }
// }
// Path: src/java/tmf/org/dsmapi/hub/service/RESTEventPublisher.java
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import tmf.org.dsmapi.hub.Hub;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Stateless
public class RESTEventPublisher implements RESTEventPublisherLocal {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Override
@Asynchronous | public void publish( Hub hub, Object event) { |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/tt/service/JsonFault.java | // Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionBean.java
// public class ExceptionBean {
//
// private String code;
// private String title;
//
// public ExceptionBean(String code, String title) {
// this.code=code;
// this.title=title;
// }
//
// /**
// * @return the code
// */
// public String getCode() {
// return code;
// }
//
// /**
// * @param code the code to set
// */
// public void setCode(String code) {
// this.code = code;
// }
//
// /**
// * @return the title
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * @param title the title to set
// */
// public void setTitle(String title) {
// this.title = title;
// }
//
// }
| import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import tmf.org.dsmapi.commons.exceptions.ExceptionBean; | package tmf.org.dsmapi.tt.service;
@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class JsonFault {
| // Path: src/java/tmf/org/dsmapi/commons/exceptions/ExceptionBean.java
// public class ExceptionBean {
//
// private String code;
// private String title;
//
// public ExceptionBean(String code, String title) {
// this.code=code;
// this.title=title;
// }
//
// /**
// * @return the code
// */
// public String getCode() {
// return code;
// }
//
// /**
// * @param code the code to set
// */
// public void setCode(String code) {
// this.code = code;
// }
//
// /**
// * @return the title
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * @param title the title to set
// */
// public void setTitle(String title) {
// this.title = title;
// }
//
// }
// Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import tmf.org.dsmapi.commons.exceptions.ExceptionBean;
package tmf.org.dsmapi.tt.service;
@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class JsonFault {
| private ExceptionBean error; |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/hub/service/PublisherLocal.java | // Path: src/java/tmf/org/dsmapi/tt/TroubleTicket.java
// @Entity
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class TroubleTicket implements Serializable {
//
// //Add other static strings as required....
// private static final long serialVersionUID = 1L;
// // Used for incremental update
// @Transient
// @JsonIgnore
// private Set<TroubleTicketField> fieldsIN;
// @Id
// @Column(name="TT_ID")
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String correlationId;
// private String description;
// private Severity severity;
// private String type;
// private String creationDate;
// private String targetResolutionDate;
// private Status status;
// private SubStatus subStatus;
// private String statusChangeReason;
// private String statusChangeDate;
// private String resolutionDate;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_OBJECT",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedObject> relatedObjects;
//
// @ElementCollection
// @CollectionTable(
// name = "NOTES",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<Note> notes;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_PARTY",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedParty> relatedParties;
//
// public String getCorrelationId() {
// return correlationId;
// }
//
// public void setCorrelationId(String correlationId) {
// this.correlationId = correlationId;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(Severity severity) {
// this.severity = severity;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(String creationDate) {
// this.creationDate = creationDate;
// }
//
// public String getTargetResolutionDate() {
// return targetResolutionDate;
// }
//
// public void setTargetResolutionDate(String targetResolutionDate) {
// this.targetResolutionDate = targetResolutionDate;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public SubStatus getSubStatus() {
// return subStatus;
// }
//
// public void setSubStatus(SubStatus subStatus) {
// this.subStatus = subStatus;
// }
//
// public String getStatusChangeReason() {
// return statusChangeReason;
// }
//
// public void setStatusChangeReason(String statusChangeReason) {
// this.statusChangeReason = statusChangeReason;
// }
//
// public String getStatusChangeDate() {
// return statusChangeDate;
// }
//
// public void setStatusChangeDate(String statusChangeDate) {
// this.statusChangeDate = statusChangeDate;
// }
//
// public String getResolutionDate() {
// return resolutionDate;
// }
//
// public void setResolutionDate(String resolutionDate) {
// this.resolutionDate = resolutionDate;
// }
//
// public List<RelatedObject> getRelatedObjects() {
// if (relatedObjects.isEmpty()) return null;
// else return relatedObjects;
// }
//
// public void setRelatedObjects(List<RelatedObject> relatedObjects) {
// this.relatedObjects = relatedObjects;
// }
//
// public List<Note> getNotes() {
// if (notes.isEmpty()) return null;
// else return notes;
// }
//
// public void setNotes(List<Note> notes) {
// this.notes = notes;
// }
//
// public List<RelatedParty> getRelatedParties() {
// if (relatedParties.isEmpty()) return null;
// else return relatedParties;
// }
//
// public void setRelatedParties(List<RelatedParty> relatedParties) {
// this.relatedParties = relatedParties;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// //this must be reimplemented
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fieldsIN are not set
// if (!(object instanceof TroubleTicket)) {
// return false;
// }
// TroubleTicket other = (TroubleTicket) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmtt.TroubleTicket[ id=" + id + " ]";
// }
//
// /**
// * @return the fieldsIN
// */
// public Set<TroubleTicketField> getFieldsIN() {
// return fieldsIN;
// }
//
// /**
// * @param fieldsIN the fieldsIN to set
// */
// public void setFieldsIN(Set<TroubleTicketField> fields) {
// this.fieldsIN = fields;
// }
// }
| import javax.ejb.Local;
import tmf.org.dsmapi.tt.TroubleTicket; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Local
public interface PublisherLocal {
void publish(Object event);
| // Path: src/java/tmf/org/dsmapi/tt/TroubleTicket.java
// @Entity
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class TroubleTicket implements Serializable {
//
// //Add other static strings as required....
// private static final long serialVersionUID = 1L;
// // Used for incremental update
// @Transient
// @JsonIgnore
// private Set<TroubleTicketField> fieldsIN;
// @Id
// @Column(name="TT_ID")
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String correlationId;
// private String description;
// private Severity severity;
// private String type;
// private String creationDate;
// private String targetResolutionDate;
// private Status status;
// private SubStatus subStatus;
// private String statusChangeReason;
// private String statusChangeDate;
// private String resolutionDate;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_OBJECT",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedObject> relatedObjects;
//
// @ElementCollection
// @CollectionTable(
// name = "NOTES",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<Note> notes;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_PARTY",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedParty> relatedParties;
//
// public String getCorrelationId() {
// return correlationId;
// }
//
// public void setCorrelationId(String correlationId) {
// this.correlationId = correlationId;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(Severity severity) {
// this.severity = severity;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(String creationDate) {
// this.creationDate = creationDate;
// }
//
// public String getTargetResolutionDate() {
// return targetResolutionDate;
// }
//
// public void setTargetResolutionDate(String targetResolutionDate) {
// this.targetResolutionDate = targetResolutionDate;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public SubStatus getSubStatus() {
// return subStatus;
// }
//
// public void setSubStatus(SubStatus subStatus) {
// this.subStatus = subStatus;
// }
//
// public String getStatusChangeReason() {
// return statusChangeReason;
// }
//
// public void setStatusChangeReason(String statusChangeReason) {
// this.statusChangeReason = statusChangeReason;
// }
//
// public String getStatusChangeDate() {
// return statusChangeDate;
// }
//
// public void setStatusChangeDate(String statusChangeDate) {
// this.statusChangeDate = statusChangeDate;
// }
//
// public String getResolutionDate() {
// return resolutionDate;
// }
//
// public void setResolutionDate(String resolutionDate) {
// this.resolutionDate = resolutionDate;
// }
//
// public List<RelatedObject> getRelatedObjects() {
// if (relatedObjects.isEmpty()) return null;
// else return relatedObjects;
// }
//
// public void setRelatedObjects(List<RelatedObject> relatedObjects) {
// this.relatedObjects = relatedObjects;
// }
//
// public List<Note> getNotes() {
// if (notes.isEmpty()) return null;
// else return notes;
// }
//
// public void setNotes(List<Note> notes) {
// this.notes = notes;
// }
//
// public List<RelatedParty> getRelatedParties() {
// if (relatedParties.isEmpty()) return null;
// else return relatedParties;
// }
//
// public void setRelatedParties(List<RelatedParty> relatedParties) {
// this.relatedParties = relatedParties;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// //this must be reimplemented
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fieldsIN are not set
// if (!(object instanceof TroubleTicket)) {
// return false;
// }
// TroubleTicket other = (TroubleTicket) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmtt.TroubleTicket[ id=" + id + " ]";
// }
//
// /**
// * @return the fieldsIN
// */
// public Set<TroubleTicketField> getFieldsIN() {
// return fieldsIN;
// }
//
// /**
// * @param fieldsIN the fieldsIN to set
// */
// public void setFieldsIN(Set<TroubleTicketField> fields) {
// this.fieldsIN = fields;
// }
// }
// Path: src/java/tmf/org/dsmapi/hub/service/PublisherLocal.java
import javax.ejb.Local;
import tmf.org.dsmapi.tt.TroubleTicket;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Local
public interface PublisherLocal {
void publish(Object event);
| public void publishTicketCreateNotification(TroubleTicket tt); |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/hub/HubEvent.java | // Path: src/java/tmf/org/dsmapi/tt/TroubleTicket.java
// @Entity
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class TroubleTicket implements Serializable {
//
// //Add other static strings as required....
// private static final long serialVersionUID = 1L;
// // Used for incremental update
// @Transient
// @JsonIgnore
// private Set<TroubleTicketField> fieldsIN;
// @Id
// @Column(name="TT_ID")
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String correlationId;
// private String description;
// private Severity severity;
// private String type;
// private String creationDate;
// private String targetResolutionDate;
// private Status status;
// private SubStatus subStatus;
// private String statusChangeReason;
// private String statusChangeDate;
// private String resolutionDate;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_OBJECT",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedObject> relatedObjects;
//
// @ElementCollection
// @CollectionTable(
// name = "NOTES",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<Note> notes;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_PARTY",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedParty> relatedParties;
//
// public String getCorrelationId() {
// return correlationId;
// }
//
// public void setCorrelationId(String correlationId) {
// this.correlationId = correlationId;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(Severity severity) {
// this.severity = severity;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(String creationDate) {
// this.creationDate = creationDate;
// }
//
// public String getTargetResolutionDate() {
// return targetResolutionDate;
// }
//
// public void setTargetResolutionDate(String targetResolutionDate) {
// this.targetResolutionDate = targetResolutionDate;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public SubStatus getSubStatus() {
// return subStatus;
// }
//
// public void setSubStatus(SubStatus subStatus) {
// this.subStatus = subStatus;
// }
//
// public String getStatusChangeReason() {
// return statusChangeReason;
// }
//
// public void setStatusChangeReason(String statusChangeReason) {
// this.statusChangeReason = statusChangeReason;
// }
//
// public String getStatusChangeDate() {
// return statusChangeDate;
// }
//
// public void setStatusChangeDate(String statusChangeDate) {
// this.statusChangeDate = statusChangeDate;
// }
//
// public String getResolutionDate() {
// return resolutionDate;
// }
//
// public void setResolutionDate(String resolutionDate) {
// this.resolutionDate = resolutionDate;
// }
//
// public List<RelatedObject> getRelatedObjects() {
// if (relatedObjects.isEmpty()) return null;
// else return relatedObjects;
// }
//
// public void setRelatedObjects(List<RelatedObject> relatedObjects) {
// this.relatedObjects = relatedObjects;
// }
//
// public List<Note> getNotes() {
// if (notes.isEmpty()) return null;
// else return notes;
// }
//
// public void setNotes(List<Note> notes) {
// this.notes = notes;
// }
//
// public List<RelatedParty> getRelatedParties() {
// if (relatedParties.isEmpty()) return null;
// else return relatedParties;
// }
//
// public void setRelatedParties(List<RelatedParty> relatedParties) {
// this.relatedParties = relatedParties;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// //this must be reimplemented
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fieldsIN are not set
// if (!(object instanceof TroubleTicket)) {
// return false;
// }
// TroubleTicket other = (TroubleTicket) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmtt.TroubleTicket[ id=" + id + " ]";
// }
//
// /**
// * @return the fieldsIN
// */
// public Set<TroubleTicketField> getFieldsIN() {
// return fieldsIN;
// }
//
// /**
// * @param fieldsIN the fieldsIN to set
// */
// public void setFieldsIN(Set<TroubleTicketField> fields) {
// this.fieldsIN = fields;
// }
// }
| import tmf.org.dsmapi.tt.TroubleTicket;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub;
/**
*
* @author pierregauthier
*/
@XmlRootElement
public class HubEvent implements Serializable {
| // Path: src/java/tmf/org/dsmapi/tt/TroubleTicket.java
// @Entity
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class TroubleTicket implements Serializable {
//
// //Add other static strings as required....
// private static final long serialVersionUID = 1L;
// // Used for incremental update
// @Transient
// @JsonIgnore
// private Set<TroubleTicketField> fieldsIN;
// @Id
// @Column(name="TT_ID")
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String correlationId;
// private String description;
// private Severity severity;
// private String type;
// private String creationDate;
// private String targetResolutionDate;
// private Status status;
// private SubStatus subStatus;
// private String statusChangeReason;
// private String statusChangeDate;
// private String resolutionDate;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_OBJECT",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedObject> relatedObjects;
//
// @ElementCollection
// @CollectionTable(
// name = "NOTES",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<Note> notes;
//
// @ElementCollection
// @CollectionTable(
// name = "RELATED_PARTY",
// joinColumns =
// @JoinColumn(name = "OWNER_ID"))
// private List<RelatedParty> relatedParties;
//
// public String getCorrelationId() {
// return correlationId;
// }
//
// public void setCorrelationId(String correlationId) {
// this.correlationId = correlationId;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(Severity severity) {
// this.severity = severity;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getCreationDate() {
// return creationDate;
// }
//
// public void setCreationDate(String creationDate) {
// this.creationDate = creationDate;
// }
//
// public String getTargetResolutionDate() {
// return targetResolutionDate;
// }
//
// public void setTargetResolutionDate(String targetResolutionDate) {
// this.targetResolutionDate = targetResolutionDate;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public SubStatus getSubStatus() {
// return subStatus;
// }
//
// public void setSubStatus(SubStatus subStatus) {
// this.subStatus = subStatus;
// }
//
// public String getStatusChangeReason() {
// return statusChangeReason;
// }
//
// public void setStatusChangeReason(String statusChangeReason) {
// this.statusChangeReason = statusChangeReason;
// }
//
// public String getStatusChangeDate() {
// return statusChangeDate;
// }
//
// public void setStatusChangeDate(String statusChangeDate) {
// this.statusChangeDate = statusChangeDate;
// }
//
// public String getResolutionDate() {
// return resolutionDate;
// }
//
// public void setResolutionDate(String resolutionDate) {
// this.resolutionDate = resolutionDate;
// }
//
// public List<RelatedObject> getRelatedObjects() {
// if (relatedObjects.isEmpty()) return null;
// else return relatedObjects;
// }
//
// public void setRelatedObjects(List<RelatedObject> relatedObjects) {
// this.relatedObjects = relatedObjects;
// }
//
// public List<Note> getNotes() {
// if (notes.isEmpty()) return null;
// else return notes;
// }
//
// public void setNotes(List<Note> notes) {
// this.notes = notes;
// }
//
// public List<RelatedParty> getRelatedParties() {
// if (relatedParties.isEmpty()) return null;
// else return relatedParties;
// }
//
// public void setRelatedParties(List<RelatedParty> relatedParties) {
// this.relatedParties = relatedParties;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// //this must be reimplemented
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fieldsIN are not set
// if (!(object instanceof TroubleTicket)) {
// return false;
// }
// TroubleTicket other = (TroubleTicket) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmtt.TroubleTicket[ id=" + id + " ]";
// }
//
// /**
// * @return the fieldsIN
// */
// public Set<TroubleTicketField> getFieldsIN() {
// return fieldsIN;
// }
//
// /**
// * @param fieldsIN the fieldsIN to set
// */
// public void setFieldsIN(Set<TroubleTicketField> fields) {
// this.fieldsIN = fields;
// }
// }
// Path: src/java/tmf/org/dsmapi/hub/HubEvent.java
import tmf.org.dsmapi.tt.TroubleTicket;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub;
/**
*
* @author pierregauthier
*/
@XmlRootElement
public class HubEvent implements Serializable {
| private TroubleTicket event; //checl for object |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/hub/service/RESTEventPublisherLocal.java | // Path: src/java/tmf/org/dsmapi/hub/Hub.java
// @Entity
// @XmlRootElement
// public class Hub implements Serializable {
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String callback;
// private String query;
//
// public String getCallback() {
// return callback;
// }
//
// public void setCallback(String callback) {
// this.callback = callback;
// }
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fields are not set
// if (!(object instanceof Hub)) {
// return false;
// }
// Hub other = (Hub) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmapi.hub.Hub[ id=" + id + " ]";
// }
// }
| import javax.ejb.Local;
import tmf.org.dsmapi.hub.Hub; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Local
public interface RESTEventPublisherLocal {
| // Path: src/java/tmf/org/dsmapi/hub/Hub.java
// @Entity
// @XmlRootElement
// public class Hub implements Serializable {
//
// private static final long serialVersionUID = 1L;
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
// private String callback;
// private String query;
//
// public String getCallback() {
// return callback;
// }
//
// public void setCallback(String callback) {
// this.callback = callback;
// }
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// @Override
// public int hashCode() {
// int hash = 0;
// hash += (id != null ? id.hashCode() : 0);
// return hash;
// }
//
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fields are not set
// if (!(object instanceof Hub)) {
// return false;
// }
// Hub other = (Hub) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
//
// @Override
// public String toString() {
// return "tmf.org.dsmapi.hub.Hub[ id=" + id + " ]";
// }
// }
// Path: src/java/tmf/org/dsmapi/hub/service/RESTEventPublisherLocal.java
import javax.ejb.Local;
import tmf.org.dsmapi.hub.Hub;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.hub.service;
/**
*
* @author pierregauthier
*/
@Local
public interface RESTEventPublisherLocal {
| public void publish(Hub hub, Object event); |
tmforum/DSMAPITT | src/java/tmf/org/dsmapi/tt/service/mapper/UnknowResourceExceptionMapper.java | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/UnknownResourceException.java
// public class UnknownResourceException extends FunctionalException {
//
// public UnknownResourceException(ExceptionType type) {
// super(type);
// }
//
// public UnknownResourceException(ExceptionType type, String message) {
// super(type, message);
// }
//
// }
| import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import tmf.org.dsmapi.commons.exceptions.UnknownResourceException; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class UnknowResourceExceptionMapper implements ExceptionMapper<UnknownResourceException> {
@Override
public Response toResponse(UnknownResourceException ex) { | // Path: src/java/tmf/org/dsmapi/tt/service/JsonFault.java
// @XmlRootElement
// @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// public class JsonFault {
//
// private ExceptionBean error;
// private String detail;
//
// public JsonFault(ExceptionBean error) {
// this.error = error;
// }
//
// public JsonFault(ExceptionBean error, String detail) {
// this.error = error;
// this.detail = detail;
// }
//
// /**
// * @return the type
// */
// public ExceptionBean getError() {
// return error;
// }
//
// /**
// * @param type the type to set
// */
// public void setError(ExceptionBean error) {
// this.error = error;
// }
//
// /**
// * @return the detail
// */
// public String getDetail() {
// return detail;
// }
//
// /**
// * @param detail the detail to set
// */
// public void setDetail(String detail) {
// this.detail = detail;
// }
//
// }
//
// Path: src/java/tmf/org/dsmapi/commons/exceptions/UnknownResourceException.java
// public class UnknownResourceException extends FunctionalException {
//
// public UnknownResourceException(ExceptionType type) {
// super(type);
// }
//
// public UnknownResourceException(ExceptionType type, String message) {
// super(type, message);
// }
//
// }
// Path: src/java/tmf/org/dsmapi/tt/service/mapper/UnknowResourceExceptionMapper.java
import tmf.org.dsmapi.tt.service.JsonFault;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import tmf.org.dsmapi.commons.exceptions.UnknownResourceException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.tt.service.mapper;
@Provider
public class UnknowResourceExceptionMapper implements ExceptionMapper<UnknownResourceException> {
@Override
public Response toResponse(UnknownResourceException ex) { | JsonFault error = new JsonFault(ex.getType().getInfo(),ex.getMessage()); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/aggregates/AggregateService.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.apache.log4j.Logger;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import java.util.*;
import org.json.*;
import java.net.*;
import javax.script.*; |
public String getAggregate() throws Exception{
if(type==JAVASCRIPT){
metric.startTimer("javascript.serialize");
jsEngine.eval("var result=null");
jsEngine.eval("if(aggregate!=null)result=JSON.stringify(aggregate);");
// Object obj=jsEngine.eval("result");
Object obj=jsEngine.get("result");
metric.stopTimer("javascript.serialize");
if(obj!=null){
aggregate=(String)obj;
}
}
return aggregate;
}
private void loadState() throws Exception{
JSONObject obj=new JSONObject(getStream("state").getLast());
index=obj.getLong("i");
outputIndex=obj.getLong("o");
aggregate=getStream("output").get(outputIndex);
if(type==JAVASCRIPT){
jsEngine.eval("var aggregate="+aggregate+";");
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
obj.put("o",outputIndex); | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/aggregates/AggregateService.java
import org.apache.log4j.Logger;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import java.util.*;
import org.json.*;
import java.net.*;
import javax.script.*;
public String getAggregate() throws Exception{
if(type==JAVASCRIPT){
metric.startTimer("javascript.serialize");
jsEngine.eval("var result=null");
jsEngine.eval("if(aggregate!=null)result=JSON.stringify(aggregate);");
// Object obj=jsEngine.eval("result");
Object obj=jsEngine.get("result");
metric.stopTimer("javascript.serialize");
if(obj!=null){
aggregate=(String)obj;
}
}
return aggregate;
}
private void loadState() throws Exception{
JSONObject obj=new JSONObject(getStream("state").getLast());
index=obj.getLong("i");
outputIndex=obj.getLong("o");
aggregate=getStream("output").get(outputIndex);
if(type==JAVASCRIPT){
jsEngine.eval("var aggregate="+aggregate+";");
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
obj.put("o",outputIndex); | getStream("state").append(obj,StreamConnection.FLUSH); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/ScriptManager.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.apache.log4j.Logger;
import java.util.*;
import org.json.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*;
import me.doubledutch.stroom.client.StreamConnection; | package me.doubledutch.stroom;
public class ScriptManager implements Runnable{
private final Logger log = Logger.getLogger("ScriptManager");
private static ScriptManager app;
private StreamHandler streamHandler;
private Map<String,String> agg=new HashMap<String,String>();
| // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/ScriptManager.java
import org.apache.log4j.Logger;
import java.util.*;
import org.json.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*;
import me.doubledutch.stroom.client.StreamConnection;
package me.doubledutch.stroom;
public class ScriptManager implements Runnable{
private final Logger log = Logger.getLogger("ScriptManager");
private static ScriptManager app;
private StreamHandler streamHandler;
private Map<String,String> agg=new HashMap<String,String>();
| private StreamConnection scriptStream; |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/ServiceManager.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.apache.log4j.Logger;
import java.util.*;
import org.json.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*;
import me.doubledutch.stroom.client.StreamConnection; | package me.doubledutch.stroom;
public class ServiceManager implements Runnable{
private final Logger log = Logger.getLogger("ServiceManager");
private static ServiceManager app;
private StreamHandler streamHandler;
private Map<String,Service> serviceMap=new HashMap<String,Service>();
private Map<String,JSONObject> agg=new HashMap<String,JSONObject>();
private AggregateManager aggregateManager;
private KeyValueManager keyValueManager;
| // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/ServiceManager.java
import org.apache.log4j.Logger;
import java.util.*;
import org.json.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*;
import me.doubledutch.stroom.client.StreamConnection;
package me.doubledutch.stroom;
public class ServiceManager implements Runnable{
private final Logger log = Logger.getLogger("ServiceManager");
private static ServiceManager app;
private StreamHandler streamHandler;
private Map<String,Service> serviceMap=new HashMap<String,Service>();
private Map<String,JSONObject> agg=new HashMap<String,JSONObject>();
private AggregateManager aggregateManager;
private KeyValueManager keyValueManager;
| private StreamConnection serviceStream; |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/query/QueryRunner.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import me.doubledutch.stroom.client.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.query.sql.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.lazyjson.*;
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*; | while(table.hasNext()){
LazyObject obj=table.next();
JSONObject out=new JSONObject();
for(DerivedColumn col:columns){
col.pickAndPlace(obj,out);
}
LazyObject outObj=new LazyObject(out.toString());
String key=query.getPartitionKey(obj);
// TODO: this is such a hack - make smarter
if(key==null)key=query.getPartitionKey(outObj);
TempTable partition=getPartition(key);
partition.append(outObj);
// picked.append(new LazyObject(out.toString()));
}
// return picked;
}
public TempTable scan(TableReference table) throws Exception{
if(table.query!=null){
QueryRunner sub=new QueryRunner(table.query);
sub.run();
if(table.condition!=null){
// Run through it
}else{
return sub.getResult();
}
}else if(table.url!=null){
// System.out.println("scanning url");
TempTable temp=createTempTable();
Stroom s=new Stroom(); | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/query/QueryRunner.java
import me.doubledutch.stroom.client.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.query.sql.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.lazyjson.*;
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
while(table.hasNext()){
LazyObject obj=table.next();
JSONObject out=new JSONObject();
for(DerivedColumn col:columns){
col.pickAndPlace(obj,out);
}
LazyObject outObj=new LazyObject(out.toString());
String key=query.getPartitionKey(obj);
// TODO: this is such a hack - make smarter
if(key==null)key=query.getPartitionKey(outObj);
TempTable partition=getPartition(key);
partition.append(outObj);
// picked.append(new LazyObject(out.toString()));
}
// return picked;
}
public TempTable scan(TableReference table) throws Exception{
if(table.query!=null){
QueryRunner sub=new QueryRunner(table.query);
sub.run();
if(table.condition!=null){
// Run through it
}else{
return sub.getResult();
}
}else if(table.url!=null){
// System.out.println("scanning url");
TempTable temp=createTempTable();
Stroom s=new Stroom(); | StreamConnection stream=s.openStream(table.url); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/MultiHostServer.java | // Path: reference/src/main/java/me/doubledutch/stroom/streams/StreamHandler.java
// public class StreamHandler{
// private String parentFolder;
// private ConcurrentHashMap<String,Stream> streamMap;
// private int MAX_COMMIT_BATCH;
// private int MAX_COMMIT_LAG;
// private long MAX_BLOCK_SIZE=32*1024*1024*1024l; // 32 gb block files
// private long MAX_INDEX_SIZE=50*1000*1000l; // close to 1gb index blocks
//
// public StreamHandler(JSONObject config) throws JSONException{
// MAX_COMMIT_BATCH=config.getInt("commit_batch_size");
// MAX_COMMIT_LAG=config.getInt("commit_batch_timeout");
// if(config.has("block_size")){
// MAX_BLOCK_SIZE=config.getLong("block_size");
// }
// if(config.has("index_size")){
// MAX_INDEX_SIZE=config.getLong("index_size");
// }
// parentFolder=config.getString("path");
// streamMap=new ConcurrentHashMap<String,Stream>();
// try{
// if(!parentFolder.endsWith(File.separator)){
// parentFolder+=File.separator;
// }
// File ftest=new File(parentFolder);
// if(!ftest.exists()){
// ftest.mkdir();
// }
// for(String subFolder:ftest.list()){
// ftest=new File(parentFolder+subFolder);
// if(ftest.exists()){
// getOrCreateStream(subFolder);
// }
// }
// }catch(Exception e){
// e.printStackTrace();
// }
//
// }
//
// public void stop(){
// synchronized(this){
// for(Stream stream:streamMap.values()){
// try{
// stream.stop();
// }catch(Exception e){}
// }
// }
// }
//
// public Stream getOrCreateStream(String topic) throws IOException{
// if(streamMap.containsKey(topic)){
// return streamMap.get(topic);
// }
// synchronized(this){
// if(!streamMap.containsKey(topic)){
// streamMap.put(topic,new Stream(parentFolder,topic,MAX_COMMIT_BATCH,MAX_COMMIT_LAG,MAX_BLOCK_SIZE,MAX_INDEX_SIZE));
// }
// }
// return streamMap.get(topic);
// }
//
// public Stream[] getStreams() throws IOException{
// return streamMap.values().toArray(new Stream[0]);
// }
//
// public Document getDocument(String topic,long location) throws IOException{
// Stream stream=getOrCreateStream(topic);
// return stream.getDocument(location);
// }
//
// public void addDocument(Document doc) throws IOException{
// Stream stream=getOrCreateStream(doc.getTopic());
// stream.addDocument(doc);
// }
//
// public void addDocument(Document doc,int writeMode) throws IOException{
// Stream stream=getOrCreateStream(doc.getTopic());
// stream.addDocument(doc,writeMode);
// }
//
// public void addDocuments(List<Document> batch) throws IOException{
// Stream stream=getOrCreateStream(batch.get(0).getTopic());
// stream.addDocuments(batch);
// }
//
// public void addDocuments(List<Document> batch,int writeMode) throws IOException{
// Stream stream=getOrCreateStream(batch.get(0).getTopic());
// stream.addDocuments(batch,writeMode);
// }
//
// public List<Document> getDocuments(String topic,long startIndex,long endIndex) throws IOException{
// Stream stream=getOrCreateStream(topic);
// return stream.getDocuments(startIndex,endIndex);
// }
//
// public void truncateStream(String topic,long index) throws IOException{
// if(index==0){
// deleteStream(topic);
// return;
// }
// Stream stream=getOrCreateStream(topic);
// stream.truncate(index);
// }
//
// public void deleteStream(String topic) throws IOException{
// Stream stream=getOrCreateStream(topic);
// stream.truncate(0);
// streamMap.remove(topic);
// File ftest=new File(parentFolder+topic);
// ftest.delete();
// }
// }
| import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.io.*;
import org.json.*;
import java.util.*;
import me.doubledutch.stroom.streams.StreamHandler;
import me.doubledutch.stroom.servlet.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*; | package me.doubledutch.stroom;
public class MultiHostServer implements Runnable{
private final Logger log = Logger.getLogger("MultiHost");
private static JSONObject config=null;
private Server server=null;
| // Path: reference/src/main/java/me/doubledutch/stroom/streams/StreamHandler.java
// public class StreamHandler{
// private String parentFolder;
// private ConcurrentHashMap<String,Stream> streamMap;
// private int MAX_COMMIT_BATCH;
// private int MAX_COMMIT_LAG;
// private long MAX_BLOCK_SIZE=32*1024*1024*1024l; // 32 gb block files
// private long MAX_INDEX_SIZE=50*1000*1000l; // close to 1gb index blocks
//
// public StreamHandler(JSONObject config) throws JSONException{
// MAX_COMMIT_BATCH=config.getInt("commit_batch_size");
// MAX_COMMIT_LAG=config.getInt("commit_batch_timeout");
// if(config.has("block_size")){
// MAX_BLOCK_SIZE=config.getLong("block_size");
// }
// if(config.has("index_size")){
// MAX_INDEX_SIZE=config.getLong("index_size");
// }
// parentFolder=config.getString("path");
// streamMap=new ConcurrentHashMap<String,Stream>();
// try{
// if(!parentFolder.endsWith(File.separator)){
// parentFolder+=File.separator;
// }
// File ftest=new File(parentFolder);
// if(!ftest.exists()){
// ftest.mkdir();
// }
// for(String subFolder:ftest.list()){
// ftest=new File(parentFolder+subFolder);
// if(ftest.exists()){
// getOrCreateStream(subFolder);
// }
// }
// }catch(Exception e){
// e.printStackTrace();
// }
//
// }
//
// public void stop(){
// synchronized(this){
// for(Stream stream:streamMap.values()){
// try{
// stream.stop();
// }catch(Exception e){}
// }
// }
// }
//
// public Stream getOrCreateStream(String topic) throws IOException{
// if(streamMap.containsKey(topic)){
// return streamMap.get(topic);
// }
// synchronized(this){
// if(!streamMap.containsKey(topic)){
// streamMap.put(topic,new Stream(parentFolder,topic,MAX_COMMIT_BATCH,MAX_COMMIT_LAG,MAX_BLOCK_SIZE,MAX_INDEX_SIZE));
// }
// }
// return streamMap.get(topic);
// }
//
// public Stream[] getStreams() throws IOException{
// return streamMap.values().toArray(new Stream[0]);
// }
//
// public Document getDocument(String topic,long location) throws IOException{
// Stream stream=getOrCreateStream(topic);
// return stream.getDocument(location);
// }
//
// public void addDocument(Document doc) throws IOException{
// Stream stream=getOrCreateStream(doc.getTopic());
// stream.addDocument(doc);
// }
//
// public void addDocument(Document doc,int writeMode) throws IOException{
// Stream stream=getOrCreateStream(doc.getTopic());
// stream.addDocument(doc,writeMode);
// }
//
// public void addDocuments(List<Document> batch) throws IOException{
// Stream stream=getOrCreateStream(batch.get(0).getTopic());
// stream.addDocuments(batch);
// }
//
// public void addDocuments(List<Document> batch,int writeMode) throws IOException{
// Stream stream=getOrCreateStream(batch.get(0).getTopic());
// stream.addDocuments(batch,writeMode);
// }
//
// public List<Document> getDocuments(String topic,long startIndex,long endIndex) throws IOException{
// Stream stream=getOrCreateStream(topic);
// return stream.getDocuments(startIndex,endIndex);
// }
//
// public void truncateStream(String topic,long index) throws IOException{
// if(index==0){
// deleteStream(topic);
// return;
// }
// Stream stream=getOrCreateStream(topic);
// stream.truncate(index);
// }
//
// public void deleteStream(String topic) throws IOException{
// Stream stream=getOrCreateStream(topic);
// stream.truncate(0);
// streamMap.remove(topic);
// File ftest=new File(parentFolder+topic);
// ftest.delete();
// }
// }
// Path: reference/src/main/java/me/doubledutch/stroom/MultiHostServer.java
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import java.io.*;
import org.json.*;
import java.util.*;
import me.doubledutch.stroom.streams.StreamHandler;
import me.doubledutch.stroom.servlet.*;
import me.doubledutch.stroom.filters.*;
import me.doubledutch.stroom.aggregates.*;
package me.doubledutch.stroom;
public class MultiHostServer implements Runnable{
private final Logger log = Logger.getLogger("MultiHost");
private static JSONObject config=null;
private Server server=null;
| private StreamHandler streamHandler=null; |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/Service.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.json.*;
import java.io.*;
import java.net.*;
import java.util.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import javax.script.*;
import me.doubledutch.stroom.perf.*; | package me.doubledutch.stroom;
public abstract class Service implements Runnable{
public static int HTTP=0;
public static int QUERY=1;
public static int JAVASCRIPT=2;
public static int SAMPLE=3;
public int type=HTTP;
public String url=null;
private int WAIT_TIME=1000;
private int BATCH_SIZE=1000;
private int BATCH_TIMEOUT=10*1000;
public long index=-1;
public static int ERR_IGNORE=0;
public static int ERR_RETRY=1;
public static int ERR_HALT=2;
private int errorStrategy=ERR_IGNORE;
private String lastError=null;
private Map<String,MockStreamConnection> mockMap=new HashMap<String,MockStreamConnection>();
private StreamHandler streamHandler=null;
private boolean isRunning=false;
private boolean shouldBeRunning=false;
private Thread thread=null;
private boolean isDisabled=false;
private String id;
private String script=null;
public ScriptEngine jsEngine;
public Invocable jsInvocable;
private JSONObject config;
private BatchMetric lastMetric=null;
| // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/Service.java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import javax.script.*;
import me.doubledutch.stroom.perf.*;
package me.doubledutch.stroom;
public abstract class Service implements Runnable{
public static int HTTP=0;
public static int QUERY=1;
public static int JAVASCRIPT=2;
public static int SAMPLE=3;
public int type=HTTP;
public String url=null;
private int WAIT_TIME=1000;
private int BATCH_SIZE=1000;
private int BATCH_TIMEOUT=10*1000;
public long index=-1;
public static int ERR_IGNORE=0;
public static int ERR_RETRY=1;
public static int ERR_HALT=2;
private int errorStrategy=ERR_IGNORE;
private String lastError=null;
private Map<String,MockStreamConnection> mockMap=new HashMap<String,MockStreamConnection>();
private StreamHandler streamHandler=null;
private boolean isRunning=false;
private boolean shouldBeRunning=false;
private Thread thread=null;
private boolean isDisabled=false;
private String id;
private String script=null;
public ScriptEngine jsEngine;
public Invocable jsInvocable;
private JSONObject config;
private BatchMetric lastMetric=null;
| private Map<String,StreamConnection> streamMap=new HashMap<String,StreamConnection>(); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/filters/KeyValueService.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
| import org.apache.log4j.Logger;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection;
import java.util.*;
import java.util.concurrent.*;
import org.json.*;
import java.net.*;
import javax.script.*;
import java.io.*; | JSONObject obj=new JSONObject(str);
index=obj.getLong("i");
if(obj.has("o")){
JSONObject objSt=obj.getJSONObject("o");
Iterator<String> keyIt=objSt.keys();
while(keyIt.hasNext()){
String key=keyIt.next();
if(objSt.isNull(key)){
keyMap.remove(key);
}else{
keyMap.put(key,objSt.getLong(key));
}
}
}
}
loc+=batch.size();
batch=getStream("state").get(loc,loc+500);
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
if(stateMap!=null){
// obj.put("o",outputIndex);
obj.put("o",stateMap);
} | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/filters/KeyValueService.java
import org.apache.log4j.Logger;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection;
import java.util.*;
import java.util.concurrent.*;
import org.json.*;
import java.net.*;
import javax.script.*;
import java.io.*;
JSONObject obj=new JSONObject(str);
index=obj.getLong("i");
if(obj.has("o")){
JSONObject objSt=obj.getJSONObject("o");
Iterator<String> keyIt=objSt.keys();
while(keyIt.hasNext()){
String key=keyIt.next();
if(objSt.isNull(key)){
keyMap.remove(key);
}else{
keyMap.put(key,objSt.getLong(key));
}
}
}
}
loc+=batch.size();
batch=getStream("state").get(loc,loc+500);
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
if(stateMap!=null){
// obj.put("o",outputIndex);
obj.put("o",stateMap);
} | getStream("state").append(obj,StreamConnection.FLUSH); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/aggregates/PartitionedAggregateService.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.apache.log4j.Logger;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.*;
import java.util.*;
import me.doubledutch.stroom.client.StreamConnection;
import org.json.*;
import java.net.*;
import javax.script.*; | JSONObject objSt=obj.getJSONObject("o");
Iterator<String> keyIt=objSt.keys();
while(keyIt.hasNext()){
String key=keyIt.next();
aggregateMap.put(key,objSt.getLong(key));
}
}
loc+=batch.size();
batch=getStream("state").get(loc,loc+500);
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
// Save snapshot and build state
List<String> batch=new ArrayList<String>();
List<String> pKeyList=new ArrayList<String>();
for(String key:partitionTouchSet){
pKeyList.add(key);
String data=aggregateCache.get(key);
batch.add(data);
}
metric.startTimer("output.append");
List<Long> results=null;
if(batch.size()>0){ | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/aggregates/PartitionedAggregateService.java
import org.apache.log4j.Logger;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.*;
import java.util.*;
import me.doubledutch.stroom.client.StreamConnection;
import org.json.*;
import java.net.*;
import javax.script.*;
JSONObject objSt=obj.getJSONObject("o");
Iterator<String> keyIt=objSt.keys();
while(keyIt.hasNext()){
String key=keyIt.next();
aggregateMap.put(key,objSt.getLong(key));
}
}
loc+=batch.size();
batch=getStream("state").get(loc,loc+500);
}
}
private void saveState() throws Exception{
JSONObject obj=new JSONObject();
obj.put("i",index);
// Save snapshot and build state
List<String> batch=new ArrayList<String>();
List<String> pKeyList=new ArrayList<String>();
for(String key:partitionTouchSet){
pKeyList.add(key);
String data=aggregateCache.get(key);
batch.add(data);
}
metric.startTimer("output.append");
List<Long> results=null;
if(batch.size()>0){ | results=getStream("output").append(batch,StreamConnection.FLUSH); |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/ScriptAPI.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
| import java.io.*;
import java.net.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection; | package me.doubledutch.stroom;
public class ScriptAPI{
private StreamHandler streamHandler;
public ScriptAPI(StreamHandler handler){
this.streamHandler=handler;
}
private String getStreamName(URI stream){
String path=stream.getPath();
if(!path.startsWith("/stream/"))return null;
return path.substring(path.lastIndexOf("/")+1); // TODO: possibly make smarter and less breakable
}
| // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/ScriptAPI.java
import java.io.*;
import java.net.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection;
package me.doubledutch.stroom;
public class ScriptAPI{
private StreamHandler streamHandler;
public ScriptAPI(StreamHandler handler){
this.streamHandler=handler;
}
private String getStreamName(URI stream){
String path=stream.getPath();
if(!path.startsWith("/stream/"))return null;
return path.substring(path.lastIndexOf("/")+1); // TODO: possibly make smarter and less breakable
}
| public StreamConnection openStream(String name) throws Exception{ |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/ScriptAPI.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
| import java.io.*;
import java.net.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection; | package me.doubledutch.stroom;
public class ScriptAPI{
private StreamHandler streamHandler;
public ScriptAPI(StreamHandler handler){
this.streamHandler=handler;
}
private String getStreamName(URI stream){
String path=stream.getPath();
if(!path.startsWith("/stream/"))return null;
return path.substring(path.lastIndexOf("/")+1); // TODO: possibly make smarter and less breakable
}
public StreamConnection openStream(String name) throws Exception{
if(name.indexOf("://")==-1){
// TODO: make this way less hacky
name="local://direct/stream/"+name;
}
URI stream=new URI(name);
String scheme=stream.getScheme();
String streamName=getStreamName(stream);
if(scheme.equals("local")){
String host=stream.getHost();
if(host.equals("direct")){
return new LocalStreamConnection(streamHandler.getOrCreateStream(streamName));
}
}
return null;
}
| // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
//
// Path: reference/src/main/java/me/doubledutch/stroom/client/KVStoreConnection.java
// public interface KVStoreConnection{
// public String get(String key) throws IOException;
// public List<String> list() throws IOException;
// public List<String> search(String pattern) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/ScriptAPI.java
import java.io.*;
import java.net.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.client.StreamConnection;
import me.doubledutch.stroom.client.KVStoreConnection;
package me.doubledutch.stroom;
public class ScriptAPI{
private StreamHandler streamHandler;
public ScriptAPI(StreamHandler handler){
this.streamHandler=handler;
}
private String getStreamName(URI stream){
String path=stream.getPath();
if(!path.startsWith("/stream/"))return null;
return path.substring(path.lastIndexOf("/")+1); // TODO: possibly make smarter and less breakable
}
public StreamConnection openStream(String name) throws Exception{
if(name.indexOf("://")==-1){
// TODO: make this way less hacky
name="local://direct/stream/"+name;
}
URI stream=new URI(name);
String scheme=stream.getScheme();
String streamName=getStreamName(stream);
if(scheme.equals("local")){
String host=stream.getHost();
if(host.equals("direct")){
return new LocalStreamConnection(streamHandler.getOrCreateStream(streamName));
}
}
return null;
}
| public KVStoreConnection openKVStore(String name) throws Exception{ |
doubledutch/StroomData | reference/src/main/java/me/doubledutch/stroom/filters/FilterService.java | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
| import org.apache.log4j.Logger;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.*;
import me.doubledutch.lazyjson.*;
import me.doubledutch.stroom.client.StreamConnection;
import java.util.*;
import org.json.*;
import java.net.*;
import javax.script.*; | package me.doubledutch.stroom.filters;
public class FilterService extends Service{
private final Logger log = Logger.getLogger("Filter");
private long outputIndex=-1;
private double sampleRate=1.0;
private BatchMetric metric=null;
private List<String> buffer=null;
private int bufferSize=0;
private long lastFlush=0;
public FilterService(StreamHandler handler,JSONObject obj) throws Exception{
super(handler,obj);
String strType=obj.getString("type");
if(strType.equals("sample")){
type=SAMPLE;
sampleRate=obj.getDouble("sample_rate");
}
}
private synchronized void loadState() throws Exception{
if(getStream("state").getCount()>0){
JSONObject obj=new JSONObject(getStream("state").getLast());
index=obj.getLong("i");
outputIndex=obj.getLong("o");
}
}
private synchronized void saveState() throws Exception{
if(index>-1){
JSONObject obj=new JSONObject();
obj.put("i",index);
obj.put("o",outputIndex); | // Path: reference/src/main/java/me/doubledutch/stroom/client/StreamConnection.java
// public interface StreamConnection{
// public final static int LINEAR=0;
// public final static int SYNC=1;
// public final static int FLUSH=2;
// public final static int NONE=3;
//
// public List<String> get(long index,long endIndex) throws IOException;
// public String get(long index) throws IOException;
// public String getLast() throws IOException;
// public long getCount() throws IOException;
//
// public long append(JSONObject data) throws IOException,JSONException;
// public long append(String data) throws IOException,JSONException;
// public List<Long> append(List<String> data) throws IOException,JSONException;
//
// public long append(JSONObject data,int hint) throws IOException,JSONException;
// public long append(String data,int hint) throws IOException,JSONException;
// public List<Long> append(List<String> data,int hint) throws IOException,JSONException;
//
// public void truncate(long index) throws IOException;
// }
// Path: reference/src/main/java/me/doubledutch/stroom/filters/FilterService.java
import org.apache.log4j.Logger;
import me.doubledutch.stroom.perf.*;
import me.doubledutch.stroom.streams.*;
import me.doubledutch.stroom.*;
import me.doubledutch.lazyjson.*;
import me.doubledutch.stroom.client.StreamConnection;
import java.util.*;
import org.json.*;
import java.net.*;
import javax.script.*;
package me.doubledutch.stroom.filters;
public class FilterService extends Service{
private final Logger log = Logger.getLogger("Filter");
private long outputIndex=-1;
private double sampleRate=1.0;
private BatchMetric metric=null;
private List<String> buffer=null;
private int bufferSize=0;
private long lastFlush=0;
public FilterService(StreamHandler handler,JSONObject obj) throws Exception{
super(handler,obj);
String strType=obj.getString("type");
if(strType.equals("sample")){
type=SAMPLE;
sampleRate=obj.getDouble("sample_rate");
}
}
private synchronized void loadState() throws Exception{
if(getStream("state").getCount()>0){
JSONObject obj=new JSONObject(getStream("state").getLast());
index=obj.getLong("i");
outputIndex=obj.getLong("o");
}
}
private synchronized void saveState() throws Exception{
if(index>-1){
JSONObject obj=new JSONObject();
obj.put("i",index);
obj.put("o",outputIndex); | getStream("state").append(obj,StreamConnection.FLUSH); |
xnx3/xunxian | xunxianAutoFight/src/action/LogThread.java | // Path: xunxianAutoFight/src/Func/Sleep.java
// public class Sleep {
// /**
// * 延迟等待,多线程sleep,与软件同步停止
// * @param millis毫秒
// */
// public void sleep(int millis){
//
// try {
// if(millis>3000){
// int i=Math.round(millis/1000)+1;
// //include.Command.run 软件的主体控制运行状态,点击结束后此项为false
// for(int j=0;j<i&&include.Command.run;j++){
// Thread.sleep(1000);
// }
// }else{
// Thread.sleep(millis);
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: xunxianAutoFight/src/include/Module/TextFile.java
// public class TextFile {
//
// /**
// * 读文本文件,返回文件信息
// * path:文件路径,encode:文件编码.如UTF-8,GBK
// */
// public String read(String path,String encode){
// StringBuffer xnx3_content=new StringBuffer();
// try{
// File file=new File(path);
// BufferedReader xnx3_reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
// String date=null;
// while((date=xnx3_reader.readLine())!=null){
// xnx3_content.append(date);
// }
// xnx3_reader.close();
// }catch (Exception e) {
// }
//
// return xnx3_content.toString();
// }
// public String read(File file,String encode){
// StringBuffer xnx3_content=new StringBuffer();
// try{
// BufferedReader xnx3_reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
// String date=null;
// while((date=xnx3_reader.readLine())!=null){
// xnx3_content.append(date);
// }
// xnx3_reader.close();
// }catch (Exception e) {
// }
//
// return xnx3_content.toString();
// }
//
//
//
// /*
// * boolean
// * 传入要保存至的路径————如D:\\a.txt
// * 传入要保存的内容,String content
// */
//
// public boolean write(String path,String xnx3_content){
// try {
// FileWriter fw=new FileWriter(path);
// java.io.PrintWriter pw=new java.io.PrintWriter(fw);
// pw.print(xnx3_content);
// pw.close();
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public boolean write(File file,String xnx3_content){
// try {
// java.io.PrintWriter pw=new java.io.PrintWriter(file);
// pw.print(xnx3_content);
// pw.close();
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public static void main(String[] args) {
// // System.out.println(new TextFile().read("F:\\MyEclipseWordspace\\xunxianAutoFight\\log.txt", "utf-8").replaceAll(" ", Command.lineNotePad));
//
// }
// }
| import Func.Sleep;
import include.Command;
import include.Module.TextFile;
| package action;
public class LogThread extends Thread {
private Sleep sleep=null;
public LogThread(){
this.sleep=new Sleep();
//将资源库中的文件转移至运行文件同目录,复制、并覆盖
try {
include.Module.File.copyFile(Command.thisFilePath+"\\"+Command.resource+"\\log.txt", Command.thisFilePath+"\\log.txt");
} catch (Exception e) {
new Func.File().log("将资源库中的文件转移至运行文件同目录,复制、并覆盖时异常捕获:"+e.getMessage());
}
}
@Override
public void run() {
while(Command.mainThread){
this.sleep.sleep(Command.logThreadSleep); //每10分钟一次日志保存
boolean writeFile=false;
try {
| // Path: xunxianAutoFight/src/Func/Sleep.java
// public class Sleep {
// /**
// * 延迟等待,多线程sleep,与软件同步停止
// * @param millis毫秒
// */
// public void sleep(int millis){
//
// try {
// if(millis>3000){
// int i=Math.round(millis/1000)+1;
// //include.Command.run 软件的主体控制运行状态,点击结束后此项为false
// for(int j=0;j<i&&include.Command.run;j++){
// Thread.sleep(1000);
// }
// }else{
// Thread.sleep(millis);
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
//
// Path: xunxianAutoFight/src/include/Module/TextFile.java
// public class TextFile {
//
// /**
// * 读文本文件,返回文件信息
// * path:文件路径,encode:文件编码.如UTF-8,GBK
// */
// public String read(String path,String encode){
// StringBuffer xnx3_content=new StringBuffer();
// try{
// File file=new File(path);
// BufferedReader xnx3_reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
// String date=null;
// while((date=xnx3_reader.readLine())!=null){
// xnx3_content.append(date);
// }
// xnx3_reader.close();
// }catch (Exception e) {
// }
//
// return xnx3_content.toString();
// }
// public String read(File file,String encode){
// StringBuffer xnx3_content=new StringBuffer();
// try{
// BufferedReader xnx3_reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
// String date=null;
// while((date=xnx3_reader.readLine())!=null){
// xnx3_content.append(date);
// }
// xnx3_reader.close();
// }catch (Exception e) {
// }
//
// return xnx3_content.toString();
// }
//
//
//
// /*
// * boolean
// * 传入要保存至的路径————如D:\\a.txt
// * 传入要保存的内容,String content
// */
//
// public boolean write(String path,String xnx3_content){
// try {
// FileWriter fw=new FileWriter(path);
// java.io.PrintWriter pw=new java.io.PrintWriter(fw);
// pw.print(xnx3_content);
// pw.close();
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public boolean write(File file,String xnx3_content){
// try {
// java.io.PrintWriter pw=new java.io.PrintWriter(file);
// pw.print(xnx3_content);
// pw.close();
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public static void main(String[] args) {
// // System.out.println(new TextFile().read("F:\\MyEclipseWordspace\\xunxianAutoFight\\log.txt", "utf-8").replaceAll(" ", Command.lineNotePad));
//
// }
// }
// Path: xunxianAutoFight/src/action/LogThread.java
import Func.Sleep;
import include.Command;
import include.Module.TextFile;
package action;
public class LogThread extends Thread {
private Sleep sleep=null;
public LogThread(){
this.sleep=new Sleep();
//将资源库中的文件转移至运行文件同目录,复制、并覆盖
try {
include.Module.File.copyFile(Command.thisFilePath+"\\"+Command.resource+"\\log.txt", Command.thisFilePath+"\\log.txt");
} catch (Exception e) {
new Func.File().log("将资源库中的文件转移至运行文件同目录,复制、并覆盖时异常捕获:"+e.getMessage());
}
}
@Override
public void run() {
while(Command.mainThread){
this.sleep.sleep(Command.logThreadSleep); //每10分钟一次日志保存
boolean writeFile=false;
try {
| TextFile textFile=new include.Module.TextFile();
|
xnx3/xunxian | xunxianAutoFight/src/action/Skill.java | // Path: xunxianAutoFight/src/Func/Lang.java
// public class Lang {
//
// /**
// * 字符型转换为整数型
// * <li>value:待转换的字符串
// * <li>errorNum:try异常后的返回值
// * @return
// */
// public int Integer_(String value,int errorNum){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
//
// /**
// *
// * @param value 要转换的
// * @param errorNum 转换出错异常时返回的值
// * @param radix 进制。16进制转换则为16
// * @return 返回int-10禁制
// */
// public int Integer_(String value,int errorNum,int radix){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value, radix);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
// }
| import Func.Lang;
import include.Command;
| package action;
public class Skill {
public Skill() {
}
public void setVisible(){
Command.JframeSkill.setVisible(true);
jComboBox1UseItemStateChanged();
jComboBox2UseItemStateChanged();
jComboBox3UseItemStateChanged();
jComboBox4UseItemStateChanged();
jComboBox5UseItemStateChanged();
}
/**
* 初始化数据,将界面的数据加载至Command
*/
public void initData(){
| // Path: xunxianAutoFight/src/Func/Lang.java
// public class Lang {
//
// /**
// * 字符型转换为整数型
// * <li>value:待转换的字符串
// * <li>errorNum:try异常后的返回值
// * @return
// */
// public int Integer_(String value,int errorNum){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
//
// /**
// *
// * @param value 要转换的
// * @param errorNum 转换出错异常时返回的值
// * @param radix 进制。16进制转换则为16
// * @return 返回int-10禁制
// */
// public int Integer_(String value,int errorNum,int radix){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value, radix);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
// }
// Path: xunxianAutoFight/src/action/Skill.java
import Func.Lang;
import include.Command;
package action;
public class Skill {
public Skill() {
}
public void setVisible(){
Command.JframeSkill.setVisible(true);
jComboBox1UseItemStateChanged();
jComboBox2UseItemStateChanged();
jComboBox3UseItemStateChanged();
jComboBox4UseItemStateChanged();
jComboBox5UseItemStateChanged();
}
/**
* 初始化数据,将界面的数据加载至Command
*/
public void initData(){
| Lang lang=new Lang();
|
xnx3/xunxian | xunxianAutoFight/src/action/SystemThread.java | // Path: xunxianAutoFight/src/Func/Sleep.java
// public class Sleep {
// /**
// * 延迟等待,多线程sleep,与软件同步停止
// * @param millis毫秒
// */
// public void sleep(int millis){
//
// try {
// if(millis>3000){
// int i=Math.round(millis/1000)+1;
// //include.Command.run 软件的主体控制运行状态,点击结束后此项为false
// for(int j=0;j<i&&include.Command.run;j++){
// Thread.sleep(1000);
// }
// }else{
// Thread.sleep(millis);
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
| import Func.Sleep;
import include.Command;
| package action;
/**
* 系统相关
* @author xnx3
*
*/
public class SystemThread extends Thread {
public void run(){
| // Path: xunxianAutoFight/src/Func/Sleep.java
// public class Sleep {
// /**
// * 延迟等待,多线程sleep,与软件同步停止
// * @param millis毫秒
// */
// public void sleep(int millis){
//
// try {
// if(millis>3000){
// int i=Math.round(millis/1000)+1;
// //include.Command.run 软件的主体控制运行状态,点击结束后此项为false
// for(int j=0;j<i&&include.Command.run;j++){
// Thread.sleep(1000);
// }
// }else{
// Thread.sleep(millis);
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// Path: xunxianAutoFight/src/action/SystemThread.java
import Func.Sleep;
import include.Command;
package action;
/**
* 系统相关
* @author xnx3
*
*/
public class SystemThread extends Thread {
public void run(){
| Sleep sleep=new Func.Sleep();
|
xnx3/xunxian | xunxianAutoFight/src/action/File.java | // Path: xunxianAutoFight/src/Func/Lang.java
// public class Lang {
//
// /**
// * 字符型转换为整数型
// * <li>value:待转换的字符串
// * <li>errorNum:try异常后的返回值
// * @return
// */
// public int Integer_(String value,int errorNum){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
//
// /**
// *
// * @param value 要转换的
// * @param errorNum 转换出错异常时返回的值
// * @param radix 进制。16进制转换则为16
// * @return 返回int-10禁制
// */
// public int Integer_(String value,int errorNum,int radix){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value, radix);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
// }
| import include.Command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import net.sf.json.JSONArray;
import Func.Lang;
| package action;
public class File {
/**
* 加载系统方面信息
*/
public void systemLoad(){
| // Path: xunxianAutoFight/src/Func/Lang.java
// public class Lang {
//
// /**
// * 字符型转换为整数型
// * <li>value:待转换的字符串
// * <li>errorNum:try异常后的返回值
// * @return
// */
// public int Integer_(String value,int errorNum){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
//
// /**
// *
// * @param value 要转换的
// * @param errorNum 转换出错异常时返回的值
// * @param radix 进制。16进制转换则为16
// * @return 返回int-10禁制
// */
// public int Integer_(String value,int errorNum,int radix){
// int xnx3_result=0;
//
// //首先判断字符串不能为空
// if(value==null||value.equalsIgnoreCase("null")){
// xnx3_result=errorNum;
// }else{
// try {
// xnx3_result=Integer.parseInt(value, radix);
// } catch (Exception e) {
// xnx3_result=errorNum;
// }
// }
//
// return xnx3_result;
// }
// }
// Path: xunxianAutoFight/src/action/File.java
import include.Command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import net.sf.json.JSONArray;
import Func.Lang;
package action;
public class File {
/**
* 加载系统方面信息
*/
public void systemLoad(){
| Lang lang=new Func.Lang();
|
Radseq/Mystic-Bastion | src/main/java/postProcessing/Fbo.java | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
| import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import engineTester.Settings; | }
/**
* Deletes the frame buffer and its attachments when the game closes.
*/
public void cleanUp() {
GL30.glDeleteFramebuffers(frameBuffer);
GL11.glDeleteTextures(colourTexture);
GL11.glDeleteTextures(depthTexture);
GL30.glDeleteRenderbuffers(depthBuffer);
GL30.glDeleteRenderbuffers(colourBuffer);
GL30.glDeleteRenderbuffers(colourBuffer2);
}
/**
* Binds the frame buffer, setting it as the current render target. Anything
* rendered after this will be rendered to this FBO, and not to the screen.
*/
public void bindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, frameBuffer);
GL11.glViewport(0, 0, width, height);
}
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
* render target. Anything rendered after this will be rendered to the
* screen, and not this FBO.
*/
public void unbindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
// Path: src/main/java/postProcessing/Fbo.java
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import engineTester.Settings;
}
/**
* Deletes the frame buffer and its attachments when the game closes.
*/
public void cleanUp() {
GL30.glDeleteFramebuffers(frameBuffer);
GL11.glDeleteTextures(colourTexture);
GL11.glDeleteTextures(depthTexture);
GL30.glDeleteRenderbuffers(depthBuffer);
GL30.glDeleteRenderbuffers(colourBuffer);
GL30.glDeleteRenderbuffers(colourBuffer2);
}
/**
* Binds the frame buffer, setting it as the current render target. Anything
* rendered after this will be rendered to this FBO, and not to the screen.
*/
public void bindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, frameBuffer);
GL11.glViewport(0, 0, width, height);
}
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
* render target. Anything rendered after this will be rendered to the
* screen, and not this FBO.
*/
public void unbindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | GL11.glViewport(0, 0, Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT); |
Radseq/Mystic-Bastion | src/main/java/renderEngine/OBJLoader.java | // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import engineTester.MainGameLoop;
import models.RawModel;
| package renderEngine;
public class OBJLoader {
public static RawModel loadObjModel(String fileName, Loader loader) {
FileReader fr = null;
try {
| // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
// Path: src/main/java/renderEngine/OBJLoader.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import engineTester.MainGameLoop;
import models.RawModel;
package renderEngine;
public class OBJLoader {
public static RawModel loadObjModel(String fileName, Loader loader) {
FileReader fr = null;
try {
| fr = new FileReader(new File(MainGameLoop.fileManager.getModelFile(fileName)));
|
Radseq/Mystic-Bastion | src/main/java/network/packets/PacketMove.java | // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
| import network.GameClient;
| package network.packets;
public class PacketMove extends Packet {
private String userName;
private float posX, posY, posZ, angle;
public PacketMove(byte[] data) {
super(02);
String[] dataArray = readData(data).split("@");
this.userName = dataArray[0];
this.posX = Float.parseFloat(dataArray[1]);
this.posY = Float.parseFloat(dataArray[2]);
this.posZ = Float.parseFloat(dataArray[3]);
this.angle = Float.parseFloat(dataArray[4]);
}
public PacketMove(String username, float x, float y, float z, float angle) {
super(02);
this.userName = username;
this.posX = x;
this.posY = y;
this.posZ = z;
this.angle = angle;
}
@Override
| // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/network/packets/PacketMove.java
import network.GameClient;
package network.packets;
public class PacketMove extends Packet {
private String userName;
private float posX, posY, posZ, angle;
public PacketMove(byte[] data) {
super(02);
String[] dataArray = readData(data).split("@");
this.userName = dataArray[0];
this.posX = Float.parseFloat(dataArray[1]);
this.posY = Float.parseFloat(dataArray[2]);
this.posZ = Float.parseFloat(dataArray[3]);
this.angle = Float.parseFloat(dataArray[4]);
}
public PacketMove(String username, float x, float y, float z, float angle) {
super(02);
this.userName = username;
this.posX = x;
this.posY = y;
this.posZ = z;
this.angle = angle;
}
@Override
| public void writeData(GameClient client) {
|
Radseq/Mystic-Bastion | src/main/java/network/packets/PacketDisconnect.java | // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
| import network.GameClient;
| package network.packets;
public class PacketDisconnect extends Packet {
private String userName;
public PacketDisconnect(byte[] data) {
super(01);
this.userName = readData(data);
}
public PacketDisconnect(String userName) {
super(01);
this.userName = userName;
}
@Override
public byte[] getData() {
return ("01" + this.userName).getBytes();
}
@Override
| // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/network/packets/PacketDisconnect.java
import network.GameClient;
package network.packets;
public class PacketDisconnect extends Packet {
private String userName;
public PacketDisconnect(byte[] data) {
super(01);
this.userName = readData(data);
}
public PacketDisconnect(String userName) {
super(01);
this.userName = userName;
}
@Override
public byte[] getData() {
return ("01" + this.userName).getBytes();
}
@Override
| public void writeData(GameClient client) {
|
Radseq/Mystic-Bastion | src/main/java/fontMeshCreator/GUIText.java | // Path: src/main/java/fontRendering/TextMaster.java
// public class TextMaster {
//
// private static Loader loader;
// private static Map<FontType, List<GUIText>> texts = new HashMap<FontType, List<GUIText>>();
// private static FontRenderer renderer;
//
// public static void init(Loader theLoader) {
// renderer = new FontRenderer();
// loader = theLoader;
// }
//
// public static void render() {
// renderer.render(texts);
// }
//
// public static void loadText(GUIText text) {
// FontType font = text.getFont();
// TextMeshData data = font.loadText(text);
// int vao = loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
// text.setMeshInfo(vao, data.getVertexCount());
// List<GUIText> textBatch = texts.get(font);
// if (textBatch == null) {
// textBatch = new ArrayList<GUIText>();
// texts.put(font, textBatch);
// }
// textBatch.add(text);
// }
//
// public static void removeText(GUIText text) {
// List<GUIText> textBatch = texts.get(text.getFont());
// textBatch.remove(text);
// if (textBatch.isEmpty()) {
// texts.remove(texts.get(text.getFont()));
// }
// }
//
// public static void cleanUp() {
// renderer.cleanUp();
// }
//
// }
| import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import fontRendering.TextMaster;
| package fontMeshCreator;
/**
* Represents a piece of text in the game.
*
* @author Karl
*
*/
public class GUIText {
private String textString;
private float fontSize;
private int textMeshVao;
private int vertexCount;
private Vector3f colour = new Vector3f(0f, 0f, 0f);
private Vector2f position;
private float lineMaxSize;
private int numberOfLines;
private FontType font;
private boolean centerText = false;
private float distanceFieldWidth;
private float distanceFieldEdge;
private float borderWidth;
private float borderEdge;
private Vector2f offset = new Vector2f(0f, 0f);
private Vector3f outlineColour = new Vector3f(0f, 0f, 0f);
/**
* Creates a new text, loads the text's quads into a VAO, and adds the text
* to the screen.
*
* @param text
* - the text.
* @param fontSize
* - the font size of the text, where a font size of 1 is the
* default size.
* @param font
* - the font that this text should use.
* @param position
* - the position on the screen where the top left corner of the
* text should be rendered. The top left corner of the screen is
* (0, 0) and the bottom right is (1, 1).
* @param maxLineLength
* - basically the width of the virtual page in terms of screen
* width (1 is full screen width, 0.5 is half the width of the
* screen, etc.) Text cannot go off the edge of the page, so if
* the text is longer than this length it will go onto the next
* line. When text is centered it is centered into the middle of
* the line, based on this line length value.
* @param centered
* - whether the text should be centered or not.
*/
public GUIText(String text, float fontSize, FontType font, Vector2f position, float maxLineLength,
boolean centered) {
this.textString = text;
this.fontSize = fontSize;
this.font = font;
this.position = position;
this.lineMaxSize = maxLineLength;
this.centerText = centered;
| // Path: src/main/java/fontRendering/TextMaster.java
// public class TextMaster {
//
// private static Loader loader;
// private static Map<FontType, List<GUIText>> texts = new HashMap<FontType, List<GUIText>>();
// private static FontRenderer renderer;
//
// public static void init(Loader theLoader) {
// renderer = new FontRenderer();
// loader = theLoader;
// }
//
// public static void render() {
// renderer.render(texts);
// }
//
// public static void loadText(GUIText text) {
// FontType font = text.getFont();
// TextMeshData data = font.loadText(text);
// int vao = loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
// text.setMeshInfo(vao, data.getVertexCount());
// List<GUIText> textBatch = texts.get(font);
// if (textBatch == null) {
// textBatch = new ArrayList<GUIText>();
// texts.put(font, textBatch);
// }
// textBatch.add(text);
// }
//
// public static void removeText(GUIText text) {
// List<GUIText> textBatch = texts.get(text.getFont());
// textBatch.remove(text);
// if (textBatch.isEmpty()) {
// texts.remove(texts.get(text.getFont()));
// }
// }
//
// public static void cleanUp() {
// renderer.cleanUp();
// }
//
// }
// Path: src/main/java/fontMeshCreator/GUIText.java
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import fontRendering.TextMaster;
package fontMeshCreator;
/**
* Represents a piece of text in the game.
*
* @author Karl
*
*/
public class GUIText {
private String textString;
private float fontSize;
private int textMeshVao;
private int vertexCount;
private Vector3f colour = new Vector3f(0f, 0f, 0f);
private Vector2f position;
private float lineMaxSize;
private int numberOfLines;
private FontType font;
private boolean centerText = false;
private float distanceFieldWidth;
private float distanceFieldEdge;
private float borderWidth;
private float borderEdge;
private Vector2f offset = new Vector2f(0f, 0f);
private Vector3f outlineColour = new Vector3f(0f, 0f, 0f);
/**
* Creates a new text, loads the text's quads into a VAO, and adds the text
* to the screen.
*
* @param text
* - the text.
* @param fontSize
* - the font size of the text, where a font size of 1 is the
* default size.
* @param font
* - the font that this text should use.
* @param position
* - the position on the screen where the top left corner of the
* text should be rendered. The top left corner of the screen is
* (0, 0) and the bottom right is (1, 1).
* @param maxLineLength
* - basically the width of the virtual page in terms of screen
* width (1 is full screen width, 0.5 is half the width of the
* screen, etc.) Text cannot go off the edge of the page, so if
* the text is longer than this length it will go onto the next
* line. When text is centered it is centered into the middle of
* the line, based on this line length value.
* @param centered
* - whether the text should be centered or not.
*/
public GUIText(String text, float fontSize, FontType font, Vector2f position, float maxLineLength,
boolean centered) {
this.textString = text;
this.fontSize = fontSize;
this.font = font;
this.position = position;
this.lineMaxSize = maxLineLength;
this.centerText = centered;
| TextMaster.loadText(this);
|
Radseq/Mystic-Bastion | src/main/java/renderEngine/Loader.java | // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
| import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GLContext;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;
import engineTester.MainGameLoop;
import models.RawModel;
import textures.TextureData;
| package renderEngine;
/*
* Loading 3D models into memory
*/
public class Loader {
private List<Integer> vaos = new ArrayList<Integer>();
private List<Integer> vbos = new ArrayList<Integer>();
private List<Integer> textures = new ArrayList<Integer>();
public int loadToVAO(float[] positions, float[] textureCoords) {
int vaoID = createVAO();
storeDataInAttributeList(0, 2, positions);
storeDataInAttributeList(1, 2, textureCoords);
unbindVAO();
return vaoID;
}
| // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
// Path: src/main/java/renderEngine/Loader.java
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GLContext;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;
import engineTester.MainGameLoop;
import models.RawModel;
import textures.TextureData;
package renderEngine;
/*
* Loading 3D models into memory
*/
public class Loader {
private List<Integer> vaos = new ArrayList<Integer>();
private List<Integer> vbos = new ArrayList<Integer>();
private List<Integer> textures = new ArrayList<Integer>();
public int loadToVAO(float[] positions, float[] textureCoords) {
int vaoID = createVAO();
storeDataInAttributeList(0, 2, positions);
storeDataInAttributeList(1, 2, textureCoords);
unbindVAO();
return vaoID;
}
| public RawModel loadToVAO(float[] positions, float[] textureCoords, float[] normals, int[] indices) {
|
Radseq/Mystic-Bastion | src/main/java/renderEngine/Loader.java | // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
| import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GLContext;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;
import engineTester.MainGameLoop;
import models.RawModel;
import textures.TextureData;
| int offset) {
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL30.glBindVertexArray(vao);
GL20.glVertexAttribPointer(attribute, dataSize, GL11.GL_FLOAT, false, instancedDataLength * 4, offset * 4);
GL33.glVertexAttribDivisor(attribute, 1);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
}
public void updateVbo(int vbo, float[] data, FloatBuffer buffer) {
buffer.clear();
buffer.put(data);
buffer.flip();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer.capacity() * 4, GL15.GL_STREAM_DRAW);
GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, buffer);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
public RawModel loadToVAO(float[] positions, int dimensions) {
int vaoID = createVAO();
this.storeDataInAttributeList(0, dimensions, positions);
unbindVAO();
return new RawModel(vaoID, positions.length / dimensions);
}
public int loadTexture(String fileName) {
Texture texture = null;
try {
texture = TextureLoader.getTexture("PNG",
| // Path: src/main/java/engineTester/MainGameLoop.java
// public class MainGameLoop {
//
// private static World world = new World();
//
// public static FileManager fileManager;
//
// public static void main(String[] args) throws URISyntaxException, IOException {
// if (args.length == 0) {
// System.out.println("Please supply one of the following arguments");
// System.out.println("dev - Only for development use!");
// System.out.println("launch - For launching after using 'copy' argument");
// System.out.println("copy - For copying resources from jar to current dir");
// } else {
// if (args[0].equalsIgnoreCase("dev")) {
// fileManager = new FileManager(false);
// world.start();
// } else if (args[0].equalsIgnoreCase("copy")) {
// fileManager = new FileManager(false);
// fileManager.loadFromJar();
// } else if (args[0].equalsIgnoreCase("launch")) {
// fileManager = new FileManager(true);
// world.start();
// }
// }
// // world.stop();
//
// }
// }
//
// Path: src/main/java/models/RawModel.java
// public class RawModel {
//
// private int vaoID;
// private int vertexCount;
//
// public RawModel(int vaoID, int vertexCount) {
// this.vaoID = vaoID;
// this.vertexCount = vertexCount;
// }
//
// public int getVaoID() {
// return vaoID;
// }
//
// public int getVertexCount() {
// return vertexCount;
// }
//
// }
// Path: src/main/java/renderEngine/Loader.java
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GLContext;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;
import engineTester.MainGameLoop;
import models.RawModel;
import textures.TextureData;
int offset) {
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL30.glBindVertexArray(vao);
GL20.glVertexAttribPointer(attribute, dataSize, GL11.GL_FLOAT, false, instancedDataLength * 4, offset * 4);
GL33.glVertexAttribDivisor(attribute, 1);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
}
public void updateVbo(int vbo, float[] data, FloatBuffer buffer) {
buffer.clear();
buffer.put(data);
buffer.flip();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer.capacity() * 4, GL15.GL_STREAM_DRAW);
GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, buffer);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
public RawModel loadToVAO(float[] positions, int dimensions) {
int vaoID = createVAO();
this.storeDataInAttributeList(0, dimensions, positions);
unbindVAO();
return new RawModel(vaoID, positions.length / dimensions);
}
public int loadTexture(String fileName) {
Texture texture = null;
try {
texture = TextureLoader.getTexture("PNG",
| new FileInputStream(MainGameLoop.fileManager.getTextureFile(fileName)));
|
Radseq/Mystic-Bastion | src/main/java/renderEngine/DisplayManager.java | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
| import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.PixelFormat;
import engineTester.Settings; | package renderEngine;
public class DisplayManager {
private static long lastFrameTime;
private static float delta;
public final static String WINDOWNAME = "Mystic Bastion!";
// frames per second
static int fps; | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
// Path: src/main/java/renderEngine/DisplayManager.java
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.PixelFormat;
import engineTester.Settings;
package renderEngine;
public class DisplayManager {
private static long lastFrameTime;
private static float delta;
public final static String WINDOWNAME = "Mystic Bastion!";
// frames per second
static int fps; | static boolean SHOWFPS = Settings.SHOW_FPS; |
Radseq/Mystic-Bastion | src/main/java/particles/ParticleSystem.java | // Path: src/main/java/renderEngine/DisplayManager.java
// public class DisplayManager {
//
// private static long lastFrameTime;
// private static float delta;
// public final static String WINDOWNAME = "Mystic Bastion!";
//
// // frames per second
// static int fps;
// static boolean SHOWFPS = Settings.SHOW_FPS;
// /** last fps time */
// static long lastFPS;
// static int fpsCountRefreshRate = Settings.FPS_REFRESH_TIME;
//
// public static void createDisplay() {
// ContextAttribs attribs = new ContextAttribs(3, 3).withForwardCompatible(true).withProfileCore(true);
//
// try {
// //Display.setResizable(true); // whether our window is resizable
// Display.setDisplayMode(new DisplayMode(Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT));
// Display.setVSyncEnabled(Settings.VSYNC); // whether hardware VSync
// // is enabled
// Display.setFullscreen(Settings.FULL_SCREEN); // whether fullscreen
// // is
// // enabled
// if (Settings.ENABLE_ANTIALIASING) {
// Display.create(new PixelFormat().withDepthBits(24), attribs);
// System.out.println(GL11.glGetInteger(GL11.GL_DEPTH_BITS));
// GL11.glEnable(GL13.GL_MULTISAMPLE);
// } else {
// Display.create(new PixelFormat(), attribs);
// }
// Display.setTitle(WINDOWNAME);
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// GL11.glViewport(0, 0, Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT);
// lastFrameTime = getCurrentTime();
// lastFPS = lastFrameTime;
// }
//
// public static void updateDisplay() {
// Display.sync(Settings.FPS_CAP);
// Display.update();
// long currentFrameTime = getCurrentTime();
// delta = (currentFrameTime - lastFrameTime) / 1000f;
// lastFrameTime = currentFrameTime;
// if (SHOWFPS) {
// updateFPS(); // update FPS Counter
// }
// }
//
// public static float getFrameTimeSeconds() {
// return delta;
// }
//
// public static void closeDisplay() {
// Display.destroy();
// }
//
// private static long getCurrentTime() {
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// /**
// * Calculate the FPS
// */
// public static void updateFPS() {
// if (getCurrentTime() - lastFPS > fpsCountRefreshRate) {
// Display.setTitle(WINDOWNAME + " FPS: " + fps);
// fps = 0;
// lastFPS += 1000;
// }
// fps++;
// }
// }
| import java.util.Random;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import renderEngine.DisplayManager;
|
public void randomizeRotation() {
randomRotation = true;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setSpeedError(float error) {
this.speedError = error * averageSpeed;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setLifeError(float error) {
this.lifeError = error * averageLifeLength;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setScaleError(float error) {
this.scaleError = error * averageScale;
}
public void generateParticles(Vector3f systemCenter) {
| // Path: src/main/java/renderEngine/DisplayManager.java
// public class DisplayManager {
//
// private static long lastFrameTime;
// private static float delta;
// public final static String WINDOWNAME = "Mystic Bastion!";
//
// // frames per second
// static int fps;
// static boolean SHOWFPS = Settings.SHOW_FPS;
// /** last fps time */
// static long lastFPS;
// static int fpsCountRefreshRate = Settings.FPS_REFRESH_TIME;
//
// public static void createDisplay() {
// ContextAttribs attribs = new ContextAttribs(3, 3).withForwardCompatible(true).withProfileCore(true);
//
// try {
// //Display.setResizable(true); // whether our window is resizable
// Display.setDisplayMode(new DisplayMode(Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT));
// Display.setVSyncEnabled(Settings.VSYNC); // whether hardware VSync
// // is enabled
// Display.setFullscreen(Settings.FULL_SCREEN); // whether fullscreen
// // is
// // enabled
// if (Settings.ENABLE_ANTIALIASING) {
// Display.create(new PixelFormat().withDepthBits(24), attribs);
// System.out.println(GL11.glGetInteger(GL11.GL_DEPTH_BITS));
// GL11.glEnable(GL13.GL_MULTISAMPLE);
// } else {
// Display.create(new PixelFormat(), attribs);
// }
// Display.setTitle(WINDOWNAME);
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// GL11.glViewport(0, 0, Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT);
// lastFrameTime = getCurrentTime();
// lastFPS = lastFrameTime;
// }
//
// public static void updateDisplay() {
// Display.sync(Settings.FPS_CAP);
// Display.update();
// long currentFrameTime = getCurrentTime();
// delta = (currentFrameTime - lastFrameTime) / 1000f;
// lastFrameTime = currentFrameTime;
// if (SHOWFPS) {
// updateFPS(); // update FPS Counter
// }
// }
//
// public static float getFrameTimeSeconds() {
// return delta;
// }
//
// public static void closeDisplay() {
// Display.destroy();
// }
//
// private static long getCurrentTime() {
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// /**
// * Calculate the FPS
// */
// public static void updateFPS() {
// if (getCurrentTime() - lastFPS > fpsCountRefreshRate) {
// Display.setTitle(WINDOWNAME + " FPS: " + fps);
// fps = 0;
// lastFPS += 1000;
// }
// fps++;
// }
// }
// Path: src/main/java/particles/ParticleSystem.java
import java.util.Random;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import renderEngine.DisplayManager;
public void randomizeRotation() {
randomRotation = true;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setSpeedError(float error) {
this.speedError = error * averageSpeed;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setLifeError(float error) {
this.lifeError = error * averageLifeLength;
}
/**
* @param error
* - A number between 0 and 1, where 0 means no error margin.
*/
public void setScaleError(float error) {
this.scaleError = error * averageScale;
}
public void generateParticles(Vector3f systemCenter) {
| float delta = DisplayManager.getFrameTimeSeconds();
|
Radseq/Mystic-Bastion | src/main/java/shadows/ShadowFrameBuffer.java | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
| import java.nio.ByteBuffer;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;
import engineTester.Settings; | package shadows;
/**
* The frame buffer for the shadow pass. This class sets up the depth texture
* which can be rendered to during the shadow render pass, producing a shadow
* map.
*
* @author Karl
*
*/
public class ShadowFrameBuffer {
private final int WIDTH;
private final int HEIGHT;
private int fbo;
private int shadowMap;
/**
* Initialises the frame buffer and shadow map of a certain size.
*
* @param width
* - the width of the shadow map in pixels.
* @param height
* - the height of the shadow map in pixels.
*/
protected ShadowFrameBuffer(int width, int height) {
this.WIDTH = width;
this.HEIGHT = height;
initialiseFrameBuffer();
}
/**
* Deletes the frame buffer and shadow map texture when the game closes.
*/
protected void cleanUp() {
GL30.glDeleteFramebuffers(fbo);
GL11.glDeleteTextures(shadowMap);
}
/**
* Binds the frame buffer, setting it as the current render target.
*/
protected void bindFrameBuffer() {
bindFrameBuffer(fbo, WIDTH, HEIGHT);
}
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
* render target.
*/
protected void unbindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
// Path: src/main/java/shadows/ShadowFrameBuffer.java
import java.nio.ByteBuffer;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;
import engineTester.Settings;
package shadows;
/**
* The frame buffer for the shadow pass. This class sets up the depth texture
* which can be rendered to during the shadow render pass, producing a shadow
* map.
*
* @author Karl
*
*/
public class ShadowFrameBuffer {
private final int WIDTH;
private final int HEIGHT;
private int fbo;
private int shadowMap;
/**
* Initialises the frame buffer and shadow map of a certain size.
*
* @param width
* - the width of the shadow map in pixels.
* @param height
* - the height of the shadow map in pixels.
*/
protected ShadowFrameBuffer(int width, int height) {
this.WIDTH = width;
this.HEIGHT = height;
initialiseFrameBuffer();
}
/**
* Deletes the frame buffer and shadow map texture when the game closes.
*/
protected void cleanUp() {
GL30.glDeleteFramebuffers(fbo);
GL11.glDeleteTextures(shadowMap);
}
/**
* Binds the frame buffer, setting it as the current render target.
*/
protected void bindFrameBuffer() {
bindFrameBuffer(fbo, WIDTH, HEIGHT);
}
/**
* Unbinds the frame buffer, setting the default frame buffer as the current
* render target.
*/
protected void unbindFrameBuffer() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | GL11.glViewport(0, 0, Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT); |
Radseq/Mystic-Bastion | src/main/java/network/packets/PacketLogin.java | // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
| import network.GameClient;
| package network.packets;
public class PacketLogin extends Packet {
private String userName;
private float posX, posY, posZ;
private float scale;
public PacketLogin(byte[] data) {
super(00);
String[] dataArray = readData(data).split("@");
this.userName = dataArray[0];
this.posX = Float.parseFloat(dataArray[1]);
this.posY = Float.parseFloat(dataArray[2]);
this.posZ = Float.parseFloat(dataArray[3]);
this.scale = Float.parseFloat(dataArray[4]);
}
public PacketLogin(String username, float x, float y, float z, float scale) {
super(00);
this.userName = username;
this.posX = x;
this.posY = y;
this.posZ = z;
this.scale = scale;
}
@Override
public byte[] getData() {
return ("00" + this.userName + "@" + this.posX + "@" + this.posY + "@" + this.posZ + "@" + this.scale)
.getBytes();
}
@Override
| // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/network/packets/PacketLogin.java
import network.GameClient;
package network.packets;
public class PacketLogin extends Packet {
private String userName;
private float posX, posY, posZ;
private float scale;
public PacketLogin(byte[] data) {
super(00);
String[] dataArray = readData(data).split("@");
this.userName = dataArray[0];
this.posX = Float.parseFloat(dataArray[1]);
this.posY = Float.parseFloat(dataArray[2]);
this.posZ = Float.parseFloat(dataArray[3]);
this.scale = Float.parseFloat(dataArray[4]);
}
public PacketLogin(String username, float x, float y, float z, float scale) {
super(00);
this.userName = username;
this.posX = x;
this.posY = y;
this.posZ = z;
this.scale = scale;
}
@Override
public byte[] getData() {
return ("00" + this.userName + "@" + this.posX + "@" + this.posY + "@" + this.posZ + "@" + this.scale)
.getBytes();
}
@Override
| public void writeData(GameClient client) {
|
Radseq/Mystic-Bastion | src/main/java/network/packets/Packet.java | // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
| import network.GameClient;
| }
public byte packetId;
public Packet(int packetId) {
this.packetId = (byte) packetId;
}
public static PacketTypes lookUpPacket(int id) {
for (PacketTypes packetTypes : PacketTypes.values()) {
if (packetTypes.getId() == id) {
return packetTypes;
}
}
return PacketTypes.INVALID;
}
public String readData(byte[] data) {
String message = new String(data).trim();
return message.substring(2);
}
public static PacketTypes lookUpPacket(String packetId) {
try {
return lookUpPacket(Integer.parseInt(packetId));
} catch (NumberFormatException e) {
return PacketTypes.INVALID;
}
}
| // Path: src/main/java/network/GameClient.java
// public class GameClient extends Thread {
//
// private InetAddress ipAddress;
// private DatagramSocket socket;
// private World world;
// private int port;
//
// public GameClient(World world, String ipAddress, int port) {
// this.world = world;
// this.port = port;
// try {
// this.socket = new DatagramSocket();
// this.ipAddress = InetAddress.getByName(ipAddress);
// } catch (SocketException e) {
// e.printStackTrace();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
//
// public void run() {
// while (true) {
// byte[] data = new byte[1024];
// DatagramPacket packet = new DatagramPacket(data, data.length);
// try {
// socket.receive(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
// }
// }
//
// private void parsePacket(byte[] data, InetAddress address, int port) {
// String message = new String(data).trim();
// PacketTypes type = Packet.lookUpPacket(message.substring(0, 2));
// Packet packet = null;
// switch (type) {
// default:
// case INVALID:
// break;
// case LOGIN:
// packet = new PacketLogin(data);
// handleLogin((PacketLogin) packet, address, port);
// break;
// case DISCONNECT:
// packet = new PacketDisconnect(data);
// System.out.println("[" + address.getHostAddress() + ":" + port + "] "
// + ((PacketDisconnect) packet).getUsername() + " has left the world...");
// world.level.removeMultiPlayer(((PacketDisconnect) packet).getUsername());
// break;
// case MOVE:
// packet = new PacketMove(data);
// handleMove((PacketMove) packet);
// }
// }
//
// private void handleLogin(PacketLogin packet, InetAddress address, int port) {
// System.out.println(
// "[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername() + " has joined the game...");
//
// // TexturedModel stanfordBunny = world.stanfordBunny;
// MultiPlayer player = new MultiPlayer(world.stanfordBunny, packet.getX(), packet.getY(), packet.getZ(), 0, 0, 0,
// packet.getScale(), packet.getUsername(), address, port);
// world.level.addEntity(player);
// }
//
// private void handleMove(PacketMove packet) {
// this.world.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getZ(),
// packet.getAngle());
// }
//
// public void sendData(byte[] data) {
// DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
// try {
// socket.send(packet);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/network/packets/Packet.java
import network.GameClient;
}
public byte packetId;
public Packet(int packetId) {
this.packetId = (byte) packetId;
}
public static PacketTypes lookUpPacket(int id) {
for (PacketTypes packetTypes : PacketTypes.values()) {
if (packetTypes.getId() == id) {
return packetTypes;
}
}
return PacketTypes.INVALID;
}
public String readData(byte[] data) {
String message = new String(data).trim();
return message.substring(2);
}
public static PacketTypes lookUpPacket(String packetId) {
try {
return lookUpPacket(Integer.parseInt(packetId));
} catch (NumberFormatException e) {
return PacketTypes.INVALID;
}
}
| public abstract void writeData(GameClient client);
|
Radseq/Mystic-Bastion | src/main/java/water/WaterFrameBuffers.java | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
| import java.nio.ByteBuffer;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;
import engineTester.Settings; | private int refractionFrameBuffer;
private int refractionTexture;
private int refractionDepthTexture;
public WaterFrameBuffers() {// call when loading the game
initialiseReflectionFrameBuffer();
initialiseRefractionFrameBuffer();
}
public void cleanUp() {// call when closing the game
GL30.glDeleteFramebuffers(reflectionFrameBuffer);
GL11.glDeleteTextures(reflectionTexture);
GL30.glDeleteRenderbuffers(reflectionDepthBuffer);
GL30.glDeleteFramebuffers(refractionFrameBuffer);
GL11.glDeleteTextures(refractionTexture);
GL11.glDeleteTextures(refractionDepthTexture);
}
public void bindReflectionFrameBuffer() {// call before rendering to this
// FBO
bindFrameBuffer(reflectionFrameBuffer, REFLECTION_WIDTH, REFLECTION_HEIGHT);
}
public void bindRefractionFrameBuffer() {// call before rendering to this
// FBO
bindFrameBuffer(refractionFrameBuffer, REFRACTION_WIDTH, REFRACTION_HEIGHT);
}
public void unbindCurrentFrameBuffer() {// call after rendering to texture
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
// Path: src/main/java/water/WaterFrameBuffers.java
import java.nio.ByteBuffer;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL32;
import engineTester.Settings;
private int refractionFrameBuffer;
private int refractionTexture;
private int refractionDepthTexture;
public WaterFrameBuffers() {// call when loading the game
initialiseReflectionFrameBuffer();
initialiseRefractionFrameBuffer();
}
public void cleanUp() {// call when closing the game
GL30.glDeleteFramebuffers(reflectionFrameBuffer);
GL11.glDeleteTextures(reflectionTexture);
GL30.glDeleteRenderbuffers(reflectionDepthBuffer);
GL30.glDeleteFramebuffers(refractionFrameBuffer);
GL11.glDeleteTextures(refractionTexture);
GL11.glDeleteTextures(refractionDepthTexture);
}
public void bindReflectionFrameBuffer() {// call before rendering to this
// FBO
bindFrameBuffer(reflectionFrameBuffer, REFLECTION_WIDTH, REFLECTION_HEIGHT);
}
public void bindRefractionFrameBuffer() {// call before rendering to this
// FBO
bindFrameBuffer(refractionFrameBuffer, REFRACTION_WIDTH, REFRACTION_HEIGHT);
}
public void unbindCurrentFrameBuffer() {// call after rendering to texture
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); | GL11.glViewport(0, 0, Settings.WINDOW_WIDTH, Settings.WINDOW_HEIGHT); |
Radseq/Mystic-Bastion | src/main/java/fontMeshCreator/MetaFile.java | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.lwjgl.opengl.Display;
import engineTester.Settings; | package fontMeshCreator;
/**
* Provides functionality for getting the values from a font file.
*
* @author Karl
*
*/
public class MetaFile {
private static final int PAD_TOP = 0;
private static final int PAD_LEFT = 1;
private static final int PAD_BOTTOM = 2;
private static final int PAD_RIGHT = 3;
private static final int DESIRED_PADDING = 3; // 3
private static final String SPLITTER = " ";
private static final String NUMBER_SEPARATOR = ",";
private double aspectRatio;
private double verticalPerPixelSize;
private double horizontalPerPixelSize;
private double spaceWidth;
private int[] padding;
private int paddingWidth;
private int paddingHeight;
private Map<Integer, Character> metaData = new HashMap<Integer, Character>();
private BufferedReader reader;
private Map<String, String> values = new HashMap<String, String>();
/**
* Opens a font file in preparation for reading.
*
* @param file
* - the font file.
*/
protected MetaFile(File file) { | // Path: src/main/java/engineTester/Settings.java
// public class Settings {
// // Game Settings
// public static int WINDOW_WIDTH = 800;
// public static int WINDOW_HEIGHT = 600;
//
// public static int FPS_CAP = 30;
// public static boolean SHOW_FPS = true;
// public static int FPS_REFRESH_TIME = 1000;
//
// public static int SHADOW_RENDER_DISTANCE = 100;
// public static int SHADOW_MAP_SIZE = 4096;
//
// public static int MAX_LIGHTS = 4; // do not change
//
// public static boolean FULL_SCREEN = false;
// public static boolean VSYNC = false;
//
// public static boolean ENABLE_ANTIALIASING = true;
//
// public static final String gameSettingPatch = FileManager.releasePath + "/config/settings.cfg";
//
// public static void loadSettings() {
//
// File f = new File(gameSettingPatch);
// if (f.exists()) {
// readFromSettingsFile();
// } else {
// writeToSettingsFile();
// }
// }
//
// public static void readFromSettingsFile() {
// Properties properties = new Properties();
// InputStream input = null;
//
// try {
// input = new FileInputStream(gameSettingPatch);
// properties.load(input);
//
// WINDOW_WIDTH = Integer.parseInt(properties.getProperty("width"));
// WINDOW_HEIGHT = Integer.parseInt(properties.getProperty("height"));
// FPS_CAP = Integer.parseInt(properties.getProperty("fpsCap"));
// SHOW_FPS = Boolean.parseBoolean(properties.getProperty("showFPS"));
// FPS_REFRESH_TIME = Integer.parseInt(properties.getProperty("fpsRefreshTime"));
// SHADOW_RENDER_DISTANCE = Integer.parseInt(properties.getProperty("shadowRenderDistance"));
// SHADOW_MAP_SIZE = Integer.parseInt(properties.getProperty("shadowMapSize"));
// FULL_SCREEN = Boolean.parseBoolean(properties.getProperty("fullScreen"));
// VSYNC = Boolean.parseBoolean(properties.getProperty("vsync"));
// ENABLE_ANTIALIASING = Boolean.parseBoolean(properties.getProperty("antialiasing"));
// input.close();
//
// } catch (IOException ex) {
// ex.printStackTrace();
// }
// }
//
// public static void writeToSettingsFile() {
// Properties properties = new Properties();
// OutputStream output = null;
//
// try {
// new File(FileManager.releasePath + "/config/").mkdir();
// output = new FileOutputStream(gameSettingPatch);
// output.write(DisplayManager.WINDOWNAME.getBytes(Charset.forName("UTF-8")));
//
// properties.setProperty("width", String.valueOf(WINDOW_WIDTH));
// properties.setProperty("height", String.valueOf(WINDOW_HEIGHT));
// properties.setProperty("fpsCap", String.valueOf(FPS_CAP));
// properties.setProperty("showFPS", String.valueOf(SHOW_FPS));
// properties.setProperty("fpsRefreshTime", String.valueOf(FPS_REFRESH_TIME));
// properties.setProperty("shadowRenderDistance", String.valueOf(SHADOW_RENDER_DISTANCE));
// properties.setProperty("shadowMapSize", String.valueOf(SHADOW_MAP_SIZE));
// properties.setProperty("fullScreen", String.valueOf(FULL_SCREEN));
// properties.setProperty("vsync", String.valueOf(VSYNC));
// properties.setProperty("antialiasing", String.valueOf(ENABLE_ANTIALIASING));
//
// // root folder
// properties.store(output, "");
// output.close();
// } catch (IOException io) {
// io.printStackTrace();
// }
// }
// }
// Path: src/main/java/fontMeshCreator/MetaFile.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.lwjgl.opengl.Display;
import engineTester.Settings;
package fontMeshCreator;
/**
* Provides functionality for getting the values from a font file.
*
* @author Karl
*
*/
public class MetaFile {
private static final int PAD_TOP = 0;
private static final int PAD_LEFT = 1;
private static final int PAD_BOTTOM = 2;
private static final int PAD_RIGHT = 3;
private static final int DESIRED_PADDING = 3; // 3
private static final String SPLITTER = " ";
private static final String NUMBER_SEPARATOR = ",";
private double aspectRatio;
private double verticalPerPixelSize;
private double horizontalPerPixelSize;
private double spaceWidth;
private int[] padding;
private int paddingWidth;
private int paddingHeight;
private Map<Integer, Character> metaData = new HashMap<Integer, Character>();
private BufferedReader reader;
private Map<String, String> values = new HashMap<String, String>();
/**
* Opens a font file in preparation for reading.
*
* @param file
* - the font file.
*/
protected MetaFile(File file) { | this.aspectRatio = (double) Settings.WINDOW_WIDTH / (double) Settings.WINDOW_HEIGHT; |
maciejwalkowiak/java-plist-serializer | src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
| import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*; | assertThat(plistSerializer.serialize(null)).isEqualTo("");
}
@Test
public void testStaticFieldSerialization() {
//given
ClassWithStaticFields classWithStaticFields = new ClassWithStaticFields();
//when
String result = plistSerializer.serialize(classWithStaticFields);
//then
assertThat(result).isEqualTo("<dict><key>serializableField</key><integer>1</integer></dict>");
}
@Test
public void testAnnotations() {
//given
ClassWithAnnotations classWithAnnotations = new ClassWithAnnotations();
//when
String xml = plistSerializer.serialize(classWithAnnotations);
//then
assertThat(xml).isEqualTo("<dict><key>trick</key><string>i am renamed</string></dict>");
}
@Test
public void testPlistRenameWithFollowingStrategy() {
//given | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
// Path: src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*;
assertThat(plistSerializer.serialize(null)).isEqualTo("");
}
@Test
public void testStaticFieldSerialization() {
//given
ClassWithStaticFields classWithStaticFields = new ClassWithStaticFields();
//when
String result = plistSerializer.serialize(classWithStaticFields);
//then
assertThat(result).isEqualTo("<dict><key>serializableField</key><integer>1</integer></dict>");
}
@Test
public void testAnnotations() {
//given
ClassWithAnnotations classWithAnnotations = new ClassWithAnnotations();
//when
String xml = plistSerializer.serialize(classWithAnnotations);
//then
assertThat(xml).isEqualTo("<dict><key>trick</key><string>i am renamed</string></dict>");
}
@Test
public void testPlistRenameWithFollowingStrategy() {
//given | PlistSerializerImpl plistSerializer = new PlistSerializerImpl(new UppercaseNamingStrategy()); |
maciejwalkowiak/java-plist-serializer | src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
| import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*; | @Test
public void testFieldSerializationWhenNull() {
//given
Comment comment = new Comment(null, "content");
//when
String xml = plistSerializer.serialize(comment);
//then
assertThat(xml).isEqualTo("<dict><key>content</key><string>content</string></dict>");
}
@Test
public void testToXML() {
//given
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
String footer = "</plist>";
String testObject= "testObject";
//when
String xml = plistSerializer.toXmlPlist(testObject);
//then
assertThat(xml).startsWith(header).endsWith(footer);
}
@Test
public void testAdditionalHandler() {
//given | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
// Path: src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*;
@Test
public void testFieldSerializationWhenNull() {
//given
Comment comment = new Comment(null, "content");
//when
String xml = plistSerializer.serialize(comment);
//then
assertThat(xml).isEqualTo("<dict><key>content</key><string>content</string></dict>");
}
@Test
public void testToXML() {
//given
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
String footer = "</plist>";
String testObject= "testObject";
//when
String xml = plistSerializer.toXmlPlist(testObject);
//then
assertThat(xml).startsWith(header).endsWith(footer);
}
@Test
public void testAdditionalHandler() {
//given | Handler bigDecimalHandler = new BigDecimalHandler(); |
maciejwalkowiak/java-plist-serializer | src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
| import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*; | }
@Test
public void testDoubleSerializationHandler() {
//given
Double object = 4.55d;
//when
String xml = plistSerializer.serialize(object);
//then
assertThat(xml).isEqualTo("<real>4.55</real>");
}
@Test
public void testInheritedFieldsSerialization() {
//given
FooChild object = new FooChild("test1", "test2");
//when
String xml = plistSerializer.serialize(object);
//then
assertThat(xml).isEqualTo("<dict><key>bar</key><string>test2</string><key>foo</key><string>test1</string></dict>");
}
@Test
public void testPlistDataSerializationHandler() {
//given
byte[] data = "test".getBytes(); | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/UppercaseNamingStrategy.java
// public class UppercaseNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return addUnderscores(toConvert).toUpperCase();
// }
//
// protected static String addUnderscores(String name) {
// StringBuffer buf = new StringBuffer(name.replace('.', '_'));
// for (int i = 1; i < buf.length() - 1; i++) {
// if (
// Character.isLowerCase(buf.charAt(i - 1)) &&
// Character.isUpperCase(buf.charAt(i)) &&
// Character.isLowerCase(buf.charAt(i + 1))
// ) {
// buf.insert(i++, '_');
// }
// }
// return buf.toString().toLowerCase();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
// Path: src/test/java/pl/maciejwalkowiak/plist/PlistSerializerImplTest.java
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.strategy.UppercaseNamingStrategy;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
import java.math.BigDecimal;
import java.util.*;
}
@Test
public void testDoubleSerializationHandler() {
//given
Double object = 4.55d;
//when
String xml = plistSerializer.serialize(object);
//then
assertThat(xml).isEqualTo("<real>4.55</real>");
}
@Test
public void testInheritedFieldsSerialization() {
//given
FooChild object = new FooChild("test1", "test2");
//when
String xml = plistSerializer.serialize(object);
//then
assertThat(xml).isEqualTo("<dict><key>bar</key><string>test2</string><key>foo</key><string>test1</string></dict>");
}
@Test
public void testPlistDataSerializationHandler() {
//given
byte[] data = "test".getBytes(); | PlistData object = new PlistData(data); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/spring/PlistHttpMessageConverter.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializer.java
// public interface PlistSerializer {
// static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
// static final String FOOTER = "</plist>";
//
// /**
// * Serializes object to plist and creates valid XML by wrapping it around XML header,
// * plist DOCTYPE and <plist> XML tag.
// *
// * @param objectToConvert object to serialize
// * @return a String containing valid XML
// */
// String toXmlPlist(Object objectToConvert);
//
// /**
// * Serializes object into plist XML
// *
// * @param objectToConvert object to serialize
// * @return a String containing XML representation without XML header, DOCTYPE
// */
// String serialize(Object objectToConvert);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
| import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import pl.maciejwalkowiak.plist.PlistSerializer; | /*
* Copyright (c) 2014 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
public class PlistHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
| // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializer.java
// public interface PlistSerializer {
// static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
// static final String FOOTER = "</plist>";
//
// /**
// * Serializes object to plist and creates valid XML by wrapping it around XML header,
// * plist DOCTYPE and <plist> XML tag.
// *
// * @param objectToConvert object to serialize
// * @return a String containing valid XML
// */
// String toXmlPlist(Object objectToConvert);
//
// /**
// * Serializes object into plist XML
// *
// * @param objectToConvert object to serialize
// * @return a String containing XML representation without XML header, DOCTYPE
// */
// String serialize(Object objectToConvert);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/spring/PlistHttpMessageConverter.java
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import pl.maciejwalkowiak.plist.PlistSerializer;
/*
* Copyright (c) 2014 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
public class PlistHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
| private PlistSerializer plistSerializer; |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/spring/PlistHttpMessageConverter.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializer.java
// public interface PlistSerializer {
// static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
// static final String FOOTER = "</plist>";
//
// /**
// * Serializes object to plist and creates valid XML by wrapping it around XML header,
// * plist DOCTYPE and <plist> XML tag.
// *
// * @param objectToConvert object to serialize
// * @return a String containing valid XML
// */
// String toXmlPlist(Object objectToConvert);
//
// /**
// * Serializes object into plist XML
// *
// * @param objectToConvert object to serialize
// * @return a String containing XML representation without XML header, DOCTYPE
// */
// String serialize(Object objectToConvert);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
| import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import pl.maciejwalkowiak.plist.PlistSerializer; | /*
* Copyright (c) 2014 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
public class PlistHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private PlistSerializer plistSerializer;
private boolean addHeader;
/**
* Construct a new {@code PlistHttpMessageConverter}.
*/
public PlistHttpMessageConverter(boolean addHeader) {
super(new MediaType("application", "x-plist", DEFAULT_CHARSET),
new MediaType("application", "x-apple-aspen-mdm-checkin", DEFAULT_CHARSET));
this.addHeader = addHeader; | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializer.java
// public interface PlistSerializer {
// static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\">";
// static final String FOOTER = "</plist>";
//
// /**
// * Serializes object to plist and creates valid XML by wrapping it around XML header,
// * plist DOCTYPE and <plist> XML tag.
// *
// * @param objectToConvert object to serialize
// * @return a String containing valid XML
// */
// String toXmlPlist(Object objectToConvert);
//
// /**
// * Serializes object into plist XML
// *
// * @param objectToConvert object to serialize
// * @return a String containing XML representation without XML header, DOCTYPE
// */
// String serialize(Object objectToConvert);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/spring/PlistHttpMessageConverter.java
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import pl.maciejwalkowiak.plist.PlistSerializer;
/*
* Copyright (c) 2014 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
public class PlistHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private PlistSerializer plistSerializer;
private boolean addHeader;
/**
* Construct a new {@code PlistHttpMessageConverter}.
*/
public PlistHttpMessageConverter(boolean addHeader) {
super(new MediaType("application", "x-plist", DEFAULT_CHARSET),
new MediaType("application", "x-apple-aspen-mdm-checkin", DEFAULT_CHARSET));
this.addHeader = addHeader; | plistSerializer = new PlistSerializerImpl(); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/handler/StringHandler.java | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
| import org.apache.commons.lang3.StringEscapeUtils;
import pl.maciejwalkowiak.plist.XMLHelper; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
* @author Nadeem Khan
*/
public class StringHandler implements Handler {
public boolean supports(Object object) {
return object instanceof String;
}
@Override
public String handle(Object object) { | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/StringHandler.java
import org.apache.commons.lang3.StringEscapeUtils;
import pl.maciejwalkowiak.plist.XMLHelper;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
* @author Nadeem Khan
*/
public class StringHandler implements Handler {
public boolean supports(Object object) {
return object instanceof String;
}
@Override
public String handle(Object object) { | return XMLHelper.wrap(StringEscapeUtils.escapeXml((String) object)).with("string"); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/BasicObjectSerializer.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
| import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.handler.PlistSerializationException; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* @author Maciej Walkowiak
*/
public class BasicObjectSerializer {
private HandlerWrapper handlerWrapper;
public BasicObjectSerializer(HandlerWrapper handlerWrapper) {
this.handlerWrapper = handlerWrapper;
}
/**
* Serializes object with type: Integer, String, Boolean, Date, Map, Collection
*
* @param object - object to serialize
* @return - serialized object plist without key
*/
public StringBuilder serializeBasicObject(Object object) {
StringBuilder result = new StringBuilder();
try { | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/BasicObjectSerializer.java
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* @author Maciej Walkowiak
*/
public class BasicObjectSerializer {
private HandlerWrapper handlerWrapper;
public BasicObjectSerializer(HandlerWrapper handlerWrapper) {
this.handlerWrapper = handlerWrapper;
}
/**
* Serializes object with type: Integer, String, Boolean, Date, Map, Collection
*
* @param object - object to serialize
* @return - serialized object plist without key
*/
public StringBuilder serializeBasicObject(Object object) {
StringBuilder result = new StringBuilder();
try { | Handler handler = handlerWrapper.getHandlerForObject(object); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/BasicObjectSerializer.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
| import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.handler.PlistSerializationException; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* @author Maciej Walkowiak
*/
public class BasicObjectSerializer {
private HandlerWrapper handlerWrapper;
public BasicObjectSerializer(HandlerWrapper handlerWrapper) {
this.handlerWrapper = handlerWrapper;
}
/**
* Serializes object with type: Integer, String, Boolean, Date, Map, Collection
*
* @param object - object to serialize
* @return - serialized object plist without key
*/
public StringBuilder serializeBasicObject(Object object) {
StringBuilder result = new StringBuilder();
try {
Handler handler = handlerWrapper.getHandlerForObject(object);
result.append(handler.handle(object)); | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/BasicObjectSerializer.java
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* @author Maciej Walkowiak
*/
public class BasicObjectSerializer {
private HandlerWrapper handlerWrapper;
public BasicObjectSerializer(HandlerWrapper handlerWrapper) {
this.handlerWrapper = handlerWrapper;
}
/**
* Serializes object with type: Integer, String, Boolean, Date, Map, Collection
*
* @param object - object to serialize
* @return - serialized object plist without key
*/
public StringBuilder serializeBasicObject(Object object) {
StringBuilder result = new StringBuilder();
try {
Handler handler = handlerWrapper.getHandlerForObject(object);
result.append(handler.handle(object)); | } catch (HandlerNotFoundException e) { |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/handler/CollectionHandler.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
| import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.XMLHelper;
import java.util.Collection; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
*/
public class CollectionHandler extends AbstractHandler {
public CollectionHandler(PlistSerializerImpl plistSerializer) {
super(plistSerializer);
}
public boolean supports(Object object) {
return object instanceof Collection || isArray(object);
}
public String doHandle(Object object) {
StringBuilder result = new StringBuilder();
Collection col = (Collection) object;
for (Object o: col) {
result.append(plistSerializer.serialize(o));
}
| // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/CollectionHandler.java
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.XMLHelper;
import java.util.Collection;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
*/
public class CollectionHandler extends AbstractHandler {
public CollectionHandler(PlistSerializerImpl plistSerializer) {
super(plistSerializer);
}
public boolean supports(Object object) {
return object instanceof Collection || isArray(object);
}
public String doHandle(Object object) {
StringBuilder result = new StringBuilder();
Collection col = (Collection) object;
for (Object o: col) {
result.append(plistSerializer.serialize(o));
}
| return XMLHelper.wrap(result).with("array"); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/handler/DateHandler.java | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
| import pl.maciejwalkowiak.plist.XMLHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
*/
public class DateHandler implements Handler {
private SimpleDateFormat dateFormat;
public DateHandler() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public boolean supports(Object object) {
return object instanceof Date;
}
public String handle(Object object) { | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/DateHandler.java
import pl.maciejwalkowiak.plist.XMLHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Maciej Walkowiak
*/
public class DateHandler implements Handler {
private SimpleDateFormat dateFormat;
public DateHandler() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public boolean supports(Object object) {
return object instanceof Date;
}
public String handle(Object object) { | return XMLHelper.wrap(dateFormat.format(object)).with("date"); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/FieldSerializer.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
| import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import pl.maciejwalkowiak.plist.annotation.PlistAlias;
import pl.maciejwalkowiak.plist.annotation.PlistIgnore;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper; | return XMLHelper.wrap(result).with("dict");
}
private String serializeField(Object o, Field field) {
String result = "";
int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
ReflectionUtils.makeAccessible(field);
if (!field.isAnnotationPresent(PlistIgnore.class)) {
result = processField(field, o).toString();
} else {
logger.debug("field {} is ignored", field.getName());
}
}
return result;
}
private StringBuilder processField(Field field, Object object) {
StringBuilder result = new StringBuilder();
Object fieldValue = getFieldValue(field, object);
if (fieldValue != null) {
result.append(createKey(field));
try { | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/FieldSerializer.java
import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import pl.maciejwalkowiak.plist.annotation.PlistAlias;
import pl.maciejwalkowiak.plist.annotation.PlistIgnore;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
return XMLHelper.wrap(result).with("dict");
}
private String serializeField(Object o, Field field) {
String result = "";
int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
ReflectionUtils.makeAccessible(field);
if (!field.isAnnotationPresent(PlistIgnore.class)) {
result = processField(field, o).toString();
} else {
logger.debug("field {} is ignored", field.getName());
}
}
return result;
}
private StringBuilder processField(Field field, Object object) {
StringBuilder result = new StringBuilder();
Object fieldValue = getFieldValue(field, object);
if (fieldValue != null) {
result.append(createKey(field));
try { | Handler handler = handlerWrapper.getHandlerForObject(fieldValue); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/FieldSerializer.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
| import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import pl.maciejwalkowiak.plist.annotation.PlistAlias;
import pl.maciejwalkowiak.plist.annotation.PlistIgnore;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper; | private String serializeField(Object o, Field field) {
String result = "";
int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
ReflectionUtils.makeAccessible(field);
if (!field.isAnnotationPresent(PlistIgnore.class)) {
result = processField(field, o).toString();
} else {
logger.debug("field {} is ignored", field.getName());
}
}
return result;
}
private StringBuilder processField(Field field, Object object) {
StringBuilder result = new StringBuilder();
Object fieldValue = getFieldValue(field, object);
if (fieldValue != null) {
result.append(createKey(field));
try {
Handler handler = handlerWrapper.getHandlerForObject(fieldValue);
result.append(handler.handle(fieldValue)); | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/HandlerNotFoundException.java
// public class HandlerNotFoundException extends Exception {
// public HandlerNotFoundException(String s) {
// super(s);
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/FieldSerializer.java
import pl.maciejwalkowiak.plist.handler.PlistSerializationException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import pl.maciejwalkowiak.plist.annotation.PlistAlias;
import pl.maciejwalkowiak.plist.annotation.PlistIgnore;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerNotFoundException;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
private String serializeField(Object o, Field field) {
String result = "";
int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
ReflectionUtils.makeAccessible(field);
if (!field.isAnnotationPresent(PlistIgnore.class)) {
result = processField(field, o).toString();
} else {
logger.debug("field {} is ignored", field.getName());
}
}
return result;
}
private StringBuilder processField(Field field, Object object) {
StringBuilder result = new StringBuilder();
Object fieldValue = getFieldValue(field, object);
if (fieldValue != null) {
result.append(createKey(field));
try {
Handler handler = handlerWrapper.getHandlerForObject(fieldValue);
result.append(handler.handle(fieldValue)); | } catch (HandlerNotFoundException e) { |
maciejwalkowiak/java-plist-serializer | src/test/java/pl/maciejwalkowiak/plist/handler/MapHandlerTest.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
| import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyInt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
@RunWith(MockitoJUnitRunner.class)
public class MapHandlerTest {
@InjectMocks
private MapHandler mapHandler;
@Mock | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
// Path: src/test/java/pl/maciejwalkowiak/plist/handler/MapHandlerTest.java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyInt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
@RunWith(MockitoJUnitRunner.class)
public class MapHandlerTest {
@InjectMocks
private MapHandler mapHandler;
@Mock | private PlistSerializerImpl plistSerializer; |
maciejwalkowiak/java-plist-serializer | src/test/java/pl/maciejwalkowiak/plist/handler/MapHandlerTest.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
| import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyInt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
@RunWith(MockitoJUnitRunner.class)
public class MapHandlerTest {
@InjectMocks
private MapHandler mapHandler;
@Mock
private PlistSerializerImpl plistSerializer;
@Test
public void testMapSerialization() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);
given(plistSerializer.serialize(anyInt())).willReturn("<integer>1</integer>"); | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
// Path: src/test/java/pl/maciejwalkowiak/plist/handler/MapHandlerTest.java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyInt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
@RunWith(MockitoJUnitRunner.class)
public class MapHandlerTest {
@InjectMocks
private MapHandler mapHandler;
@Mock
private PlistSerializerImpl plistSerializer;
@Test
public void testMapSerialization() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);
given(plistSerializer.serialize(anyInt())).willReturn("<integer>1</integer>"); | given(plistSerializer.getNamingStrategy()).willReturn(new DefaultNamingStrategy()); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/spring/PlistView.java | // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
| import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
/**
* @author Maciej Walkowiak
*/
public class PlistView extends AbstractView {
private static final String ENCODING = "UTF-8";
| // Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
// public class PlistSerializerImpl implements PlistSerializer {
// private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
//
// private HandlerWrapper handlerWrapper;
// private BasicObjectSerializer basicObjectSerializer;
// private FieldSerializer fieldSerializer;
// private NamingStrategy namingStrategy = new DefaultNamingStrategy();
//
// public PlistSerializerImpl(NamingStrategy namingStrategy) {
// this();
// this.namingStrategy = namingStrategy;
// }
//
// public PlistSerializerImpl() {
// this.handlerWrapper = new HandlerWrapper(this);
// this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
// this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
// }
//
// public String toXmlPlist(Object objectToConvert) {
// StringBuilder result = new StringBuilder(HEADER);
//
// result.append(serialize(objectToConvert));
//
// result.append(FOOTER);
//
// return result.toString();
// }
//
// public String serialize(Object objectToConvert) {
// StringBuilder result = new StringBuilder();
//
// logger.debug("converting object = {}", objectToConvert);
//
// if (objectToConvert != null) {
// if (handlerWrapper.isSupported(objectToConvert)) {
// result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
// } else {
// result.append(fieldSerializer.serializeFields(objectToConvert));
// }
// }
//
// return result.toString();
// }
//
// public void setAdditionalHandlers(List<Handler> additionalHandlers) {
// handlerWrapper.addAdditionalHandlers(additionalHandlers);
// }
//
// public NamingStrategy getNamingStrategy() {
// return namingStrategy;
// }
//
// HandlerWrapper getHandlerWrapper() {
// return handlerWrapper;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/spring/PlistView.java
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.spring;
/**
* @author Maciej Walkowiak
*/
public class PlistView extends AbstractView {
private static final String ENCODING = "UTF-8";
| private PlistSerializerImpl plistSerializer; |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/handler/DataHandler.java | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
| import org.apache.commons.codec.binary.Base64;
import pl.maciejwalkowiak.plist.XMLHelper;
import pl.maciejwalkowiak.plist.plisttypes.PlistData; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Victor Ronin
*/
public class DataHandler implements Handler {
public boolean supports(Object object) { | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/DataHandler.java
import org.apache.commons.codec.binary.Base64;
import pl.maciejwalkowiak.plist.XMLHelper;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Victor Ronin
*/
public class DataHandler implements Handler {
public boolean supports(Object object) { | return object instanceof PlistData; |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/handler/DataHandler.java | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
| import org.apache.commons.codec.binary.Base64;
import pl.maciejwalkowiak.plist.XMLHelper;
import pl.maciejwalkowiak.plist.plisttypes.PlistData; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Victor Ronin
*/
public class DataHandler implements Handler {
public boolean supports(Object object) {
return object instanceof PlistData;
}
public String handle(Object object) { | // Path: src/main/java/pl/maciejwalkowiak/plist/XMLHelper.java
// public class XMLHelper {
// private XMLHelper() {}
//
// private Object objectToWrap;
//
// public static XMLHelper wrap(Object object) {
// if (object == null) {
// throw new IllegalArgumentException("object to wrap cannot be null");
// }
//
// XMLHelper xmlHelper = new XMLHelper();
// xmlHelper.objectToWrap = object;
//
// return xmlHelper;
// }
//
// public String with(String wrappedWith) {
// if (wrappedWith == null || wrappedWith.isEmpty()) {
// throw new IllegalArgumentException("wrappedWith cannot be null or empty");
// }
//
// StringBuilder result = new StringBuilder();
//
// result.append("<").append(wrappedWith).append(">").append(this.objectToWrap).append("</").append(wrappedWith).append(">");
//
// return result.toString();
// }
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/plisttypes/PlistData.java
// public class PlistData {
// private byte[] data;
//
// public PlistData(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/handler/DataHandler.java
import org.apache.commons.codec.binary.Base64;
import pl.maciejwalkowiak.plist.XMLHelper;
import pl.maciejwalkowiak.plist.plisttypes.PlistData;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist.handler;
/**
* @author Victor Ronin
*/
public class DataHandler implements Handler {
public boolean supports(Object object) {
return object instanceof PlistData;
}
public String handle(Object object) { | return XMLHelper.wrap(new String(Base64.encodeBase64(((PlistData) object).getData()))).with("data"); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
import java.util.List; | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* Implementation of {@link PlistSerializer} capable of serializing objects containing elements:
* <ul>
* <li>basic types: {@link Integer}, {@link String}, {@link Boolean}, {@link Double}, {@link Short},
* {@link Long}, {@link Byte} as well as theirs primitive representation</li>
* <li>{@link java.util.Collection}</li>
* <li>{@link java.util.Map}</li>
* </ul>
*
* Goes through all object fields and serializes them into plist entries. Fields can be ignored by annotating them with
* {@link pl.maciejwalkowiak.plist.annotation.PlistIgnore} annotation. Its key name can be changed by annotation them with
* {@link pl.maciejwalkowiak.plist.annotation.PlistAlias} annotation.
*
* Its possible to add handlers for additional objects by calling {@link #setAdditionalHandlers(java.util.List)}.
*
* For naming plist <key> {@link #namingStrategy} strategy can be set. By default {@link DefaultNamingStrategy} is used.
*
* @author Maciej Walkowiak
*/
public class PlistSerializerImpl implements PlistSerializer {
private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
private HandlerWrapper handlerWrapper;
private BasicObjectSerializer basicObjectSerializer;
private FieldSerializer fieldSerializer; | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
import java.util.List;
/*
* Copyright (c) 2012 Maciej Walkowiak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.maciejwalkowiak.plist;
/**
* Implementation of {@link PlistSerializer} capable of serializing objects containing elements:
* <ul>
* <li>basic types: {@link Integer}, {@link String}, {@link Boolean}, {@link Double}, {@link Short},
* {@link Long}, {@link Byte} as well as theirs primitive representation</li>
* <li>{@link java.util.Collection}</li>
* <li>{@link java.util.Map}</li>
* </ul>
*
* Goes through all object fields and serializes them into plist entries. Fields can be ignored by annotating them with
* {@link pl.maciejwalkowiak.plist.annotation.PlistIgnore} annotation. Its key name can be changed by annotation them with
* {@link pl.maciejwalkowiak.plist.annotation.PlistAlias} annotation.
*
* Its possible to add handlers for additional objects by calling {@link #setAdditionalHandlers(java.util.List)}.
*
* For naming plist <key> {@link #namingStrategy} strategy can be set. By default {@link DefaultNamingStrategy} is used.
*
* @author Maciej Walkowiak
*/
public class PlistSerializerImpl implements PlistSerializer {
private static final Logger logger = LoggerFactory.getLogger(PlistSerializerImpl.class);
private HandlerWrapper handlerWrapper;
private BasicObjectSerializer basicObjectSerializer;
private FieldSerializer fieldSerializer; | private NamingStrategy namingStrategy = new DefaultNamingStrategy(); |
maciejwalkowiak/java-plist-serializer | src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java | // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
import java.util.List; | this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
}
public String toXmlPlist(Object objectToConvert) {
StringBuilder result = new StringBuilder(HEADER);
result.append(serialize(objectToConvert));
result.append(FOOTER);
return result.toString();
}
public String serialize(Object objectToConvert) {
StringBuilder result = new StringBuilder();
logger.debug("converting object = {}", objectToConvert);
if (objectToConvert != null) {
if (handlerWrapper.isSupported(objectToConvert)) {
result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
} else {
result.append(fieldSerializer.serializeFields(objectToConvert));
}
}
return result.toString();
}
| // Path: src/main/java/pl/maciejwalkowiak/plist/handler/Handler.java
// public interface Handler {
// boolean supports(Object object);
// String handle(Object object);
// }
//
// Path: src/main/java/pl/maciejwalkowiak/plist/strategy/DefaultNamingStrategy.java
// public class DefaultNamingStrategy implements NamingStrategy {
// public String fieldNameToKey(String toConvert) {
// return toConvert;
// }
// }
// Path: src/main/java/pl/maciejwalkowiak/plist/PlistSerializerImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.maciejwalkowiak.plist.handler.Handler;
import pl.maciejwalkowiak.plist.handler.HandlerWrapper;
import pl.maciejwalkowiak.plist.strategy.DefaultNamingStrategy;
import java.util.List;
this.fieldSerializer = new FieldSerializer(handlerWrapper, this);
this.basicObjectSerializer = new BasicObjectSerializer(handlerWrapper);
}
public String toXmlPlist(Object objectToConvert) {
StringBuilder result = new StringBuilder(HEADER);
result.append(serialize(objectToConvert));
result.append(FOOTER);
return result.toString();
}
public String serialize(Object objectToConvert) {
StringBuilder result = new StringBuilder();
logger.debug("converting object = {}", objectToConvert);
if (objectToConvert != null) {
if (handlerWrapper.isSupported(objectToConvert)) {
result.append(basicObjectSerializer.serializeBasicObject(objectToConvert));
} else {
result.append(fieldSerializer.serializeFields(objectToConvert));
}
}
return result.toString();
}
| public void setAdditionalHandlers(List<Handler> additionalHandlers) { |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/HirschbergLinearSpaceLcsTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
| import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest; | package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class HirschbergLinearSpaceLcsTest extends AbstractLcsLengthTest {
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/HirschbergLinearSpaceLcsTest.java
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest;
package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class HirschbergLinearSpaceLcsTest extends AbstractLcsLengthTest {
@Override | public LcsLength getLcsLengthAlgorithm() { |
fillumina/LCS | lcs-algorithms/src/test/java/com/fillumina/lcs/algorithm/scoretable/WagnerFischerLevenshteinDistanceTest.java | // Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/Converter.java
// public class Converter {
//
// public static Character[] toArray(String s) {
// if (s == null) {
// return new Character[0];
// }
// char[] array = s.toCharArray();
// Character[] ca = new Character[array.length];
// for (int i=0; i<array.length; i++) {
// ca[i] = array[i];
// }
// return ca;
// }
//
// public static List<Character> toList(String s) {
// char[] array = s.toCharArray();
// List<Character> list = new ArrayList<>(array.length);
// for (char c : array) {
// list.add(c);
// }
// return list;
// }
//
// public static String toString(List<? extends Character> list) {
// if (list == null || list.isEmpty()) {
// return "";
// }
// int i = 0;
// char[] array = new char[list.size()];
// for (Character c : list) {
// array[i++] = c;
// }
// return new String(array);
// }
//
// }
| import com.fillumina.lcs.testutil.Converter;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test; | package com.fillumina.lcs.algorithm.scoretable;
/**
*
* @author Francesco Illuminati
*/
public class WagnerFischerLevenshteinDistanceTest {
@Test
public void testCloseDistance() {
WagnerFischerLevenshteinDistance algo =
new WagnerFischerLevenshteinDistance();
| // Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/Converter.java
// public class Converter {
//
// public static Character[] toArray(String s) {
// if (s == null) {
// return new Character[0];
// }
// char[] array = s.toCharArray();
// Character[] ca = new Character[array.length];
// for (int i=0; i<array.length; i++) {
// ca[i] = array[i];
// }
// return ca;
// }
//
// public static List<Character> toList(String s) {
// char[] array = s.toCharArray();
// List<Character> list = new ArrayList<>(array.length);
// for (char c : array) {
// list.add(c);
// }
// return list;
// }
//
// public static String toString(List<? extends Character> list) {
// if (list == null || list.isEmpty()) {
// return "";
// }
// int i = 0;
// char[] array = new char[list.size()];
// for (Character c : list) {
// array[i++] = c;
// }
// return new String(array);
// }
//
// }
// Path: lcs-algorithms/src/test/java/com/fillumina/lcs/algorithm/scoretable/WagnerFischerLevenshteinDistanceTest.java
import com.fillumina.lcs.testutil.Converter;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
package com.fillumina.lcs.algorithm.scoretable;
/**
*
* @author Francesco Illuminati
*/
public class WagnerFischerLevenshteinDistanceTest {
@Test
public void testCloseDistance() {
WagnerFischerLevenshteinDistance algo =
new WagnerFischerLevenshteinDistance();
| List<Character> a = Converter.toList("tuesday"); |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/MyersLcsTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
| import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest; | package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class MyersLcsTest extends AbstractLcsLengthTest {
public static void main(String[] args) {
new MyersLcsTest().randomLcs(600, 5, 100);
}
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/MyersLcsTest.java
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest;
package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class MyersLcsTest extends AbstractLcsLengthTest {
public static void main(String[] args) {
new MyersLcsTest().randomLcs(600, 5, 100);
}
@Override | public LcsLength getLcsLengthAlgorithm() { |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/AlgorithmsPerformanceTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/RandomSequenceGenerator.java
// public class RandomSequenceGenerator {
//
// private final int total, lcs;
// private final long seed;
// private final List<Integer> lcsList;
// private Integer[] a, b;
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence (lcs <= total)
// */
// public RandomSequenceGenerator(final int total, final int lcs) {
// this(total, lcs, System.nanoTime());
// }
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence
// * @param seed seed of the random number generator. To the same
// * seeds correspond same random generations (useful for
// * debugging).
// */
// public RandomSequenceGenerator(final int total, final int lcs,
// final long seed) {
// assert lcs <= total;
// this.total = total;
// this.lcs = lcs;
// this.seed = seed;
//
// this.a = new Integer[total];
// this.b = new Integer[total];
// createSequences(total);
//
// Integer[] lcsArray = createLcsArray(lcs);
//
// Random rnd = new Random(seed);
// setLcsSequenceRandomlyIntoList(a, lcsArray, rnd);
// setLcsSequenceRandomlyIntoList(b, lcsArray, rnd);
//
// this.lcsList = Arrays.asList(lcsArray);
// }
//
// private void createSequences(final int total) {
// int index;
// for (int i = 0; i < total; i++) {
// index = i * 2;
// a[i] = index;
// b[i] = index+1;
// }
// }
//
// private static Integer[] createLcsArray(final int lcs) {
// Integer[] lcsArray = new Integer[lcs];
// for (int i = 1; i <= lcs; i++) {
// lcsArray[i-1] = -i;
// }
// return lcsArray;
// }
//
// private void setLcsSequenceRandomlyIntoList(Integer[] array,
// final Integer[] lcsArray, final Random rnd) {
// int max = lcs;
// TreeSet<Integer> set = new TreeSet<>();
// for (int i=0; i<max; i++) {
// if (!set.add(rnd.nextInt(total))) {
// max++;
// }
// }
// assert set.size() == lcs;
// int index = 0;
// Iterator<Integer> i = set.iterator();
// while(i.hasNext()) {
// array[i.next()] = lcsArray[index];
// index++;
// }
// }
//
// public List<Integer> getLcs() {
// return lcsList;
// }
//
// public List<Integer> getA() {
// return Arrays.asList(a);
// }
//
// public List<Integer> getB() {
// return Arrays.asList(b);
// }
//
// public Integer[] getArrayA() {
// return Arrays.copyOf(a, a.length);
// }
//
// public Integer[] getArrayB() {
// return Arrays.copyOf(b, b.length);
// }
//
// public long getSeed() {
// return seed;
// }
//
// @Override
// public String toString() {
// return "RandomSequenceGenerator (lcs= " + lcs +
// ", seed= " + seed + "L ):\n" +
// " a=" + a.toString() +
// "\n b=" + b.toString() +
// "\n";
// }
// }
| import com.fillumina.lcs.helper.LcsList;
import com.fillumina.lcs.testutil.RandomSequenceGenerator;
import com.fillumina.performance.consumer.assertion.PerformanceAssertion;
import com.fillumina.performance.producer.TestContainer;
import com.fillumina.performance.template.AutoProgressionPerformanceTemplate;
import com.fillumina.performance.template.ProgressionConfigurator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals; | package com.fillumina.lcs;
/**
* Confront the performances of different algorithms. Note that performances
* can vary for different values of {@link #TOTAL} and {@link #LCS}.
*
* @author Francesco Illuminati
*/
public class AlgorithmsPerformanceTest extends AutoProgressionPerformanceTemplate {
private static final int TOTAL = 30;
private static final int LCS = 20;
private static final long SEED = System.nanoTime();
| // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/RandomSequenceGenerator.java
// public class RandomSequenceGenerator {
//
// private final int total, lcs;
// private final long seed;
// private final List<Integer> lcsList;
// private Integer[] a, b;
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence (lcs <= total)
// */
// public RandomSequenceGenerator(final int total, final int lcs) {
// this(total, lcs, System.nanoTime());
// }
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence
// * @param seed seed of the random number generator. To the same
// * seeds correspond same random generations (useful for
// * debugging).
// */
// public RandomSequenceGenerator(final int total, final int lcs,
// final long seed) {
// assert lcs <= total;
// this.total = total;
// this.lcs = lcs;
// this.seed = seed;
//
// this.a = new Integer[total];
// this.b = new Integer[total];
// createSequences(total);
//
// Integer[] lcsArray = createLcsArray(lcs);
//
// Random rnd = new Random(seed);
// setLcsSequenceRandomlyIntoList(a, lcsArray, rnd);
// setLcsSequenceRandomlyIntoList(b, lcsArray, rnd);
//
// this.lcsList = Arrays.asList(lcsArray);
// }
//
// private void createSequences(final int total) {
// int index;
// for (int i = 0; i < total; i++) {
// index = i * 2;
// a[i] = index;
// b[i] = index+1;
// }
// }
//
// private static Integer[] createLcsArray(final int lcs) {
// Integer[] lcsArray = new Integer[lcs];
// for (int i = 1; i <= lcs; i++) {
// lcsArray[i-1] = -i;
// }
// return lcsArray;
// }
//
// private void setLcsSequenceRandomlyIntoList(Integer[] array,
// final Integer[] lcsArray, final Random rnd) {
// int max = lcs;
// TreeSet<Integer> set = new TreeSet<>();
// for (int i=0; i<max; i++) {
// if (!set.add(rnd.nextInt(total))) {
// max++;
// }
// }
// assert set.size() == lcs;
// int index = 0;
// Iterator<Integer> i = set.iterator();
// while(i.hasNext()) {
// array[i.next()] = lcsArray[index];
// index++;
// }
// }
//
// public List<Integer> getLcs() {
// return lcsList;
// }
//
// public List<Integer> getA() {
// return Arrays.asList(a);
// }
//
// public List<Integer> getB() {
// return Arrays.asList(b);
// }
//
// public Integer[] getArrayA() {
// return Arrays.copyOf(a, a.length);
// }
//
// public Integer[] getArrayB() {
// return Arrays.copyOf(b, b.length);
// }
//
// public long getSeed() {
// return seed;
// }
//
// @Override
// public String toString() {
// return "RandomSequenceGenerator (lcs= " + lcs +
// ", seed= " + seed + "L ):\n" +
// " a=" + a.toString() +
// "\n b=" + b.toString() +
// "\n";
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/AlgorithmsPerformanceTest.java
import com.fillumina.lcs.helper.LcsList;
import com.fillumina.lcs.testutil.RandomSequenceGenerator;
import com.fillumina.performance.consumer.assertion.PerformanceAssertion;
import com.fillumina.performance.producer.TestContainer;
import com.fillumina.performance.template.AutoProgressionPerformanceTemplate;
import com.fillumina.performance.template.ProgressionConfigurator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
package com.fillumina.lcs;
/**
* Confront the performances of different algorithms. Note that performances
* can vary for different values of {@link #TOTAL} and {@link #LCS}.
*
* @author Francesco Illuminati
*/
public class AlgorithmsPerformanceTest extends AutoProgressionPerformanceTemplate {
private static final int TOTAL = 30;
private static final int LCS = 20;
private static final long SEED = System.nanoTime();
| private final RandomSequenceGenerator generator; |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/AlgorithmsPerformanceTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/RandomSequenceGenerator.java
// public class RandomSequenceGenerator {
//
// private final int total, lcs;
// private final long seed;
// private final List<Integer> lcsList;
// private Integer[] a, b;
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence (lcs <= total)
// */
// public RandomSequenceGenerator(final int total, final int lcs) {
// this(total, lcs, System.nanoTime());
// }
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence
// * @param seed seed of the random number generator. To the same
// * seeds correspond same random generations (useful for
// * debugging).
// */
// public RandomSequenceGenerator(final int total, final int lcs,
// final long seed) {
// assert lcs <= total;
// this.total = total;
// this.lcs = lcs;
// this.seed = seed;
//
// this.a = new Integer[total];
// this.b = new Integer[total];
// createSequences(total);
//
// Integer[] lcsArray = createLcsArray(lcs);
//
// Random rnd = new Random(seed);
// setLcsSequenceRandomlyIntoList(a, lcsArray, rnd);
// setLcsSequenceRandomlyIntoList(b, lcsArray, rnd);
//
// this.lcsList = Arrays.asList(lcsArray);
// }
//
// private void createSequences(final int total) {
// int index;
// for (int i = 0; i < total; i++) {
// index = i * 2;
// a[i] = index;
// b[i] = index+1;
// }
// }
//
// private static Integer[] createLcsArray(final int lcs) {
// Integer[] lcsArray = new Integer[lcs];
// for (int i = 1; i <= lcs; i++) {
// lcsArray[i-1] = -i;
// }
// return lcsArray;
// }
//
// private void setLcsSequenceRandomlyIntoList(Integer[] array,
// final Integer[] lcsArray, final Random rnd) {
// int max = lcs;
// TreeSet<Integer> set = new TreeSet<>();
// for (int i=0; i<max; i++) {
// if (!set.add(rnd.nextInt(total))) {
// max++;
// }
// }
// assert set.size() == lcs;
// int index = 0;
// Iterator<Integer> i = set.iterator();
// while(i.hasNext()) {
// array[i.next()] = lcsArray[index];
// index++;
// }
// }
//
// public List<Integer> getLcs() {
// return lcsList;
// }
//
// public List<Integer> getA() {
// return Arrays.asList(a);
// }
//
// public List<Integer> getB() {
// return Arrays.asList(b);
// }
//
// public Integer[] getArrayA() {
// return Arrays.copyOf(a, a.length);
// }
//
// public Integer[] getArrayB() {
// return Arrays.copyOf(b, b.length);
// }
//
// public long getSeed() {
// return seed;
// }
//
// @Override
// public String toString() {
// return "RandomSequenceGenerator (lcs= " + lcs +
// ", seed= " + seed + "L ):\n" +
// " a=" + a.toString() +
// "\n b=" + b.toString() +
// "\n";
// }
// }
| import com.fillumina.lcs.helper.LcsList;
import com.fillumina.lcs.testutil.RandomSequenceGenerator;
import com.fillumina.performance.consumer.assertion.PerformanceAssertion;
import com.fillumina.performance.producer.TestContainer;
import com.fillumina.performance.template.AutoProgressionPerformanceTemplate;
import com.fillumina.performance.template.ProgressionConfigurator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals; | package com.fillumina.lcs;
/**
* Confront the performances of different algorithms. Note that performances
* can vary for different values of {@link #TOTAL} and {@link #LCS}.
*
* @author Francesco Illuminati
*/
public class AlgorithmsPerformanceTest extends AutoProgressionPerformanceTemplate {
private static final int TOTAL = 30;
private static final int LCS = 20;
private static final long SEED = System.nanoTime();
private final RandomSequenceGenerator generator;
private final List<Integer> lcsList;
public static void main(String[] args) {
System.out.println("performance evaluation, please wait...");
new AlgorithmsPerformanceTest().executeWithIntermediateOutput();
}
public AlgorithmsPerformanceTest() {
super();
this.generator = new RandomSequenceGenerator(TOTAL, LCS, SEED);
this.lcsList = generator.getLcs();
}
private class LcsRunnable implements Runnable { | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/RandomSequenceGenerator.java
// public class RandomSequenceGenerator {
//
// private final int total, lcs;
// private final long seed;
// private final List<Integer> lcsList;
// private Integer[] a, b;
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence (lcs <= total)
// */
// public RandomSequenceGenerator(final int total, final int lcs) {
// this(total, lcs, System.nanoTime());
// }
//
// /**
// *
// * @param total length of the sequences
// * @param lcs length of the longest common sequence
// * @param seed seed of the random number generator. To the same
// * seeds correspond same random generations (useful for
// * debugging).
// */
// public RandomSequenceGenerator(final int total, final int lcs,
// final long seed) {
// assert lcs <= total;
// this.total = total;
// this.lcs = lcs;
// this.seed = seed;
//
// this.a = new Integer[total];
// this.b = new Integer[total];
// createSequences(total);
//
// Integer[] lcsArray = createLcsArray(lcs);
//
// Random rnd = new Random(seed);
// setLcsSequenceRandomlyIntoList(a, lcsArray, rnd);
// setLcsSequenceRandomlyIntoList(b, lcsArray, rnd);
//
// this.lcsList = Arrays.asList(lcsArray);
// }
//
// private void createSequences(final int total) {
// int index;
// for (int i = 0; i < total; i++) {
// index = i * 2;
// a[i] = index;
// b[i] = index+1;
// }
// }
//
// private static Integer[] createLcsArray(final int lcs) {
// Integer[] lcsArray = new Integer[lcs];
// for (int i = 1; i <= lcs; i++) {
// lcsArray[i-1] = -i;
// }
// return lcsArray;
// }
//
// private void setLcsSequenceRandomlyIntoList(Integer[] array,
// final Integer[] lcsArray, final Random rnd) {
// int max = lcs;
// TreeSet<Integer> set = new TreeSet<>();
// for (int i=0; i<max; i++) {
// if (!set.add(rnd.nextInt(total))) {
// max++;
// }
// }
// assert set.size() == lcs;
// int index = 0;
// Iterator<Integer> i = set.iterator();
// while(i.hasNext()) {
// array[i.next()] = lcsArray[index];
// index++;
// }
// }
//
// public List<Integer> getLcs() {
// return lcsList;
// }
//
// public List<Integer> getA() {
// return Arrays.asList(a);
// }
//
// public List<Integer> getB() {
// return Arrays.asList(b);
// }
//
// public Integer[] getArrayA() {
// return Arrays.copyOf(a, a.length);
// }
//
// public Integer[] getArrayB() {
// return Arrays.copyOf(b, b.length);
// }
//
// public long getSeed() {
// return seed;
// }
//
// @Override
// public String toString() {
// return "RandomSequenceGenerator (lcs= " + lcs +
// ", seed= " + seed + "L ):\n" +
// " a=" + a.toString() +
// "\n b=" + b.toString() +
// "\n";
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/AlgorithmsPerformanceTest.java
import com.fillumina.lcs.helper.LcsList;
import com.fillumina.lcs.testutil.RandomSequenceGenerator;
import com.fillumina.performance.consumer.assertion.PerformanceAssertion;
import com.fillumina.performance.producer.TestContainer;
import com.fillumina.performance.template.AutoProgressionPerformanceTemplate;
import com.fillumina.performance.template.ProgressionConfigurator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
package com.fillumina.lcs;
/**
* Confront the performances of different algorithms. Note that performances
* can vary for different values of {@link #TOTAL} and {@link #LCS}.
*
* @author Francesco Illuminati
*/
public class AlgorithmsPerformanceTest extends AutoProgressionPerformanceTemplate {
private static final int TOTAL = 30;
private static final int LCS = 20;
private static final long SEED = System.nanoTime();
private final RandomSequenceGenerator generator;
private final List<Integer> lcsList;
public static void main(String[] args) {
System.out.println("performance evaluation, please wait...");
new AlgorithmsPerformanceTest().executeWithIntermediateOutput();
}
public AlgorithmsPerformanceTest() {
super();
this.generator = new RandomSequenceGenerator(TOTAL, LCS, SEED);
this.lcsList = generator.getLcs();
}
private class LcsRunnable implements Runnable { | private final LcsList lcsAlgorithm; |
fillumina/LCS | lcs-algorithms/src/test/java/com/fillumina/lcs/algorithm/myers/BidirectionalVectorTest.java | // Path: lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/BidirectionalVector.java
// public class BidirectionalVector {
//
// private final int[] array;
// private final int zero;
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// */
// public BidirectionalVector(int size) {
// this(size, 0);
// }
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// * @param offset is always subtracted to the given index
// */
// public BidirectionalVector(int size, int offset) {
// int length = size + Math.abs(offset);
// this.array = new int[(length << 1) + 1];
// this.zero = length - offset;
// }
//
// /** Clone constructor. */
// private BidirectionalVector(int zero, int[] array) {
// this.zero = zero;
// this.array = array;
// }
//
// public int get(int x) {
// return array[zero + x];
// }
//
// public void set(int x, int value) {
// array[zero + x] = value;
// }
//
// @Override
// public String toString() {
// return "" + zero + ":" + Arrays.toString(array);
// }
//
// /** Same as {@link Object#clone()} but without throwing anything. */
// public BidirectionalVector copy() {
// int [] cloned = new int[array.length];
// System.arraycopy(array, 0, cloned, 0, array.length);
// return new BidirectionalVector(zero, cloned);
// }
//
// }
| import com.fillumina.lcs.algorithm.myers.BidirectionalVector;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | package com.fillumina.lcs.algorithm.myers;
/**
*
* @author Francesco Illuminati
*/
public class BidirectionalVectorTest {
@Test
public void shouldCreateAnEmptyVector() { | // Path: lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/BidirectionalVector.java
// public class BidirectionalVector {
//
// private final int[] array;
// private final int zero;
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// */
// public BidirectionalVector(int size) {
// this(size, 0);
// }
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// * @param offset is always subtracted to the given index
// */
// public BidirectionalVector(int size, int offset) {
// int length = size + Math.abs(offset);
// this.array = new int[(length << 1) + 1];
// this.zero = length - offset;
// }
//
// /** Clone constructor. */
// private BidirectionalVector(int zero, int[] array) {
// this.zero = zero;
// this.array = array;
// }
//
// public int get(int x) {
// return array[zero + x];
// }
//
// public void set(int x, int value) {
// array[zero + x] = value;
// }
//
// @Override
// public String toString() {
// return "" + zero + ":" + Arrays.toString(array);
// }
//
// /** Same as {@link Object#clone()} but without throwing anything. */
// public BidirectionalVector copy() {
// int [] cloned = new int[array.length];
// System.arraycopy(array, 0, cloned, 0, array.length);
// return new BidirectionalVector(zero, cloned);
// }
//
// }
// Path: lcs-algorithms/src/test/java/com/fillumina/lcs/algorithm/myers/BidirectionalVectorTest.java
import com.fillumina.lcs.algorithm.myers.BidirectionalVector;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
package com.fillumina.lcs.algorithm.myers;
/**
*
* @author Francesco Illuminati
*/
public class BidirectionalVectorTest {
@Test
public void shouldCreateAnEmptyVector() { | BidirectionalVector v = new BidirectionalVector(0); |
fillumina/LCS | lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsTestExecutor.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
| import com.fillumina.lcs.helper.LcsList;
import java.util.Arrays;
import java.util.List;
import javax.xml.stream.events.Characters; | package com.fillumina.lcs.testutil;
/**
* An helper for testing LCS algorithms.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsTestExecutor
extends Converter {
/**
* Call {@link #count(List<Characters> xs, List<Charactes> ys)} in
* the body of the created
* {@link LcsList#lcs(java.util.List, java.util.List)}.
*/ | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsTestExecutor.java
import com.fillumina.lcs.helper.LcsList;
import java.util.Arrays;
import java.util.List;
import javax.xml.stream.events.Characters;
package com.fillumina.lcs.testutil;
/**
* An helper for testing LCS algorithms.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsTestExecutor
extends Converter {
/**
* Call {@link #count(List<Characters> xs, List<Charactes> ys)} in
* the body of the created
* {@link LcsList#lcs(java.util.List, java.util.List)}.
*/ | public abstract LcsList getLcsAlgorithm(); |
fillumina/LCS | lcs-test-util/src/test/java/com/fillumina/lcs/testutil/AbstractLcsTestExecutorTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
| import com.fillumina.lcs.helper.LcsList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test; | package com.fillumina.lcs.testutil;
/**
*
* @author Francesco Illuminati
*/
public class AbstractLcsTestExecutorTest extends AbstractLcsTestExecutor {
@Test
public void shouldReturnResult() {
lcs("ab", "cd").assertResult("abcd");
}
@Test(expected = AssertionError.class)
public void shouldCheckErrorResult() {
lcs("ab", "cd").assertResult("ERROR");
}
@Test(expected = AssertionError.class)
public void shouldGetEmptyStrings() {
lcs(null, "").assertResult((String)null);
}
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
// Path: lcs-test-util/src/test/java/com/fillumina/lcs/testutil/AbstractLcsTestExecutorTest.java
import com.fillumina.lcs.helper.LcsList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
package com.fillumina.lcs.testutil;
/**
*
* @author Francesco Illuminati
*/
public class AbstractLcsTestExecutorTest extends AbstractLcsTestExecutor {
@Test
public void shouldReturnResult() {
lcs("ab", "cd").assertResult("abcd");
}
@Test(expected = AssertionError.class)
public void shouldCheckErrorResult() {
lcs("ab", "cd").assertResult("ERROR");
}
@Test(expected = AssertionError.class)
public void shouldGetEmptyStrings() {
lcs(null, "").assertResult((String)null);
}
@Override | public LcsList getLcsAlgorithm() { |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/LinearSpaceMyersLcsTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
| import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest; | package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class LinearSpaceMyersLcsTest extends AbstractLcsLengthTest {
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/LinearSpaceMyersLcsTest.java
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest;
package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati
*/
public class LinearSpaceMyersLcsTest extends AbstractLcsLengthTest {
@Override | public LcsLength getLcsLengthAlgorithm() { |
fillumina/LCS | lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/linearspace/LinearSpaceMyersLcsSolver.java | // Path: lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/BidirectionalVector.java
// public class BidirectionalVector {
//
// private final int[] array;
// private final int zero;
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// */
// public BidirectionalVector(int size) {
// this(size, 0);
// }
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// * @param offset is always subtracted to the given index
// */
// public BidirectionalVector(int size, int offset) {
// int length = size + Math.abs(offset);
// this.array = new int[(length << 1) + 1];
// this.zero = length - offset;
// }
//
// /** Clone constructor. */
// private BidirectionalVector(int zero, int[] array) {
// this.zero = zero;
// this.array = array;
// }
//
// public int get(int x) {
// return array[zero + x];
// }
//
// public void set(int x, int value) {
// array[zero + x] = value;
// }
//
// @Override
// public String toString() {
// return "" + zero + ":" + Arrays.toString(array);
// }
//
// /** Same as {@link Object#clone()} but without throwing anything. */
// public BidirectionalVector copy() {
// int [] cloned = new int[array.length];
// System.arraycopy(array, 0, cloned, 0, array.length);
// return new BidirectionalVector(zero, cloned);
// }
//
// }
| import com.fillumina.lcs.algorithm.myers.BidirectionalVector;
import java.util.ArrayList;
import java.util.List; | package com.fillumina.lcs.algorithm.myers.linearspace;
/**
* Myers algorithm that uses forward and backward snakes. It is not designed
* to be fast but to be easy to understand and close to the description
* given by Myers on his paper.
*
* @see <a href='www.xmailserver.org/diff2.pdf'>
* An O(ND) Difference Algorithm and Its Variations (PDF)
* </a>
*
* @author Francesco Illuminati
*/
class LinearSpaceMyersLcsSolver<T> {
private final T[] a;
private final T[] b;
public LinearSpaceMyersLcsSolver(T[] a, T[] b) {
this.a = a;
this.b = b;
}
List<T> calculateLcs() {
Snake snakes = new Section(0, 0, a.length, b.length).lcs();
return extractLcs(snakes);
}
/** @return the common subsequence elements. */
private List<T> extractLcs(Snake snakes) {
List<T> list = new ArrayList<>();
for (Snake snake : snakes) {
for (int index : snake.getDiagonal()) {
list.add(a[index]);
}
}
return list;
}
class Section extends Rectangle {
Section(int xStart, int yStart, int xEnd, int yEnd) {
super(xStart, yStart, xEnd, yEnd);
}
/**
* Executes the LCS algorithm over this section. Remember that the
* returned snake is actually an iterable of snakes.
*/
<T> Snake lcs() {
if (isImproper()) {
// has zero size in at least one of its dimensions
return createNullSnake();
}
Snake snake = findMiddleSnake();
if (hasSameDimentionOf(snake)) {
// the returned snake has the size of the entire section
return snake;
}
// recurse the algorithm on the sections before and after
// the returned snake
Snake before = getSectionBefore(snake).lcs();
Snake after = getSectionAfter(snake).lcs();
// chain the snakes containing the solution together
return Snake.chain(before, snake, after);
}
/** Searches for a snake in the section. */
<T> Snake findMiddleSnake() {
final int max = (int) Math.ceil((m + n) / 2.0) + 1;
final int delta = n - m;
final boolean evenDelta = delta % 2 == 0;
| // Path: lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/BidirectionalVector.java
// public class BidirectionalVector {
//
// private final int[] array;
// private final int zero;
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// */
// public BidirectionalVector(int size) {
// this(size, 0);
// }
//
// /**
// * @param size specify the positive size (the total size will be
// * {@code size * 2 + 1}.
// * @param offset is always subtracted to the given index
// */
// public BidirectionalVector(int size, int offset) {
// int length = size + Math.abs(offset);
// this.array = new int[(length << 1) + 1];
// this.zero = length - offset;
// }
//
// /** Clone constructor. */
// private BidirectionalVector(int zero, int[] array) {
// this.zero = zero;
// this.array = array;
// }
//
// public int get(int x) {
// return array[zero + x];
// }
//
// public void set(int x, int value) {
// array[zero + x] = value;
// }
//
// @Override
// public String toString() {
// return "" + zero + ":" + Arrays.toString(array);
// }
//
// /** Same as {@link Object#clone()} but without throwing anything. */
// public BidirectionalVector copy() {
// int [] cloned = new int[array.length];
// System.arraycopy(array, 0, cloned, 0, array.length);
// return new BidirectionalVector(zero, cloned);
// }
//
// }
// Path: lcs-algorithms/src/main/java/com/fillumina/lcs/algorithm/myers/linearspace/LinearSpaceMyersLcsSolver.java
import com.fillumina.lcs.algorithm.myers.BidirectionalVector;
import java.util.ArrayList;
import java.util.List;
package com.fillumina.lcs.algorithm.myers.linearspace;
/**
* Myers algorithm that uses forward and backward snakes. It is not designed
* to be fast but to be easy to understand and close to the description
* given by Myers on his paper.
*
* @see <a href='www.xmailserver.org/diff2.pdf'>
* An O(ND) Difference Algorithm and Its Variations (PDF)
* </a>
*
* @author Francesco Illuminati
*/
class LinearSpaceMyersLcsSolver<T> {
private final T[] a;
private final T[] b;
public LinearSpaceMyersLcsSolver(T[] a, T[] b) {
this.a = a;
this.b = b;
}
List<T> calculateLcs() {
Snake snakes = new Section(0, 0, a.length, b.length).lcs();
return extractLcs(snakes);
}
/** @return the common subsequence elements. */
private List<T> extractLcs(Snake snakes) {
List<T> list = new ArrayList<>();
for (Snake snake : snakes) {
for (int index : snake.getDiagonal()) {
list.add(a[index]);
}
}
return list;
}
class Section extends Rectangle {
Section(int xStart, int yStart, int xEnd, int yEnd) {
super(xStart, yStart, xEnd, yEnd);
}
/**
* Executes the LCS algorithm over this section. Remember that the
* returned snake is actually an iterable of snakes.
*/
<T> Snake lcs() {
if (isImproper()) {
// has zero size in at least one of its dimensions
return createNullSnake();
}
Snake snake = findMiddleSnake();
if (hasSameDimentionOf(snake)) {
// the returned snake has the size of the entire section
return snake;
}
// recurse the algorithm on the sections before and after
// the returned snake
Snake before = getSectionBefore(snake).lcs();
Snake after = getSectionAfter(snake).lcs();
// chain the snakes containing the solution together
return Snake.chain(before, snake, after);
}
/** Searches for a snake in the section. */
<T> Snake findMiddleSnake() {
final int max = (int) Math.ceil((m + n) / 2.0) + 1;
final int delta = n - m;
final boolean evenDelta = delta % 2 == 0;
| final BidirectionalVector vf = new BidirectionalVector(max); |
fillumina/LCS | lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
| import com.fillumina.lcs.helper.LcsList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | package com.fillumina.lcs.testutil;
/**
* A suite of tests for LCS sequences.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsTest extends AbstractLcsTestExecutor {
public void randomLcs(int len, int lcs, int iterations) { | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsTest.java
import com.fillumina.lcs.helper.LcsList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
package com.fillumina.lcs.testutil;
/**
* A suite of tests for LCS sequences.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsTest extends AbstractLcsTestExecutor {
public void randomLcs(int len, int lcs, int iterations) { | final LcsList algorithm = getLcsAlgorithm(); |
fillumina/LCS | lcs/src/test/java/com/fillumina/lcs/WagnerFisherLcsTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
| import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest; | package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati <[email protected]>
*/
public class WagnerFisherLcsTest extends AbstractLcsLengthTest {
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
// public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
//
// public abstract LcsLength getLcsLengthAlgorithm();
//
// @Override
// public LcsList getLcsAlgorithm() {
// return getLcsLengthAlgorithm();
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHUMAN() {
// countLcs("HUMAN", "CHIMPANZEE", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsABCABBA() {
// countLcs("ABCABBA", "CBABAC", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsPYTHON() {
// countLcs("PYTHON", "PONY", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsSPRINGTIME() {
// countLcs("SPRINGTIME", "PIONEER", 4);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHORSEBACK() {
// countLcs("HORSEBACK", "SNOWFLAKE", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsMAELSTROM() {
// countLcs("MAELSTROM", "BECALM", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsHEROICALLY() {
// countLcs("HEROICALLY", "SCHOLARLY", 5);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs0ForAnEmptyString() {
// countLcs("ABCDEF", "GHIJKLMN", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtBeginning() {
// countLcs("ABCDEF", "A", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtEnd() {
// countLcs("ABCDEF", "F", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcs1ForTheOnlyMatchAtMiddle() {
// countLcs("ABCDEF", "C", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyList() {
// countLcs("ABCDEF", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtBeginningReversed() {
// countLcs("A", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtEndReversed() {
// countLcs("F", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheOnlyMatchAtMiddleReversed() {
// countLcs("C", "ABCDEF", 1);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyResultForEmptyListReversed() {
// countLcs("", "ABCDEF", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsEmptyListForBothEmptyList() {
// countLcs("", "", 0);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheLeftDiagonal() {
// countLcs("123AAAAAAA", "123BBBBBBB", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheRightDiagonal() {
// countLcs("AAAAAAA123", "BBBBBBB123", 3);
// }
//
// @Test(timeout = 2000L)
// public void shouldLcsTheBothEndsDiagonals() {
// countLcs("123AAAAAAA123", "123BBBBBBB123", 6);
// }
//
// @Test(timeout = 2000L)
// public void shouldPassLengthTestSize() {
// final int tot = 600;
// final int lcs = 500;
// RandomSequenceGenerator seqGen = new RandomSequenceGenerator(tot, lcs);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(lcs, algorithm.lcsLength(seqGen.getArrayA(),
// seqGen.getArrayB()));
// }
//
// private void countLcs(String a, String b, int expectedLcs) {
// final Character[] arrayA = Converter.toArray(a);
// final Character[] arrayB = Converter.toArray(b);
// final LcsLength algorithm = getLcsLengthAlgorithm();
// assertEquals(expectedLcs, algorithm.lcsLength(arrayA, arrayB));
// }
//
// @Test//(timeout = 2_000L)
// public void shouldPassVeryLongTest() {
// randomLcs(6000, 5000, 1);
// }
// }
// Path: lcs/src/test/java/com/fillumina/lcs/WagnerFisherLcsTest.java
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.testutil.AbstractLcsLengthTest;
package com.fillumina.lcs;
/**
*
* @author Francesco Illuminati <[email protected]>
*/
public class WagnerFisherLcsTest extends AbstractLcsLengthTest {
@Override | public LcsLength getLcsLengthAlgorithm() { |
fillumina/LCS | lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
| import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.helper.LcsList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | package com.fillumina.lcs.testutil;
/**
* A test suite that checks the returned LCS length.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
public abstract LcsLength getLcsLengthAlgorithm();
@Override | // Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsLength.java
// public interface LcsLength extends LcsList {
//
// int lcsLength(Object[] xs, Object[] ys);
// }
//
// Path: lcs-helper/src/main/java/com/fillumina/lcs/helper/LcsList.java
// public interface LcsList {
//
// <T> List<T> lcs(T[] xs, T[] ys);
// }
// Path: lcs-test-util/src/main/java/com/fillumina/lcs/testutil/AbstractLcsLengthTest.java
import com.fillumina.lcs.helper.LcsLength;
import com.fillumina.lcs.helper.LcsList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
package com.fillumina.lcs.testutil;
/**
* A test suite that checks the returned LCS length.
*
* @author Francesco Illuminati
*/
public abstract class AbstractLcsLengthTest extends AbstractLcsTest {
public abstract LcsLength getLcsLengthAlgorithm();
@Override | public LcsList getLcsAlgorithm() { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.