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 |
|---|---|---|---|---|---|---|
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/DefinitionsReferenceNameProvider.java | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
| import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap; | package pl.zientarski;
public class DefinitionsReferenceNameProvider extends DefaultReferenceNameProvider {
@Override
protected String getPrefix() {
return "#/definitions/";
}
@Override
public String typeReferenceName(Class<?> clazz, List<Type> genericTypeArguments) {
try {
final StringBuilder ref = new StringBuilder(); | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
// Path: src/main/java/pl/zientarski/DefinitionsReferenceNameProvider.java
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap;
package pl.zientarski;
public class DefinitionsReferenceNameProvider extends DefaultReferenceNameProvider {
@Override
protected String getPrefix() {
return "#/definitions/";
}
@Override
public String typeReferenceName(Class<?> clazz, List<Type> genericTypeArguments) {
try {
final StringBuilder ref = new StringBuilder(); | if (isPrimitiveTypeWrapper(clazz)) { |
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/DefinitionsReferenceNameProvider.java | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
| import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap; | package pl.zientarski;
public class DefinitionsReferenceNameProvider extends DefaultReferenceNameProvider {
@Override
protected String getPrefix() {
return "#/definitions/";
}
@Override
public String typeReferenceName(Class<?> clazz, List<Type> genericTypeArguments) {
try {
final StringBuilder ref = new StringBuilder();
if (isPrimitiveTypeWrapper(clazz)) { | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
// Path: src/main/java/pl/zientarski/DefinitionsReferenceNameProvider.java
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap;
package pl.zientarski;
public class DefinitionsReferenceNameProvider extends DefaultReferenceNameProvider {
@Override
protected String getPrefix() {
return "#/definitions/";
}
@Override
public String typeReferenceName(Class<?> clazz, List<Type> genericTypeArguments) {
try {
final StringBuilder ref = new StringBuilder();
if (isPrimitiveTypeWrapper(clazz)) { | ref.append(unwrap(clazz).getSimpleName()); |
wodzuu/JSONschema4-mapper | src/test/java/pl/zientarski/DocumentationTest.java | // Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java
// public interface TypeHandler {
// boolean accepts(Type type);
//
// JSONObject process(TypeDescription typeDescription, MapperContext mapperContext);
// }
//
// Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
| import com.google.common.collect.Lists;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import pl.zientarski.typehandler.TypeHandler;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*; | public void descriptionProviderTest() throws Exception {
//given
schemaMapper.setDescriptionProvider(Object::toString);
//and
class Demo {
private int field;
public int getField() {
return field;
}
}
//when
final JSONObject schema = schemaMapper.toJsonSchema4(Demo.class);
//then
assertTrue(schema.has("description"));
assertThat(schema.toString(), equalTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"description\":\"class pl.zientarski.DocumentationTest$4Demo\",\"additionalProperties\":false,\"type\":\"object\",\"properties\":{\"field\":{\"$ref\":\"int\"}},\"required\":[\"field\"]}"));
}
@Test
public void typeHandlerTest() throws Exception {
//given
class DeathStar {
}
//and | // Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java
// public interface TypeHandler {
// boolean accepts(Type type);
//
// JSONObject process(TypeDescription typeDescription, MapperContext mapperContext);
// }
//
// Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
// Path: src/test/java/pl/zientarski/DocumentationTest.java
import com.google.common.collect.Lists;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import pl.zientarski.typehandler.TypeHandler;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*;
public void descriptionProviderTest() throws Exception {
//given
schemaMapper.setDescriptionProvider(Object::toString);
//and
class Demo {
private int field;
public int getField() {
return field;
}
}
//when
final JSONObject schema = schemaMapper.toJsonSchema4(Demo.class);
//then
assertTrue(schema.has("description"));
assertThat(schema.toString(), equalTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"description\":\"class pl.zientarski.DocumentationTest$4Demo\",\"additionalProperties\":false,\"type\":\"object\",\"properties\":{\"field\":{\"$ref\":\"int\"}},\"required\":[\"field\"]}"));
}
@Test
public void typeHandlerTest() throws Exception {
//given
class DeathStar {
}
//and | schemaMapper.addTypeHandler(new TypeHandler() { |
wodzuu/JSONschema4-mapper | src/test/java/pl/zientarski/DocumentationTest.java | // Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java
// public interface TypeHandler {
// boolean accepts(Type type);
//
// JSONObject process(TypeDescription typeDescription, MapperContext mapperContext);
// }
//
// Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
| import com.google.common.collect.Lists;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import pl.zientarski.typehandler.TypeHandler;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*; | //when
final JSONObject schema = schemaMapper.toJsonSchema4(DeathStar.class);
//then
assertTrue(schema.has("construction"));
assertThat(schema.toString(), equalTo("{\"construction\":\"completed\"}"));
}
@Test(expected = MappingException.class)
public void withoutSpecifiedGenericParameterTest() throws Exception {
class Generic<T> {
private T field;
public T getField() {
return field;
}
}
schemaMapper.toJsonSchema4(Generic.class);
}
@Test
public void withSpecifiedGenericParameterTest() throws Exception {
class Generic<T> {
private T field;
public T getField() {
return field;
}
} | // Path: src/main/java/pl/zientarski/typehandler/TypeHandler.java
// public interface TypeHandler {
// boolean accepts(Type type);
//
// JSONObject process(TypeDescription typeDescription, MapperContext mapperContext);
// }
//
// Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
// Path: src/test/java/pl/zientarski/DocumentationTest.java
import com.google.common.collect.Lists;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import pl.zientarski.typehandler.TypeHandler;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*;
//when
final JSONObject schema = schemaMapper.toJsonSchema4(DeathStar.class);
//then
assertTrue(schema.has("construction"));
assertThat(schema.toString(), equalTo("{\"construction\":\"completed\"}"));
}
@Test(expected = MappingException.class)
public void withoutSpecifiedGenericParameterTest() throws Exception {
class Generic<T> {
private T field;
public T getField() {
return field;
}
}
schemaMapper.toJsonSchema4(Generic.class);
}
@Test
public void withSpecifiedGenericParameterTest() throws Exception {
class Generic<T> {
private T field;
public T getField() {
return field;
}
} | Type type = new ParameterizedTypeReference<Generic<String>>(){}.getType(); |
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/typehandler/DefaultTypeHandler.java | // Path: src/main/java/pl/zientarski/serialization/PropertySerializer.java
// public abstract class PropertySerializer {
//
// protected final PropertyDescription propertyDescription;
// protected final MapperContext mapperContext;
//
// public PropertySerializer(final PropertyDescription propertyDescription, final MapperContext mapperContext) {
// this.propertyDescription = propertyDescription;
// this.mapperContext = mapperContext;
// }
//
// public String getPropertyName() {
// return propertyDescription.getName();
// }
//
// public abstract JSONObject toJsonObject();
//
// public boolean isPropertyRequired() {
// return false;
// }
// }
//
// Path: src/main/java/pl/zientarski/serialization/PropertySerializerFactory.java
// public interface PropertySerializerFactory {
// public static PropertySerializer get(final PropertyDescription description, final MapperContext mapperContext) {
// final Type type = description.getType();
// return getForType(type, description, mapperContext);
// }
//
// public static PropertySerializer getForType(final Type type, final PropertyDescription description, final MapperContext mapperContext) {
// if (type instanceof ParameterizedType) {
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// if (Collection.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
// return new CollectionSerializer(description, parameterizedType.getActualTypeArguments()[0], mapperContext);
// }
// return new GenericObjectSerializer(description, mapperContext);
// } else if (type instanceof TypeVariable) {
// final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
// final Type genericType = mapperContext.getGenericTypeByName(typeVariable.getTypeName());
// return getForType(genericType, description, mapperContext);
// } else {
// final Class<?> clazz = (Class<?>) type;
// if (isArrayType(clazz)) {
// return new CollectionSerializer(description, clazz.getComponentType(), mapperContext);
// }
// if (Collection.class.isAssignableFrom(clazz)) {
// return new CollectionSerializer(description, Object.class, mapperContext);
// }
// if (isDirectlyMappedToJsonSchemaType(clazz)) {
// return new DirectTypeSerializer(description, mapperContext);
// }
// if (isPrimitiveType(clazz)) {
// return new PrimitiveSerializer(description, mapperContext);
// }
// if (isEnumType(clazz)) {
// return new ObjectSerializer(description, mapperContext);
// }
// }
//
// return new ObjectSerializer(description, mapperContext);
// }
// }
| import org.json.JSONArray;
import org.json.JSONObject;
import pl.zientarski.*;
import pl.zientarski.serialization.PropertySerializer;
import pl.zientarski.serialization.PropertySerializerFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors; |
@Override
public JSONObject process(final TypeDescription typeDescription, final MapperContext mapperContext) {
final Set<PropertyDescription> properties = typeDescription.getProperties();
final JSONObject result = new JSONObject();
result.put("type", "object");
result.put("additionalProperties", false);
result.put("$schema", JsonSchema4.SCHEMA_REFERENCE);
mapperContext.addDescription(typeDescription.getType(), result);
final Predicate<PropertyDescription> byGetterSetterAndFieldPresence = getByGetterSetterAndFieldPresencePredicate(mapperContext.getPropertyDiscoveryMode());
final Set<PropertyDescription> filteredProperties = properties.stream().filter(byGetterSetterAndFieldPresence).collect(Collectors.toSet());
addProperties(result, filteredProperties, mapperContext);
return result;
}
private Predicate<PropertyDescription> getByGetterSetterAndFieldPresencePredicate(final PropertyDiscoveryMode propertyDiscoveryMode) {
switch (propertyDiscoveryMode) {
case GETTER:
return hasGetter;
case GETTER_WITH_FIELD:
return hasGetter.and(hasField);
}
throw new MappingException("Not supported propertyDiscoveryMode: " + propertyDiscoveryMode);
}
private void addProperties(final JSONObject result, final Set<PropertyDescription> properties, final MapperContext mapperContext) { | // Path: src/main/java/pl/zientarski/serialization/PropertySerializer.java
// public abstract class PropertySerializer {
//
// protected final PropertyDescription propertyDescription;
// protected final MapperContext mapperContext;
//
// public PropertySerializer(final PropertyDescription propertyDescription, final MapperContext mapperContext) {
// this.propertyDescription = propertyDescription;
// this.mapperContext = mapperContext;
// }
//
// public String getPropertyName() {
// return propertyDescription.getName();
// }
//
// public abstract JSONObject toJsonObject();
//
// public boolean isPropertyRequired() {
// return false;
// }
// }
//
// Path: src/main/java/pl/zientarski/serialization/PropertySerializerFactory.java
// public interface PropertySerializerFactory {
// public static PropertySerializer get(final PropertyDescription description, final MapperContext mapperContext) {
// final Type type = description.getType();
// return getForType(type, description, mapperContext);
// }
//
// public static PropertySerializer getForType(final Type type, final PropertyDescription description, final MapperContext mapperContext) {
// if (type instanceof ParameterizedType) {
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// if (Collection.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
// return new CollectionSerializer(description, parameterizedType.getActualTypeArguments()[0], mapperContext);
// }
// return new GenericObjectSerializer(description, mapperContext);
// } else if (type instanceof TypeVariable) {
// final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
// final Type genericType = mapperContext.getGenericTypeByName(typeVariable.getTypeName());
// return getForType(genericType, description, mapperContext);
// } else {
// final Class<?> clazz = (Class<?>) type;
// if (isArrayType(clazz)) {
// return new CollectionSerializer(description, clazz.getComponentType(), mapperContext);
// }
// if (Collection.class.isAssignableFrom(clazz)) {
// return new CollectionSerializer(description, Object.class, mapperContext);
// }
// if (isDirectlyMappedToJsonSchemaType(clazz)) {
// return new DirectTypeSerializer(description, mapperContext);
// }
// if (isPrimitiveType(clazz)) {
// return new PrimitiveSerializer(description, mapperContext);
// }
// if (isEnumType(clazz)) {
// return new ObjectSerializer(description, mapperContext);
// }
// }
//
// return new ObjectSerializer(description, mapperContext);
// }
// }
// Path: src/main/java/pl/zientarski/typehandler/DefaultTypeHandler.java
import org.json.JSONArray;
import org.json.JSONObject;
import pl.zientarski.*;
import pl.zientarski.serialization.PropertySerializer;
import pl.zientarski.serialization.PropertySerializerFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Override
public JSONObject process(final TypeDescription typeDescription, final MapperContext mapperContext) {
final Set<PropertyDescription> properties = typeDescription.getProperties();
final JSONObject result = new JSONObject();
result.put("type", "object");
result.put("additionalProperties", false);
result.put("$schema", JsonSchema4.SCHEMA_REFERENCE);
mapperContext.addDescription(typeDescription.getType(), result);
final Predicate<PropertyDescription> byGetterSetterAndFieldPresence = getByGetterSetterAndFieldPresencePredicate(mapperContext.getPropertyDiscoveryMode());
final Set<PropertyDescription> filteredProperties = properties.stream().filter(byGetterSetterAndFieldPresence).collect(Collectors.toSet());
addProperties(result, filteredProperties, mapperContext);
return result;
}
private Predicate<PropertyDescription> getByGetterSetterAndFieldPresencePredicate(final PropertyDiscoveryMode propertyDiscoveryMode) {
switch (propertyDiscoveryMode) {
case GETTER:
return hasGetter;
case GETTER_WITH_FIELD:
return hasGetter.and(hasField);
}
throw new MappingException("Not supported propertyDiscoveryMode: " + propertyDiscoveryMode);
}
private void addProperties(final JSONObject result, final Set<PropertyDescription> properties, final MapperContext mapperContext) { | final Set<PropertySerializer> serializers = properties.stream().map(p -> PropertySerializerFactory.get(p, mapperContext)).collect(Collectors.toSet()); |
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/typehandler/DefaultTypeHandler.java | // Path: src/main/java/pl/zientarski/serialization/PropertySerializer.java
// public abstract class PropertySerializer {
//
// protected final PropertyDescription propertyDescription;
// protected final MapperContext mapperContext;
//
// public PropertySerializer(final PropertyDescription propertyDescription, final MapperContext mapperContext) {
// this.propertyDescription = propertyDescription;
// this.mapperContext = mapperContext;
// }
//
// public String getPropertyName() {
// return propertyDescription.getName();
// }
//
// public abstract JSONObject toJsonObject();
//
// public boolean isPropertyRequired() {
// return false;
// }
// }
//
// Path: src/main/java/pl/zientarski/serialization/PropertySerializerFactory.java
// public interface PropertySerializerFactory {
// public static PropertySerializer get(final PropertyDescription description, final MapperContext mapperContext) {
// final Type type = description.getType();
// return getForType(type, description, mapperContext);
// }
//
// public static PropertySerializer getForType(final Type type, final PropertyDescription description, final MapperContext mapperContext) {
// if (type instanceof ParameterizedType) {
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// if (Collection.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
// return new CollectionSerializer(description, parameterizedType.getActualTypeArguments()[0], mapperContext);
// }
// return new GenericObjectSerializer(description, mapperContext);
// } else if (type instanceof TypeVariable) {
// final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
// final Type genericType = mapperContext.getGenericTypeByName(typeVariable.getTypeName());
// return getForType(genericType, description, mapperContext);
// } else {
// final Class<?> clazz = (Class<?>) type;
// if (isArrayType(clazz)) {
// return new CollectionSerializer(description, clazz.getComponentType(), mapperContext);
// }
// if (Collection.class.isAssignableFrom(clazz)) {
// return new CollectionSerializer(description, Object.class, mapperContext);
// }
// if (isDirectlyMappedToJsonSchemaType(clazz)) {
// return new DirectTypeSerializer(description, mapperContext);
// }
// if (isPrimitiveType(clazz)) {
// return new PrimitiveSerializer(description, mapperContext);
// }
// if (isEnumType(clazz)) {
// return new ObjectSerializer(description, mapperContext);
// }
// }
//
// return new ObjectSerializer(description, mapperContext);
// }
// }
| import org.json.JSONArray;
import org.json.JSONObject;
import pl.zientarski.*;
import pl.zientarski.serialization.PropertySerializer;
import pl.zientarski.serialization.PropertySerializerFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors; |
@Override
public JSONObject process(final TypeDescription typeDescription, final MapperContext mapperContext) {
final Set<PropertyDescription> properties = typeDescription.getProperties();
final JSONObject result = new JSONObject();
result.put("type", "object");
result.put("additionalProperties", false);
result.put("$schema", JsonSchema4.SCHEMA_REFERENCE);
mapperContext.addDescription(typeDescription.getType(), result);
final Predicate<PropertyDescription> byGetterSetterAndFieldPresence = getByGetterSetterAndFieldPresencePredicate(mapperContext.getPropertyDiscoveryMode());
final Set<PropertyDescription> filteredProperties = properties.stream().filter(byGetterSetterAndFieldPresence).collect(Collectors.toSet());
addProperties(result, filteredProperties, mapperContext);
return result;
}
private Predicate<PropertyDescription> getByGetterSetterAndFieldPresencePredicate(final PropertyDiscoveryMode propertyDiscoveryMode) {
switch (propertyDiscoveryMode) {
case GETTER:
return hasGetter;
case GETTER_WITH_FIELD:
return hasGetter.and(hasField);
}
throw new MappingException("Not supported propertyDiscoveryMode: " + propertyDiscoveryMode);
}
private void addProperties(final JSONObject result, final Set<PropertyDescription> properties, final MapperContext mapperContext) { | // Path: src/main/java/pl/zientarski/serialization/PropertySerializer.java
// public abstract class PropertySerializer {
//
// protected final PropertyDescription propertyDescription;
// protected final MapperContext mapperContext;
//
// public PropertySerializer(final PropertyDescription propertyDescription, final MapperContext mapperContext) {
// this.propertyDescription = propertyDescription;
// this.mapperContext = mapperContext;
// }
//
// public String getPropertyName() {
// return propertyDescription.getName();
// }
//
// public abstract JSONObject toJsonObject();
//
// public boolean isPropertyRequired() {
// return false;
// }
// }
//
// Path: src/main/java/pl/zientarski/serialization/PropertySerializerFactory.java
// public interface PropertySerializerFactory {
// public static PropertySerializer get(final PropertyDescription description, final MapperContext mapperContext) {
// final Type type = description.getType();
// return getForType(type, description, mapperContext);
// }
//
// public static PropertySerializer getForType(final Type type, final PropertyDescription description, final MapperContext mapperContext) {
// if (type instanceof ParameterizedType) {
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// if (Collection.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
// return new CollectionSerializer(description, parameterizedType.getActualTypeArguments()[0], mapperContext);
// }
// return new GenericObjectSerializer(description, mapperContext);
// } else if (type instanceof TypeVariable) {
// final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
// final Type genericType = mapperContext.getGenericTypeByName(typeVariable.getTypeName());
// return getForType(genericType, description, mapperContext);
// } else {
// final Class<?> clazz = (Class<?>) type;
// if (isArrayType(clazz)) {
// return new CollectionSerializer(description, clazz.getComponentType(), mapperContext);
// }
// if (Collection.class.isAssignableFrom(clazz)) {
// return new CollectionSerializer(description, Object.class, mapperContext);
// }
// if (isDirectlyMappedToJsonSchemaType(clazz)) {
// return new DirectTypeSerializer(description, mapperContext);
// }
// if (isPrimitiveType(clazz)) {
// return new PrimitiveSerializer(description, mapperContext);
// }
// if (isEnumType(clazz)) {
// return new ObjectSerializer(description, mapperContext);
// }
// }
//
// return new ObjectSerializer(description, mapperContext);
// }
// }
// Path: src/main/java/pl/zientarski/typehandler/DefaultTypeHandler.java
import org.json.JSONArray;
import org.json.JSONObject;
import pl.zientarski.*;
import pl.zientarski.serialization.PropertySerializer;
import pl.zientarski.serialization.PropertySerializerFactory;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Override
public JSONObject process(final TypeDescription typeDescription, final MapperContext mapperContext) {
final Set<PropertyDescription> properties = typeDescription.getProperties();
final JSONObject result = new JSONObject();
result.put("type", "object");
result.put("additionalProperties", false);
result.put("$schema", JsonSchema4.SCHEMA_REFERENCE);
mapperContext.addDescription(typeDescription.getType(), result);
final Predicate<PropertyDescription> byGetterSetterAndFieldPresence = getByGetterSetterAndFieldPresencePredicate(mapperContext.getPropertyDiscoveryMode());
final Set<PropertyDescription> filteredProperties = properties.stream().filter(byGetterSetterAndFieldPresence).collect(Collectors.toSet());
addProperties(result, filteredProperties, mapperContext);
return result;
}
private Predicate<PropertyDescription> getByGetterSetterAndFieldPresencePredicate(final PropertyDiscoveryMode propertyDiscoveryMode) {
switch (propertyDiscoveryMode) {
case GETTER:
return hasGetter;
case GETTER_WITH_FIELD:
return hasGetter.and(hasField);
}
throw new MappingException("Not supported propertyDiscoveryMode: " + propertyDiscoveryMode);
}
private void addProperties(final JSONObject result, final Set<PropertyDescription> properties, final MapperContext mapperContext) { | final Set<PropertySerializer> serializers = properties.stream().map(p -> PropertySerializerFactory.get(p, mapperContext)).collect(Collectors.toSet()); |
wodzuu/JSONschema4-mapper | src/test/java/pl/zientarski/ParameterizedTypeReferenceTest.java | // Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
| import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf; | package pl.zientarski;
public class ParameterizedTypeReferenceTest {
class Generic<T> {
T property;
public T getProperty() {
return property;
}
}
@Test
public void typeTest() throws Exception {
//when | // Path: src/main/java/pl/zientarski/util/ParameterizedTypeReference.java
// public abstract class ParameterizedTypeReference<T> {
//
// private final ParameterizedType type;
//
// protected ParameterizedTypeReference() {
// final Class<?> parameterizedTypeReferenceSubClass = findParameterizedTypeReferenceSubClass(getClass());
// final Type type = parameterizedTypeReferenceSubClass.getGenericSuperclass();
// final ParameterizedType parameterizedType = (ParameterizedType) type;
// final Type parameterType = parameterizedType.getActualTypeArguments()[0];
// if(!(parameterType instanceof ParameterizedType)){
// throw new IllegalArgumentException("Given type is not generic");
// }
// this.type = (ParameterizedType) parameterType;
// }
//
// private static Class<?> findParameterizedTypeReferenceSubClass(Class<?> child) {
//
// Class<?> parent = child.getSuperclass();
//
// if (Object.class.equals(parent)) {
// throw new IllegalStateException("Expected ParameterizedTypeReference superclass");
// }
// else if (ParameterizedTypeReference.class.equals(parent)) {
// return child;
// }
// else {
// return findParameterizedTypeReferenceSubClass(parent);
// }
// }
//
// public ParameterizedType getType() {
// return this.type;
// }
// }
// Path: src/test/java/pl/zientarski/ParameterizedTypeReferenceTest.java
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import pl.zientarski.util.ParameterizedTypeReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
package pl.zientarski;
public class ParameterizedTypeReferenceTest {
class Generic<T> {
T property;
public T getProperty() {
return property;
}
}
@Test
public void typeTest() throws Exception {
//when | final Type type = new ParameterizedTypeReference<Generic<String>>(){}.getType(); |
wodzuu/JSONschema4-mapper | src/test/java/pl/zientarski/PrimitivePropertiesTest.java | // Path: src/test/java/pl/zientarski/TestUtils.java
// public static Set<String> toStringSet(final JSONArray jsonArray) {
// final Set<String> result = new HashSet<>();
// for (int i = 0; i < jsonArray.length(); i++) {
// result.add(jsonArray.getString(i));
// }
// return result;
// }
| import com.google.common.collect.ImmutableMap;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*;
import static pl.zientarski.JsonSchema4.TYPE_BOOLEAN;
import static pl.zientarski.TestUtils.toStringSet; | return charProperty;
}
}
@Before
public void before() {
mapper = new SchemaMapper();
}
@Test
public void requiredKeySetTest() throws Exception {
//given
//when
final JSONObject schema = mapper.toJsonSchema4(PrimitiveProperties.class);
//then
assertTrue(schema.has("required"));
}
@Test
public void requiredPropertiesTest() throws Exception {
//given
//when
final JSONObject schema = mapper.toJsonSchema4(PrimitiveProperties.class);
//then
assertThat(schema.getJSONArray("required").length(), equalTo(8));
| // Path: src/test/java/pl/zientarski/TestUtils.java
// public static Set<String> toStringSet(final JSONArray jsonArray) {
// final Set<String> result = new HashSet<>();
// for (int i = 0; i < jsonArray.length(); i++) {
// result.add(jsonArray.getString(i));
// }
// return result;
// }
// Path: src/test/java/pl/zientarski/PrimitivePropertiesTest.java
import com.google.common.collect.ImmutableMap;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*;
import static pl.zientarski.JsonSchema4.TYPE_BOOLEAN;
import static pl.zientarski.TestUtils.toStringSet;
return charProperty;
}
}
@Before
public void before() {
mapper = new SchemaMapper();
}
@Test
public void requiredKeySetTest() throws Exception {
//given
//when
final JSONObject schema = mapper.toJsonSchema4(PrimitiveProperties.class);
//then
assertTrue(schema.has("required"));
}
@Test
public void requiredPropertiesTest() throws Exception {
//given
//when
final JSONObject schema = mapper.toJsonSchema4(PrimitiveProperties.class);
//then
assertThat(schema.getJSONArray("required").length(), equalTo(8));
| final Set<String> requiredProperties = toStringSet(schema.getJSONArray("required")); |
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/DefaultReferenceNameProvider.java | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
| import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap; | package pl.zientarski;
public class DefaultReferenceNameProvider implements ReferenceNameProvider {
protected String getPrefix() {
return "";
}
@Override
public String typeReferenceName(final Class<?> clazz, final List<Type> genericTypeArguments) {
final StringBuilder ref = new StringBuilder(); | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
// Path: src/main/java/pl/zientarski/DefaultReferenceNameProvider.java
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap;
package pl.zientarski;
public class DefaultReferenceNameProvider implements ReferenceNameProvider {
protected String getPrefix() {
return "";
}
@Override
public String typeReferenceName(final Class<?> clazz, final List<Type> genericTypeArguments) {
final StringBuilder ref = new StringBuilder(); | if (isPrimitiveTypeWrapper(clazz)) { |
wodzuu/JSONschema4-mapper | src/main/java/pl/zientarski/DefaultReferenceNameProvider.java | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
| import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap; | package pl.zientarski;
public class DefaultReferenceNameProvider implements ReferenceNameProvider {
protected String getPrefix() {
return "";
}
@Override
public String typeReferenceName(final Class<?> clazz, final List<Type> genericTypeArguments) {
final StringBuilder ref = new StringBuilder();
if (isPrimitiveTypeWrapper(clazz)) { | // Path: src/main/java/pl/zientarski/Utils.java
// public static boolean isPrimitiveTypeWrapper(final Class<?> clazz) {
// return primitivesToWrappers.containsKey(clazz);
// }
//
// Path: src/main/java/pl/zientarski/Utils.java
// public static Class<?> unwrap(final Class<?> clazz) {
// if (isPrimitiveTypeWrapper(clazz)) {
// return primitivesToWrappers.get(clazz);
// }
// return clazz;
// }
// Path: src/main/java/pl/zientarski/DefaultReferenceNameProvider.java
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import static pl.zientarski.Utils.isPrimitiveTypeWrapper;
import static pl.zientarski.Utils.unwrap;
package pl.zientarski;
public class DefaultReferenceNameProvider implements ReferenceNameProvider {
protected String getPrefix() {
return "";
}
@Override
public String typeReferenceName(final Class<?> clazz, final List<Type> genericTypeArguments) {
final StringBuilder ref = new StringBuilder();
if (isPrimitiveTypeWrapper(clazz)) { | ref.append(unwrap(clazz).getSimpleName()); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/homefragment/HomeFragmentPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
| import android.content.Context;
import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.List; | package cc.bitky.bitkyshop.fragment.homefragment;
class HomeFragmentPresenter {
private IHomeFragment mView;
private int currentPosition = 0;
private int countLimit = 10;
private Context mContext;
HomeFragmentPresenter(Context context, IHomeFragment view) {
mContext = context;
mView = view;
}
void refreshRecyclerAdapterData(RefreshType type) {
switch (type) {
case Refresh:
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/homefragment/HomeFragmentPresenter.java
import android.content.Context;
import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.List;
package cc.bitky.bitkyshop.fragment.homefragment;
class HomeFragmentPresenter {
private IHomeFragment mView;
private int currentPosition = 0;
private int countLimit = 10;
private Context mContext;
HomeFragmentPresenter(Context context, IHomeFragment view) {
mContext = context;
mView = view;
}
void refreshRecyclerAdapterData(RefreshType type) {
switch (type) {
case Refresh:
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | BmobQuery<Commodity> bmobQuery = new BmobQuery<>(); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/categrayfragment/CategrayFragmentPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/SubCategory.java
// public class SubCategory extends BmobObject {
//
// private String mainCategory;
// private String photoUrl;
// public String photoName;
// private String name;
//
// public String getMainCategory() {
// return mainCategory;
// }
//
// public void setMainCategory(String mainCategory) {
// this.mainCategory = mainCategory;
// }
//
// public String getPhotoUrl() {
// return photoUrl;
// }
//
// public void setPhotoUrl(String photoUrl) {
// this.photoUrl = photoUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhotoName() {
// return photoName;
// }
//
// public void setPhotoName(String photoName) {
// this.photoName = photoName;
// }
// }
| import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import cc.bitky.bitkyshop.bean.SubCategory;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener; | package cc.bitky.bitkyshop.fragment.categrayfragment;
public class CategrayFragmentPresenter {
ICategrayFragment mView;
private List<String> categrayNames;
private int currentPosition = 0;
private int countLimit = 50;
private String currentCategoryStr = "洗浴用品";
public CategrayFragmentPresenter(ICategrayFragment view) {
mView = view;
}
void refreshRecyclerAdapterData(String category, RefreshType type) {
switch (type) {
case Refresh:
if (category != null) {
currentCategoryStr = category;
}
new Thread(new Runnable() {
@Override
public void run() {
currentPosition = 0; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/SubCategory.java
// public class SubCategory extends BmobObject {
//
// private String mainCategory;
// private String photoUrl;
// public String photoName;
// private String name;
//
// public String getMainCategory() {
// return mainCategory;
// }
//
// public void setMainCategory(String mainCategory) {
// this.mainCategory = mainCategory;
// }
//
// public String getPhotoUrl() {
// return photoUrl;
// }
//
// public void setPhotoUrl(String photoUrl) {
// this.photoUrl = photoUrl;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhotoName() {
// return photoName;
// }
//
// public void setPhotoName(String photoName) {
// this.photoName = photoName;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/categrayfragment/CategrayFragmentPresenter.java
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import cc.bitky.bitkyshop.bean.SubCategory;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
package cc.bitky.bitkyshop.fragment.categrayfragment;
public class CategrayFragmentPresenter {
ICategrayFragment mView;
private List<String> categrayNames;
private int currentPosition = 0;
private int countLimit = 50;
private String currentCategoryStr = "洗浴用品";
public CategrayFragmentPresenter(ICategrayFragment view) {
mView = view;
}
void refreshRecyclerAdapterData(String category, RefreshType type) {
switch (type) {
case Refresh:
if (category != null) {
currentCategoryStr = category;
}
new Thread(new Runnable() {
@Override
public void run() {
currentPosition = 0; | BmobQuery<SubCategory> bmobQuery = new BmobQuery<>(); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/orderactivity/OrderManagerPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/Order.java
// public class Order extends BmobObject implements Serializable {
// public static final int NONE = 0;
// public static final int POSTED = 100;
// public static final int CONFIRMED = 110;
//
// public static final int COMPLETED = 200;
//
// public static final int CANCELLED = 500;
// public static final int DELETED = 600;
// private String userObjectId;
// private String username;
// private Integer status;
//
// private ReceiveAddress receiveAddress;
// private List<CommodityOrder> commodityList;
//
// private String name;
// private String phone;
// private String address;
//
// public Order() {
// status = POSTED;
// }
//
// public Order(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// status = POSTED;
// }
//
// /**
// * 设置收货地址以及当前用户信息
// */
// public void setAddressAndUserInfo(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// userObjectId = receiveAddress.getUserObjectId();
// username = receiveAddress.getUsername();
//
// name = receiveAddress.getName();
// phone = receiveAddress.getPhone();
// address = receiveAddress.getAddress();
// status = POSTED;
// }
//
// /**
// * JavaBean是否填写完整
// *
// * @return 填写完整的状态
// */
// public Boolean isDone() {
// if (userObjectId != null
// && username != null
// && receiveAddress != null
// && commodityList != null) {
// return true;
// }
// return false;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Integer getStatus() {
// return status;
// }
//
// public void setStatus(Integer status) {
// this.status = status;
// }
//
// public ReceiveAddress getReceiveAddress() {
// return receiveAddress;
// }
//
// public void setReceiveAddress(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<CommodityOrder> getCommodityList() {
// return commodityList;
// }
//
// public void setCommodityList(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// }
// }
| import cc.bitky.bitkyshop.bean.cart.Order;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import com.socks.library.KLog;
import java.util.List; | package cc.bitky.bitkyshop.fragment.userfragment.orderactivity;
public class OrderManagerPresenter {
OrderManagerActivity activity;
String userObjectId; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/Order.java
// public class Order extends BmobObject implements Serializable {
// public static final int NONE = 0;
// public static final int POSTED = 100;
// public static final int CONFIRMED = 110;
//
// public static final int COMPLETED = 200;
//
// public static final int CANCELLED = 500;
// public static final int DELETED = 600;
// private String userObjectId;
// private String username;
// private Integer status;
//
// private ReceiveAddress receiveAddress;
// private List<CommodityOrder> commodityList;
//
// private String name;
// private String phone;
// private String address;
//
// public Order() {
// status = POSTED;
// }
//
// public Order(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// status = POSTED;
// }
//
// /**
// * 设置收货地址以及当前用户信息
// */
// public void setAddressAndUserInfo(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// userObjectId = receiveAddress.getUserObjectId();
// username = receiveAddress.getUsername();
//
// name = receiveAddress.getName();
// phone = receiveAddress.getPhone();
// address = receiveAddress.getAddress();
// status = POSTED;
// }
//
// /**
// * JavaBean是否填写完整
// *
// * @return 填写完整的状态
// */
// public Boolean isDone() {
// if (userObjectId != null
// && username != null
// && receiveAddress != null
// && commodityList != null) {
// return true;
// }
// return false;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Integer getStatus() {
// return status;
// }
//
// public void setStatus(Integer status) {
// this.status = status;
// }
//
// public ReceiveAddress getReceiveAddress() {
// return receiveAddress;
// }
//
// public void setReceiveAddress(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<CommodityOrder> getCommodityList() {
// return commodityList;
// }
//
// public void setCommodityList(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/orderactivity/OrderManagerPresenter.java
import cc.bitky.bitkyshop.bean.cart.Order;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import com.socks.library.KLog;
import java.util.List;
package cc.bitky.bitkyshop.fragment.userfragment.orderactivity;
public class OrderManagerPresenter {
OrderManagerActivity activity;
String userObjectId; | int status = Order.NONE; |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/addressactivity/AddressOptionPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/ReceiveAddress.java
// public class ReceiveAddress extends BmobObject implements Serializable {
//
// private String userObjectId;
// private String username;
// private String name;
// private String phone;
// private String address;
// private Boolean isDefault;
//
// public ReceiveAddress() {
// }
//
// public ReceiveAddress(String userObjectId, String username, String name, String phone,
// String address) {
// this.userObjectId = userObjectId;
// this.username = username;
// this.name = name;
// this.phone = phone;
// this.address = address;
// isDefault = false;
// }
//
// public ReceiveAddress(String userObjectId, String username, String name, String phone,
// String address, Boolean isDefault) {
// this.userObjectId = userObjectId;
// this.username = username;
// this.name = name;
// this.phone = phone;
// this.address = address;
// this.isDefault = isDefault;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Boolean getDefault() {
// return isDefault;
// }
//
// public void setDefault(Boolean aDefault) {
// isDefault = aDefault;
// }
// }
| import cc.bitky.bitkyshop.bean.cart.ReceiveAddress;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import com.socks.library.KLog;
import java.util.List; | package cc.bitky.bitkyshop.fragment.userfragment.addressactivity;
public class AddressOptionPresenter {
private AddressOptionActivity activity;
public AddressOptionPresenter(AddressOptionActivity activity) {
this.activity = activity;
}
public void getCurrentUserAddress(String userObjectId) { | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/ReceiveAddress.java
// public class ReceiveAddress extends BmobObject implements Serializable {
//
// private String userObjectId;
// private String username;
// private String name;
// private String phone;
// private String address;
// private Boolean isDefault;
//
// public ReceiveAddress() {
// }
//
// public ReceiveAddress(String userObjectId, String username, String name, String phone,
// String address) {
// this.userObjectId = userObjectId;
// this.username = username;
// this.name = name;
// this.phone = phone;
// this.address = address;
// isDefault = false;
// }
//
// public ReceiveAddress(String userObjectId, String username, String name, String phone,
// String address, Boolean isDefault) {
// this.userObjectId = userObjectId;
// this.username = username;
// this.name = name;
// this.phone = phone;
// this.address = address;
// this.isDefault = isDefault;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Boolean getDefault() {
// return isDefault;
// }
//
// public void setDefault(Boolean aDefault) {
// isDefault = aDefault;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/addressactivity/AddressOptionPresenter.java
import cc.bitky.bitkyshop.bean.cart.ReceiveAddress;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import com.socks.library.KLog;
import java.util.List;
package cc.bitky.bitkyshop.fragment.userfragment.addressactivity;
public class AddressOptionPresenter {
private AddressOptionActivity activity;
public AddressOptionPresenter(AddressOptionActivity activity) {
this.activity = activity;
}
public void getCurrentUserAddress(String userObjectId) { | BmobQuery<ReceiveAddress> bmobQuery = new BmobQuery<>(); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/orderactivity/OrderActivityPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/Order.java
// public class Order extends BmobObject implements Serializable {
// public static final int NONE = 0;
// public static final int POSTED = 100;
// public static final int CONFIRMED = 110;
//
// public static final int COMPLETED = 200;
//
// public static final int CANCELLED = 500;
// public static final int DELETED = 600;
// private String userObjectId;
// private String username;
// private Integer status;
//
// private ReceiveAddress receiveAddress;
// private List<CommodityOrder> commodityList;
//
// private String name;
// private String phone;
// private String address;
//
// public Order() {
// status = POSTED;
// }
//
// public Order(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// status = POSTED;
// }
//
// /**
// * 设置收货地址以及当前用户信息
// */
// public void setAddressAndUserInfo(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// userObjectId = receiveAddress.getUserObjectId();
// username = receiveAddress.getUsername();
//
// name = receiveAddress.getName();
// phone = receiveAddress.getPhone();
// address = receiveAddress.getAddress();
// status = POSTED;
// }
//
// /**
// * JavaBean是否填写完整
// *
// * @return 填写完整的状态
// */
// public Boolean isDone() {
// if (userObjectId != null
// && username != null
// && receiveAddress != null
// && commodityList != null) {
// return true;
// }
// return false;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Integer getStatus() {
// return status;
// }
//
// public void setStatus(Integer status) {
// this.status = status;
// }
//
// public ReceiveAddress getReceiveAddress() {
// return receiveAddress;
// }
//
// public void setReceiveAddress(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<CommodityOrder> getCommodityList() {
// return commodityList;
// }
//
// public void setCommodityList(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// }
// }
| import cc.bitky.bitkyshop.bean.cart.Order;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener; | package cc.bitky.bitkyshop.fragment.userfragment.orderactivity;
public class OrderActivityPresenter {
private final OrderActivity activity;
public OrderActivityPresenter(OrderActivity activity) {
this.activity = activity;
}
/**
* 在服务器中更新订单状态
*
* @param orderOrigin 当前本地订单条目
* @param updateStatus 欲更新到的状态
*/ | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/cart/Order.java
// public class Order extends BmobObject implements Serializable {
// public static final int NONE = 0;
// public static final int POSTED = 100;
// public static final int CONFIRMED = 110;
//
// public static final int COMPLETED = 200;
//
// public static final int CANCELLED = 500;
// public static final int DELETED = 600;
// private String userObjectId;
// private String username;
// private Integer status;
//
// private ReceiveAddress receiveAddress;
// private List<CommodityOrder> commodityList;
//
// private String name;
// private String phone;
// private String address;
//
// public Order() {
// status = POSTED;
// }
//
// public Order(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// status = POSTED;
// }
//
// /**
// * 设置收货地址以及当前用户信息
// */
// public void setAddressAndUserInfo(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// userObjectId = receiveAddress.getUserObjectId();
// username = receiveAddress.getUsername();
//
// name = receiveAddress.getName();
// phone = receiveAddress.getPhone();
// address = receiveAddress.getAddress();
// status = POSTED;
// }
//
// /**
// * JavaBean是否填写完整
// *
// * @return 填写完整的状态
// */
// public Boolean isDone() {
// if (userObjectId != null
// && username != null
// && receiveAddress != null
// && commodityList != null) {
// return true;
// }
// return false;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getAddress() {
// return address;
// }
//
// public void setAddress(String address) {
// this.address = address;
// }
//
// public Integer getStatus() {
// return status;
// }
//
// public void setStatus(Integer status) {
// this.status = status;
// }
//
// public ReceiveAddress getReceiveAddress() {
// return receiveAddress;
// }
//
// public void setReceiveAddress(ReceiveAddress receiveAddress) {
// this.receiveAddress = receiveAddress;
// }
//
// public String getUserObjectId() {
// return userObjectId;
// }
//
// public void setUserObjectId(String userObjectId) {
// this.userObjectId = userObjectId;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<CommodityOrder> getCommodityList() {
// return commodityList;
// }
//
// public void setCommodityList(List<CommodityOrder> commodityList) {
// this.commodityList = commodityList;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/orderactivity/OrderActivityPresenter.java
import cc.bitky.bitkyshop.bean.cart.Order;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
package cc.bitky.bitkyshop.fragment.userfragment.orderactivity;
public class OrderActivityPresenter {
private final OrderActivity activity;
public OrderActivityPresenter(OrderActivity activity) {
this.activity = activity;
}
/**
* 在服务器中更新订单状态
*
* @param orderOrigin 当前本地订单条目
* @param updateStatus 欲更新到的状态
*/ | public void updateOrderStatus(final Order orderOrigin, final int updateStatus) { |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/hotfragment/HotFragmentPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
| import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List; | package cc.bitky.bitkyshop.fragment.hotfragment;
class HotFragmentPresenter {
private IHotFragment mView;
private int currentPosition = 0;
private int countLimit = 10;
private String currentCategoryStr = "水果";
HotFragmentPresenter(IHotFragment view) {
mView = view;
}
public List<String> getCategoryNames() {
List<String> strings = new ArrayList<>();
strings.add("水果");
strings.add("烧烤");
strings.add("旅游");
return strings;
}
public void refreshRecyclerAdapterData(String category, RefreshType type) {
switch (type) {
case Refresh:
if (category != null) {
currentCategoryStr = category;
}
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/hotfragment/HotFragmentPresenter.java
import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
package cc.bitky.bitkyshop.fragment.hotfragment;
class HotFragmentPresenter {
private IHotFragment mView;
private int currentPosition = 0;
private int countLimit = 10;
private String currentCategoryStr = "水果";
HotFragmentPresenter(IHotFragment view) {
mView = view;
}
public List<String> getCategoryNames() {
List<String> strings = new ArrayList<>();
strings.add("水果");
strings.add("烧烤");
strings.add("旅游");
return strings;
}
public void refreshRecyclerAdapterData(String category, RefreshType type) {
switch (type) {
case Refresh:
if (category != null) {
currentCategoryStr = category;
}
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | BmobQuery<Commodity> bmobQuery = new BmobQuery<>(); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/categrayfragment/SubCategrayActivityPresenter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
| import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.List; | package cc.bitky.bitkyshop.fragment.categrayfragment;
public class SubCategrayActivityPresenter {
private SubCategoryActivity activity;
private int currentPosition = 0;
private int countLimit = 10;
private String currentSubCategoryStr;
SubCategrayActivityPresenter(SubCategoryActivity activity) {
this.activity = activity;
}
void refreshRecyclerAdapterData(String subCategory, RefreshType type) {
switch (type) {
case Refresh:
if (subCategory != null) {
currentSubCategoryStr = subCategory;
}
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/categrayfragment/SubCategrayActivityPresenter.java
import cc.bitky.bitkyshop.bean.Commodity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import com.socks.library.KLog;
import java.util.List;
package cc.bitky.bitkyshop.fragment.categrayfragment;
public class SubCategrayActivityPresenter {
private SubCategoryActivity activity;
private int currentPosition = 0;
private int countLimit = 10;
private String currentSubCategoryStr;
SubCategrayActivityPresenter(SubCategoryActivity activity) {
this.activity = activity;
}
void refreshRecyclerAdapterData(String subCategory, RefreshType type) {
switch (type) {
case Refresh:
if (subCategory != null) {
currentSubCategoryStr = subCategory;
}
new Thread(new Runnable() {
@Override public void run() {
currentPosition = 0; | BmobQuery<Commodity> bmobQuery = new BmobQuery<>(); |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/utils/BitkyRecyclerAdapter.java | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
| import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import cc.bitky.bitkyshop.R;
import cc.bitky.bitkyshop.bean.Commodity;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List; | package cc.bitky.bitkyshop.utils;
public class BitkyRecyclerAdapter
extends RecyclerView.Adapter<BitkyRecyclerAdapter.BitkyViewHolder> {
private BitkyOnClickListener listener; | // Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/bean/Commodity.java
// public class Commodity extends BmobObject implements Serializable{
// private String BitkyId;
// private Integer BitkyMode;
// private String BitkyModeStr;
// private String Promotion;
// private String AD;
// private String Category;
// private String CategorySub;
// private String Name;
// private Double Price;
// private Integer Count;
// private String Details;
// private String CoverPhotoUrl;
// private List<String> CoverPhotoUrlSet;
// private String CoverPhotoName;
// private List<String> CoverPhotoNameSet;
//
// public String getPromotion() {
// return Promotion;
// }
//
// public void setPromotion(String promotion) {
// Promotion = promotion;
// }
//
// public String getAD() {
// return AD;
// }
//
// public void setAD(String AD) {
// this.AD = AD;
// }
//
// public String getCategorySub() {
// return CategorySub;
// }
//
// public void setCategorySub(String categorySub) {
// CategorySub = categorySub;
// }
//
// public String getBitkyModeStr() {
// return BitkyModeStr;
// }
//
// public void setBitkyModeStr(String bitkyModeStr) {
// BitkyModeStr = bitkyModeStr;
// }
//
// public String getBitkyId() {
// return BitkyId;
// }
//
// public void setBitkyId(String bitkyId) {
// BitkyId = bitkyId;
// }
//
// public Integer getBitkyMode() {
// return BitkyMode;
// }
//
// public void setBitkyMode(Integer bitkyMode) {
// BitkyMode = bitkyMode;
// }
//
// public String getCategory() {
// return Category;
// }
//
// public void setCategory(String category) {
// Category = category;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public Double getPrice() {
// return Price;
// }
//
// public void setPrice(Double price) {
// Price = price;
// }
//
// public Integer getCount() {
// return Count;
// }
//
// public void setCount(Integer count) {
// Count = count;
// }
//
// public String getDetails() {
// return Details;
// }
//
// public void setDetails(String details) {
// Details = details;
// }
//
// public String getCoverPhotoUrl() {
// return CoverPhotoUrl;
// }
//
// public void setCoverPhotoUrl(String coverPhotoUrl) {
// CoverPhotoUrl = coverPhotoUrl;
// }
//
// public List<String> getCoverPhotoUrlSet() {
// return CoverPhotoUrlSet;
// }
//
// public void setCoverPhotoUrlSet(List<String> coverPhotoUrlSet) {
// CoverPhotoUrlSet = coverPhotoUrlSet;
// }
//
// public String getCoverPhotoName() {
// return CoverPhotoName;
// }
//
// public void setCoverPhotoName(String coverPhotoName) {
// CoverPhotoName = coverPhotoName;
// }
//
// public List<String> getCoverPhotoNameSet() {
// return CoverPhotoNameSet;
// }
//
// public void setCoverPhotoNameSet(List<String> coverPhotoNameSet) {
// CoverPhotoNameSet = coverPhotoNameSet;
// }
// }
// Path: Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/utils/BitkyRecyclerAdapter.java
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import cc.bitky.bitkyshop.R;
import cc.bitky.bitkyshop.bean.Commodity;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
package cc.bitky.bitkyshop.utils;
public class BitkyRecyclerAdapter
extends RecyclerView.Adapter<BitkyRecyclerAdapter.BitkyViewHolder> {
private BitkyOnClickListener listener; | private List<Commodity> mDatas; |
softwarespartan/TWS | src/apidemo/TradesPanel.java | // Path: src/apidemo/util/HtmlButton.java
// public class HtmlButton extends JLabel {
// static Color light = new Color( 220, 220, 220);
//
// private String m_text;
// protected boolean m_selected;
// private ActionListener m_al;
// private Color m_bg = getBackground();
//
// public boolean isSelected() { return m_selected; }
//
// public void setSelected( boolean v) { m_selected = v; }
// public void addActionListener(ActionListener v) { m_al = v; }
//
// public HtmlButton( String text) {
// this( text, null);
// }
//
// public HtmlButton( String text, ActionListener v) {
// super( text);
// m_text = text;
// m_al = v;
// setOpaque( true);
// setForeground( Color.blue);
//
// MouseAdapter a = new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// onPressed( e);
// }
// public void mouseReleased(MouseEvent e) {
// onClicked(e);
// setBackground( m_bg);
// }
// public void mouseEntered(MouseEvent e) {
// onEntered(e);
// }
// public void mouseExited(MouseEvent e) {
// onExited();
// }
// @Override public void mouseMoved(MouseEvent e) {
// onMouseMoved( e);
// }
// };
// addMouseListener( a);
// addMouseMotionListener(a);
// setFont( getFont().deriveFont( Font.PLAIN) );
// }
//
// protected void onMouseMoved(MouseEvent e) {
// }
//
// protected void onEntered(MouseEvent e) {
// if (!m_selected) {
// setText( underline( m_text) );
// }
// }
//
// protected void onExited() {
// setText( m_text);
// }
//
// protected void onPressed(MouseEvent e) {
// if (!m_selected) {
// setBackground( light);
// }
// }
//
// protected void onClicked(MouseEvent e) {
// actionPerformed();
// }
//
// protected void actionPerformed() {
// if( m_al != null) {
// m_al.actionPerformed( null);
// }
// }
//
// public static class HtmlRadioButton extends HtmlButton {
// private HashSet<HtmlRadioButton> m_group;
// HtmlRadioButton( String text, HashSet<HtmlRadioButton> group) {
// super( text);
// m_group = group;
// group.add( this);
// }
// @Override protected void actionPerformed() {
// for( HtmlRadioButton but : m_group) {
// but.setSelected( false);
// }
// setSelected( true);
// super.actionPerformed();
// }
// }
//
// static String underline( String str) {
// return String.format( "<html><u>%s</html>", str);
// }
//
// static String bold( String str) {
// return String.format( "<html><b>%s</html>", str);
// }
//
// class B implements Border {
// @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
// }
//
// @Override public Insets getBorderInsets(Component c) {
// return null;
// }
//
// @Override public boolean isBorderOpaque() {
// return false;
// }
// }
// }
//
// Path: src/com/ib/controller/ApiController.java
// public interface ITradeReportHandler {
// void tradeReport(String tradeKey, NewContract contract, Execution execution);
// void tradeReportEnd();
// void commissionReport(String tradeKey, CommissionReport commissionReport);
// }
| import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;
import apidemo.util.HtmlButton;
import com.ib.client.CommissionReport;
import com.ib.client.Execution;
import com.ib.client.ExecutionFilter;
import com.ib.controller.NewContract;
import com.ib.controller.ApiController.ITradeReportHandler; | /* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package apidemo;
public class TradesPanel extends JPanel implements ITradeReportHandler {
private ArrayList<FullExec> m_trades = new ArrayList<FullExec>();
private HashMap<String,FullExec> m_map = new HashMap<String,FullExec>();
private Model m_model = new Model();
TradesPanel() {
JTable table = new JTable( m_model);
JScrollPane scroll = new JScrollPane( table);
scroll.setBorder( new TitledBorder( "Trade Log"));
| // Path: src/apidemo/util/HtmlButton.java
// public class HtmlButton extends JLabel {
// static Color light = new Color( 220, 220, 220);
//
// private String m_text;
// protected boolean m_selected;
// private ActionListener m_al;
// private Color m_bg = getBackground();
//
// public boolean isSelected() { return m_selected; }
//
// public void setSelected( boolean v) { m_selected = v; }
// public void addActionListener(ActionListener v) { m_al = v; }
//
// public HtmlButton( String text) {
// this( text, null);
// }
//
// public HtmlButton( String text, ActionListener v) {
// super( text);
// m_text = text;
// m_al = v;
// setOpaque( true);
// setForeground( Color.blue);
//
// MouseAdapter a = new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// onPressed( e);
// }
// public void mouseReleased(MouseEvent e) {
// onClicked(e);
// setBackground( m_bg);
// }
// public void mouseEntered(MouseEvent e) {
// onEntered(e);
// }
// public void mouseExited(MouseEvent e) {
// onExited();
// }
// @Override public void mouseMoved(MouseEvent e) {
// onMouseMoved( e);
// }
// };
// addMouseListener( a);
// addMouseMotionListener(a);
// setFont( getFont().deriveFont( Font.PLAIN) );
// }
//
// protected void onMouseMoved(MouseEvent e) {
// }
//
// protected void onEntered(MouseEvent e) {
// if (!m_selected) {
// setText( underline( m_text) );
// }
// }
//
// protected void onExited() {
// setText( m_text);
// }
//
// protected void onPressed(MouseEvent e) {
// if (!m_selected) {
// setBackground( light);
// }
// }
//
// protected void onClicked(MouseEvent e) {
// actionPerformed();
// }
//
// protected void actionPerformed() {
// if( m_al != null) {
// m_al.actionPerformed( null);
// }
// }
//
// public static class HtmlRadioButton extends HtmlButton {
// private HashSet<HtmlRadioButton> m_group;
// HtmlRadioButton( String text, HashSet<HtmlRadioButton> group) {
// super( text);
// m_group = group;
// group.add( this);
// }
// @Override protected void actionPerformed() {
// for( HtmlRadioButton but : m_group) {
// but.setSelected( false);
// }
// setSelected( true);
// super.actionPerformed();
// }
// }
//
// static String underline( String str) {
// return String.format( "<html><u>%s</html>", str);
// }
//
// static String bold( String str) {
// return String.format( "<html><b>%s</html>", str);
// }
//
// class B implements Border {
// @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
// }
//
// @Override public Insets getBorderInsets(Component c) {
// return null;
// }
//
// @Override public boolean isBorderOpaque() {
// return false;
// }
// }
// }
//
// Path: src/com/ib/controller/ApiController.java
// public interface ITradeReportHandler {
// void tradeReport(String tradeKey, NewContract contract, Execution execution);
// void tradeReportEnd();
// void commissionReport(String tradeKey, CommissionReport commissionReport);
// }
// Path: src/apidemo/TradesPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;
import apidemo.util.HtmlButton;
import com.ib.client.CommissionReport;
import com.ib.client.Execution;
import com.ib.client.ExecutionFilter;
import com.ib.controller.NewContract;
import com.ib.controller.ApiController.ITradeReportHandler;
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package apidemo;
public class TradesPanel extends JPanel implements ITradeReportHandler {
private ArrayList<FullExec> m_trades = new ArrayList<FullExec>();
private HashMap<String,FullExec> m_map = new HashMap<String,FullExec>();
private Model m_model = new Model();
TradesPanel() {
JTable table = new JTable( m_model);
JScrollPane scroll = new JScrollPane( table);
scroll.setBorder( new TitledBorder( "Trade Log"));
| HtmlButton but = new HtmlButton( "Refresh") { |
softwarespartan/TWS | src/apidemo/ContractDlg.java | // Path: src/apidemo/util/HtmlButton.java
// public class HtmlButton extends JLabel {
// static Color light = new Color( 220, 220, 220);
//
// private String m_text;
// protected boolean m_selected;
// private ActionListener m_al;
// private Color m_bg = getBackground();
//
// public boolean isSelected() { return m_selected; }
//
// public void setSelected( boolean v) { m_selected = v; }
// public void addActionListener(ActionListener v) { m_al = v; }
//
// public HtmlButton( String text) {
// this( text, null);
// }
//
// public HtmlButton( String text, ActionListener v) {
// super( text);
// m_text = text;
// m_al = v;
// setOpaque( true);
// setForeground( Color.blue);
//
// MouseAdapter a = new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// onPressed( e);
// }
// public void mouseReleased(MouseEvent e) {
// onClicked(e);
// setBackground( m_bg);
// }
// public void mouseEntered(MouseEvent e) {
// onEntered(e);
// }
// public void mouseExited(MouseEvent e) {
// onExited();
// }
// @Override public void mouseMoved(MouseEvent e) {
// onMouseMoved( e);
// }
// };
// addMouseListener( a);
// addMouseMotionListener(a);
// setFont( getFont().deriveFont( Font.PLAIN) );
// }
//
// protected void onMouseMoved(MouseEvent e) {
// }
//
// protected void onEntered(MouseEvent e) {
// if (!m_selected) {
// setText( underline( m_text) );
// }
// }
//
// protected void onExited() {
// setText( m_text);
// }
//
// protected void onPressed(MouseEvent e) {
// if (!m_selected) {
// setBackground( light);
// }
// }
//
// protected void onClicked(MouseEvent e) {
// actionPerformed();
// }
//
// protected void actionPerformed() {
// if( m_al != null) {
// m_al.actionPerformed( null);
// }
// }
//
// public static class HtmlRadioButton extends HtmlButton {
// private HashSet<HtmlRadioButton> m_group;
// HtmlRadioButton( String text, HashSet<HtmlRadioButton> group) {
// super( text);
// m_group = group;
// group.add( this);
// }
// @Override protected void actionPerformed() {
// for( HtmlRadioButton but : m_group) {
// but.setSelected( false);
// }
// setSelected( true);
// super.actionPerformed();
// }
// }
//
// static String underline( String str) {
// return String.format( "<html><u>%s</html>", str);
// }
//
// static String bold( String str) {
// return String.format( "<html><b>%s</html>", str);
// }
//
// class B implements Border {
// @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
// }
//
// @Override public Insets getBorderInsets(Component c) {
// return null;
// }
//
// @Override public boolean isBorderOpaque() {
// return false;
// }
// }
// }
| import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import apidemo.util.HtmlButton;
import com.ib.controller.NewContract; | /* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package apidemo;
class ContractDlg extends JDialog {
ContractPanel m_contractPanel;
ContractDlg( JFrame f, NewContract c) {
super( f, true);
m_contractPanel = new ContractPanel( c);
setLayout( new BorderLayout() );
| // Path: src/apidemo/util/HtmlButton.java
// public class HtmlButton extends JLabel {
// static Color light = new Color( 220, 220, 220);
//
// private String m_text;
// protected boolean m_selected;
// private ActionListener m_al;
// private Color m_bg = getBackground();
//
// public boolean isSelected() { return m_selected; }
//
// public void setSelected( boolean v) { m_selected = v; }
// public void addActionListener(ActionListener v) { m_al = v; }
//
// public HtmlButton( String text) {
// this( text, null);
// }
//
// public HtmlButton( String text, ActionListener v) {
// super( text);
// m_text = text;
// m_al = v;
// setOpaque( true);
// setForeground( Color.blue);
//
// MouseAdapter a = new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// onPressed( e);
// }
// public void mouseReleased(MouseEvent e) {
// onClicked(e);
// setBackground( m_bg);
// }
// public void mouseEntered(MouseEvent e) {
// onEntered(e);
// }
// public void mouseExited(MouseEvent e) {
// onExited();
// }
// @Override public void mouseMoved(MouseEvent e) {
// onMouseMoved( e);
// }
// };
// addMouseListener( a);
// addMouseMotionListener(a);
// setFont( getFont().deriveFont( Font.PLAIN) );
// }
//
// protected void onMouseMoved(MouseEvent e) {
// }
//
// protected void onEntered(MouseEvent e) {
// if (!m_selected) {
// setText( underline( m_text) );
// }
// }
//
// protected void onExited() {
// setText( m_text);
// }
//
// protected void onPressed(MouseEvent e) {
// if (!m_selected) {
// setBackground( light);
// }
// }
//
// protected void onClicked(MouseEvent e) {
// actionPerformed();
// }
//
// protected void actionPerformed() {
// if( m_al != null) {
// m_al.actionPerformed( null);
// }
// }
//
// public static class HtmlRadioButton extends HtmlButton {
// private HashSet<HtmlRadioButton> m_group;
// HtmlRadioButton( String text, HashSet<HtmlRadioButton> group) {
// super( text);
// m_group = group;
// group.add( this);
// }
// @Override protected void actionPerformed() {
// for( HtmlRadioButton but : m_group) {
// but.setSelected( false);
// }
// setSelected( true);
// super.actionPerformed();
// }
// }
//
// static String underline( String str) {
// return String.format( "<html><u>%s</html>", str);
// }
//
// static String bold( String str) {
// return String.format( "<html><b>%s</html>", str);
// }
//
// class B implements Border {
// @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
// }
//
// @Override public Insets getBorderInsets(Component c) {
// return null;
// }
//
// @Override public boolean isBorderOpaque() {
// return false;
// }
// }
// }
// Path: src/apidemo/ContractDlg.java
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import apidemo.util.HtmlButton;
import com.ib.controller.NewContract;
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package apidemo;
class ContractDlg extends JDialog {
ContractPanel m_contractPanel;
ContractDlg( JFrame f, NewContract c) {
super( f, true);
m_contractPanel = new ContractPanel( c);
setLayout( new BorderLayout() );
| HtmlButton ok = new HtmlButton( "OK") { |
softwarespartan/TWS | src/apidemo/TopModel.java | // Path: src/com/ib/controller/ApiController.java
// public static class TopMktDataAdapter implements ITopMktDataHandler {
// @Override public void tickPrice(NewTickType tickType, double price, int canAutoExecute) {
// }
// @Override public void tickSize(NewTickType tickType, int size) {
// }
// @Override public void tickString(NewTickType tickType, String value) {
// }
// @Override public void tickSnapshotEnd() {
// }
// @Override public void marketDataType(MktDataType marketDataType) {
// }
// }
| import static com.ib.controller.Formats.fmt;
import static com.ib.controller.Formats.fmtPct;
import static com.ib.controller.Formats.*;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import com.ib.controller.ApiController.TopMktDataAdapter;
import com.ib.controller.Formats;
import com.ib.controller.NewContract;
import com.ib.controller.NewTickType;
import com.ib.controller.Types.MktDataType; | default: return null;
}
}
@Override public Object getValueAt(int rowIn, int col) {
TopRow row = m_rows.get( rowIn);
switch( col) {
case 0: return row.m_description;
case 1: return row.m_bidSize;
case 2: return fmt( row.m_bid);
case 3: return fmt( row.m_ask);
case 4: return row.m_askSize;
case 5: return fmt( row.m_last);
case 6: return fmtTime( row.m_lastTime);
case 7: return row.change();
case 8: return fmt0( row.m_volume);
default: return null;
}
}
public void color(TableCellRenderer rend, int rowIn, Color def) {
TopRow row = m_rows.get( rowIn);
Color c = row.m_frozen ? Color.gray : def;
((JLabel)rend).setForeground( c);
}
public void cancel(int i) {
ApiDemo.INSTANCE.controller().cancelTopMktData( m_rows.get( i) );
}
| // Path: src/com/ib/controller/ApiController.java
// public static class TopMktDataAdapter implements ITopMktDataHandler {
// @Override public void tickPrice(NewTickType tickType, double price, int canAutoExecute) {
// }
// @Override public void tickSize(NewTickType tickType, int size) {
// }
// @Override public void tickString(NewTickType tickType, String value) {
// }
// @Override public void tickSnapshotEnd() {
// }
// @Override public void marketDataType(MktDataType marketDataType) {
// }
// }
// Path: src/apidemo/TopModel.java
import static com.ib.controller.Formats.fmt;
import static com.ib.controller.Formats.fmtPct;
import static com.ib.controller.Formats.*;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import com.ib.controller.ApiController.TopMktDataAdapter;
import com.ib.controller.Formats;
import com.ib.controller.NewContract;
import com.ib.controller.NewTickType;
import com.ib.controller.Types.MktDataType;
default: return null;
}
}
@Override public Object getValueAt(int rowIn, int col) {
TopRow row = m_rows.get( rowIn);
switch( col) {
case 0: return row.m_description;
case 1: return row.m_bidSize;
case 2: return fmt( row.m_bid);
case 3: return fmt( row.m_ask);
case 4: return row.m_askSize;
case 5: return fmt( row.m_last);
case 6: return fmtTime( row.m_lastTime);
case 7: return row.change();
case 8: return fmt0( row.m_volume);
default: return null;
}
}
public void color(TableCellRenderer rend, int rowIn, Color def) {
TopRow row = m_rows.get( rowIn);
Color c = row.m_frozen ? Color.gray : def;
((JLabel)rend).setForeground( c);
}
public void cancel(int i) {
ApiDemo.INSTANCE.controller().cancelTopMktData( m_rows.get( i) );
}
| static class TopRow extends TopMktDataAdapter { |
softwarespartan/TWS | src/com/examples/MarketDepthAdv.java | // Path: src/com/tws/ContractFactory.java
// public class ContractFactory {
//
// public static Contract GenericContract (String symbol){
//
// // init an empty contract
// Contract contract = new Contract();
//
// // set the symbol for the contract
// contract.m_symbol = symbol;
//
// // fill in the contract with default values
// contract.m_conId = 0 ;
// contract.m_secType = null ;
// contract.m_expiry = "" ;
// contract.m_strike = 0.0 ;
// contract.m_right = "" ;
// contract.m_multiplier = "" ;
// contract.m_exchange = "SMART" ;
// contract.m_primaryExch = "ISLAND" ;
// contract.m_currency = "USD" ;
// contract.m_localSymbol = "" ;
// contract.m_tradingClass = "" ;
// contract.m_secIdType = "" ;
// contract.m_secId = null ;
// contract.m_underComp = null ;
// contract.m_comboLegsDescrip = null ;
// contract.m_comboLegs = null ;
// contract.m_includeExpired = false ;
//
// // that's all folks
// return contract;
// }
//
// public static Contract GenericStockContract(String symbol){
//
// // init an empty contract
// Contract contract = ContractFactory.GenericContract(symbol);
//
// // set the security type to stock
// contract.m_secType = Types.SecType.STK.toString();
//
// // that's a [w]rap
// return contract;
// }
//
//
// }
| import com.ib.client.*;
import com.tws.ContractFactory;
import java.util.HashMap;
import java.util.concurrent.*; | }
@Override
public void connectionClosed() {
System.out.println("connection closed ...");
}
});
public final ExecutorService executorService = Executors.newSingleThreadExecutor();
public ContractDetails getContractDetails(Contract contract) throws InterruptedException,ExecutionException {
this.eClientSocket.reqContractDetails(0,contract);
/** Java 8
ContractDetails contractDetails = executorService.submit( () -> results.take() ).get();
*/
ContractDetails contractDetails = executorService.submit( new Callable<ContractDetails>() {
@Override
public ContractDetails call() throws Exception {
return results.take();
}
}).get();
return contractDetails;
}
public void reqMarketDepth(String symbol, int numRows) throws ExecutionException, InterruptedException {
| // Path: src/com/tws/ContractFactory.java
// public class ContractFactory {
//
// public static Contract GenericContract (String symbol){
//
// // init an empty contract
// Contract contract = new Contract();
//
// // set the symbol for the contract
// contract.m_symbol = symbol;
//
// // fill in the contract with default values
// contract.m_conId = 0 ;
// contract.m_secType = null ;
// contract.m_expiry = "" ;
// contract.m_strike = 0.0 ;
// contract.m_right = "" ;
// contract.m_multiplier = "" ;
// contract.m_exchange = "SMART" ;
// contract.m_primaryExch = "ISLAND" ;
// contract.m_currency = "USD" ;
// contract.m_localSymbol = "" ;
// contract.m_tradingClass = "" ;
// contract.m_secIdType = "" ;
// contract.m_secId = null ;
// contract.m_underComp = null ;
// contract.m_comboLegsDescrip = null ;
// contract.m_comboLegs = null ;
// contract.m_includeExpired = false ;
//
// // that's all folks
// return contract;
// }
//
// public static Contract GenericStockContract(String symbol){
//
// // init an empty contract
// Contract contract = ContractFactory.GenericContract(symbol);
//
// // set the security type to stock
// contract.m_secType = Types.SecType.STK.toString();
//
// // that's a [w]rap
// return contract;
// }
//
//
// }
// Path: src/com/examples/MarketDepthAdv.java
import com.ib.client.*;
import com.tws.ContractFactory;
import java.util.HashMap;
import java.util.concurrent.*;
}
@Override
public void connectionClosed() {
System.out.println("connection closed ...");
}
});
public final ExecutorService executorService = Executors.newSingleThreadExecutor();
public ContractDetails getContractDetails(Contract contract) throws InterruptedException,ExecutionException {
this.eClientSocket.reqContractDetails(0,contract);
/** Java 8
ContractDetails contractDetails = executorService.submit( () -> results.take() ).get();
*/
ContractDetails contractDetails = executorService.submit( new Callable<ContractDetails>() {
@Override
public ContractDetails call() throws Exception {
return results.take();
}
}).get();
return contractDetails;
}
public void reqMarketDepth(String symbol, int numRows) throws ExecutionException, InterruptedException {
| Contract contract = ContractFactory.GenericStockContract(symbol); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/verifier/MyColorVerificationTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
| import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
public class MyColorVerificationTest {
@Test
public void en_UK() { | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/verifier/MyColorVerificationTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
public class MyColorVerificationTest {
@Test
public void en_UK() { | IMessageKeyVerifier mcv = new MessageKeyVerifier(Colors.class); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/util/CAL10NResourceBundleFinderTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.util;
public class CAL10NResourceBundleFinderTest {
ResourceBundle rb;
String encoding;
| // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/util/CAL10NResourceBundleFinderTest.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.util;
public class CAL10NResourceBundleFinderTest {
ResourceBundle rb;
String encoding;
| AnnotationExtractorViaEnumClass annotationExtractor = new AnnotationExtractorViaEnumClass(Colors.class); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en")); | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java
import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en")); | mc.getMessage(Colors.BLUE); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en"));
mc.getMessage(Colors.BLUE);
| // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java
import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en"));
mc.getMessage(Colors.BLUE);
| CAL10NBundle initalRB = mc.cache.get(Colors.BLUE.getDeclaringClass().getName()); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en"));
mc.getMessage(Colors.BLUE);
CAL10NBundle initalRB = mc.cache.get(Colors.BLUE.getDeclaringClass().getName());
initalRB.resetCheckTimes(); | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java
// public class CAL10NBundle extends ResourceBundle {
//
// static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
//
// Map<String, String> map = new ConcurrentHashMap<String, String>();
// File hostFile;
// volatile long nextCheck;
// long lastModified;
// CAL10NBundle parent;
//
// public CAL10NBundle(Reader r, File file)
// throws IOException {
// read(r);
// this.hostFile = file;
// nextCheck = System.currentTimeMillis() + CHECK_DELAY;
// }
//
// void read(Reader r) throws IOException {
// Parser p = new Parser(r, map);
// p.parseAndPopulate();
// }
//
//
// public void setParent(CAL10NBundle parent) {
// this.parent = (parent);
// }
//
// public boolean hasChanged() {
// // if the host file is unknown, no point in a check
// if (hostFile == null) {
// return false;
// }
//
// long now = System.currentTimeMillis();
// if (now < nextCheck) {
// return false;
// } else {
// nextCheck = now + CHECK_DELAY;
// if (lastModified != hostFile.lastModified()) {
// lastModified = hostFile.lastModified();
// return true;
// } else {
// return false;
// }
// }
// }
//
// /**
// * WARNING: Used for testing purposes. Do not invoke directly in user code.
// */
// public void resetCheckTimes() {
// nextCheck = 0;
// lastModified = 0;
// }
//
// @Override
// public Enumeration<String> getKeys() {
// Hashtable<String, String> ht = new Hashtable<String, String>(map);
// if(parent != null) {
// ht.putAll(parent.map);
// }
// return ht.keys();
// }
//
// @Override
// protected Object handleGetObject(String key) {
// if (key == null) {
// throw new NullPointerException();
// }
// Object o = map.get(key);
// if(o == null && parent != null) {
// o = parent.handleGetObject(key);
// }
// return o;
// }
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorReloadTest.java
import ch.qos.cal10n.util.CAL10NBundle;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.util.MiscUtil;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorReloadTest {
@Test
public void bundleReload() throws IOException, InterruptedException {
ClassLoader classLoader = this.getClass().getClassLoader();
String resourceCandidate = "colors" + "_" + "en" + ".properties";
URL url = classLoader.getResource(resourceCandidate);
assertNotNull("the problem is in this test, not the code tested", url);
MessageConveyor mc = new MessageConveyor(new Locale("en"));
mc.getMessage(Colors.BLUE);
CAL10NBundle initalRB = mc.cache.get(Colors.BLUE.getDeclaringClass().getName());
initalRB.resetCheckTimes(); | File file = MiscUtil.urlToFile(url); |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinderByClassloader.java
// public class CAL10NBundleFinderByClassloader extends AbstractCAL10NBundleFinder {
//
// final ClassLoader classLoader;
//
// public CAL10NBundleFinderByClassloader(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
//
// protected URL getResource(String resourceCandidate) {
// return classLoader.getResource(resourceCandidate);
// }
// }
| import ch.qos.cal10n.util.AnnotationExtractorViaEnumClass;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.CAL10NBundleFinderByClassloader;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
* Given an enum class, verify that the resource bundles corresponding to a
* given locale contains the correct keys.
*
* @author Ceki Gulcu
*/
public class MessageKeyVerifier extends AbstractMessageKeyVerifier {
final Class<? extends Enum<?>> enumClass;
public MessageKeyVerifier(Class<? extends Enum<?>> enumClass) {
super(enumClass.getName(), new AnnotationExtractorViaEnumClass(enumClass));
this.enumClass = enumClass;
}
public MessageKeyVerifier(String enumTypeAsStr) {
this(buildEnumClass(enumTypeAsStr));
}
static Class<? extends Enum<?>> buildEnumClass(String enumClassAsStr) {
String errMsg = "Failed to find enum class [" + enumClassAsStr + "]";
try {
return (Class<? extends Enum<?>>) Class.forName(enumClassAsStr);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(errMsg, e);
} catch (NoClassDefFoundError e) {
throw new IllegalStateException(errMsg, e);
}
}
protected List<String> extractKeysInEnum() {
List<String> enumKeyList = new ArrayList<String>();
Enum<?>[] enumArray = enumClass.getEnumConstants();
for (Enum<?> e : enumArray) {
enumKeyList.add(e.toString());
}
return enumKeyList;
}
@Override | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinderByClassloader.java
// public class CAL10NBundleFinderByClassloader extends AbstractCAL10NBundleFinder {
//
// final ClassLoader classLoader;
//
// public CAL10NBundleFinderByClassloader(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
//
// protected URL getResource(String resourceCandidate) {
// return classLoader.getResource(resourceCandidate);
// }
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java
import ch.qos.cal10n.util.AnnotationExtractorViaEnumClass;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.CAL10NBundleFinderByClassloader;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
* Given an enum class, verify that the resource bundles corresponding to a
* given locale contains the correct keys.
*
* @author Ceki Gulcu
*/
public class MessageKeyVerifier extends AbstractMessageKeyVerifier {
final Class<? extends Enum<?>> enumClass;
public MessageKeyVerifier(Class<? extends Enum<?>> enumClass) {
super(enumClass.getName(), new AnnotationExtractorViaEnumClass(enumClass));
this.enumClass = enumClass;
}
public MessageKeyVerifier(String enumTypeAsStr) {
this(buildEnumClass(enumTypeAsStr));
}
static Class<? extends Enum<?>> buildEnumClass(String enumClassAsStr) {
String errMsg = "Failed to find enum class [" + enumClassAsStr + "]";
try {
return (Class<? extends Enum<?>>) Class.forName(enumClassAsStr);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(errMsg, e);
} catch (NoClassDefFoundError e) {
throw new IllegalStateException(errMsg, e);
}
}
protected List<String> extractKeysInEnum() {
List<String> enumKeyList = new ArrayList<String>();
Enum<?>[] enumArray = enumClass.getEnumConstants();
for (Enum<?> e : enumArray) {
enumKeyList.add(e.toString());
}
return enumKeyList;
}
@Override | protected CAL10NBundleFinder getResourceBundleFinder() { |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinderByClassloader.java
// public class CAL10NBundleFinderByClassloader extends AbstractCAL10NBundleFinder {
//
// final ClassLoader classLoader;
//
// public CAL10NBundleFinderByClassloader(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
//
// protected URL getResource(String resourceCandidate) {
// return classLoader.getResource(resourceCandidate);
// }
// }
| import ch.qos.cal10n.util.AnnotationExtractorViaEnumClass;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.CAL10NBundleFinderByClassloader;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
* Given an enum class, verify that the resource bundles corresponding to a
* given locale contains the correct keys.
*
* @author Ceki Gulcu
*/
public class MessageKeyVerifier extends AbstractMessageKeyVerifier {
final Class<? extends Enum<?>> enumClass;
public MessageKeyVerifier(Class<? extends Enum<?>> enumClass) {
super(enumClass.getName(), new AnnotationExtractorViaEnumClass(enumClass));
this.enumClass = enumClass;
}
public MessageKeyVerifier(String enumTypeAsStr) {
this(buildEnumClass(enumTypeAsStr));
}
static Class<? extends Enum<?>> buildEnumClass(String enumClassAsStr) {
String errMsg = "Failed to find enum class [" + enumClassAsStr + "]";
try {
return (Class<? extends Enum<?>>) Class.forName(enumClassAsStr);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(errMsg, e);
} catch (NoClassDefFoundError e) {
throw new IllegalStateException(errMsg, e);
}
}
protected List<String> extractKeysInEnum() {
List<String> enumKeyList = new ArrayList<String>();
Enum<?>[] enumArray = enumClass.getEnumConstants();
for (Enum<?> e : enumArray) {
enumKeyList.add(e.toString());
}
return enumKeyList;
}
@Override
protected CAL10NBundleFinder getResourceBundleFinder() { | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinderByClassloader.java
// public class CAL10NBundleFinderByClassloader extends AbstractCAL10NBundleFinder {
//
// final ClassLoader classLoader;
//
// public CAL10NBundleFinderByClassloader(ClassLoader classLoader) {
// this.classLoader = classLoader;
// }
//
//
// protected URL getResource(String resourceCandidate) {
// return classLoader.getResource(resourceCandidate);
// }
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java
import ch.qos.cal10n.util.AnnotationExtractorViaEnumClass;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.CAL10NBundleFinderByClassloader;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
* Given an enum class, verify that the resource bundles corresponding to a
* given locale contains the correct keys.
*
* @author Ceki Gulcu
*/
public class MessageKeyVerifier extends AbstractMessageKeyVerifier {
final Class<? extends Enum<?>> enumClass;
public MessageKeyVerifier(Class<? extends Enum<?>> enumClass) {
super(enumClass.getName(), new AnnotationExtractorViaEnumClass(enumClass));
this.enumClass = enumClass;
}
public MessageKeyVerifier(String enumTypeAsStr) {
this(buildEnumClass(enumTypeAsStr));
}
static Class<? extends Enum<?>> buildEnumClass(String enumClassAsStr) {
String errMsg = "Failed to find enum class [" + enumClassAsStr + "]";
try {
return (Class<? extends Enum<?>>) Class.forName(enumClassAsStr);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(errMsg, e);
} catch (NoClassDefFoundError e) {
throw new IllegalStateException(errMsg, e);
}
}
protected List<String> extractKeysInEnum() {
List<String> enumKeyList = new ArrayList<String>();
Enum<?>[] enumArray = enumClass.getEnumConstants();
for (Enum<?> e : enumArray) {
enumKeyList.add(e.toString());
}
return enumKeyList;
}
@Override
protected CAL10NBundleFinder getResourceBundleFinder() { | return new CAL10NBundleFinderByClassloader(enumClass.getClassLoader()); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
| import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorTest {
@Test
public void smoke_EN() {
MessageConveyor rbbmc = new MessageConveyor(Locale.UK);
String val;
| // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n;
public class MessageConveyorTest {
@Test
public void smoke_EN() {
MessageConveyor rbbmc = new MessageConveyor(Locale.UK);
String val;
| val = rbbmc.getMessage(Colors.BLUE); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
| import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test; | MessageConveyor rbbmc = new MessageConveyor(Locale.UK);
MessageParameterObj mpo;
String val;
mpo = new MessageParameterObj(Colors.BLUE);
val = rbbmc.getMessage(mpo);
assertEquals("violets are blue", val);
mpo = new MessageParameterObj(Colors.GREEN, "apples");
val = rbbmc.getMessage(mpo);
assertEquals("apples are green", val);
}
@Test
public void failedRBLookup() {
MessageConveyor mc = new MessageConveyor(Locale.CHINA);
try {
mc.getMessage(Colors.BLUE);
fail("missing exception");
} catch (MessageConveyorException e) {
assertEquals(
"Failed to locate resource bundle [colors] for locale [zh_CN] for enum type [ch.qos.cal10n.sample.Colors]",
e.getMessage());
}
}
@Test
public void minimal() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH); | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test;
MessageConveyor rbbmc = new MessageConveyor(Locale.UK);
MessageParameterObj mpo;
String val;
mpo = new MessageParameterObj(Colors.BLUE);
val = rbbmc.getMessage(mpo);
assertEquals("violets are blue", val);
mpo = new MessageParameterObj(Colors.GREEN, "apples");
val = rbbmc.getMessage(mpo);
assertEquals("apples are green", val);
}
@Test
public void failedRBLookup() {
MessageConveyor mc = new MessageConveyor(Locale.CHINA);
try {
mc.getMessage(Colors.BLUE);
fail("missing exception");
} catch (MessageConveyorException e) {
assertEquals(
"Failed to locate resource bundle [colors] for locale [zh_CN] for enum type [ch.qos.cal10n.sample.Colors]",
e.getMessage());
}
}
@Test
public void minimal() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH); | assertEquals("A", mc.getMessage(Minimal.A)); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
| import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test; |
mpo = new MessageParameterObj(Colors.GREEN, "apples");
val = rbbmc.getMessage(mpo);
assertEquals("apples are green", val);
}
@Test
public void failedRBLookup() {
MessageConveyor mc = new MessageConveyor(Locale.CHINA);
try {
mc.getMessage(Colors.BLUE);
fail("missing exception");
} catch (MessageConveyorException e) {
assertEquals(
"Failed to locate resource bundle [colors] for locale [zh_CN] for enum type [ch.qos.cal10n.sample.Colors]",
e.getMessage());
}
}
@Test
public void minimal() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH);
assertEquals("A", mc.getMessage(Minimal.A));
}
@Test
public void specialCharacters() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH); | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Labels.java
// @BaseName("labels")
// public enum Labels {
// L0, L1;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
//
// Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Minimal.java
// @BaseName("minimal")
// public enum Minimal {
// A;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/MessageConveyorTest.java
import ch.qos.cal10n.sample.Colors;
import ch.qos.cal10n.sample.Minimal;
import ch.qos.cal10n.sample.Host.OtherColors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Locale;
import ch.qos.cal10n.sample.Labels;
import org.junit.Test;
mpo = new MessageParameterObj(Colors.GREEN, "apples");
val = rbbmc.getMessage(mpo);
assertEquals("apples are green", val);
}
@Test
public void failedRBLookup() {
MessageConveyor mc = new MessageConveyor(Locale.CHINA);
try {
mc.getMessage(Colors.BLUE);
fail("missing exception");
} catch (MessageConveyorException e) {
assertEquals(
"Failed to locate resource bundle [colors] for locale [zh_CN] for enum type [ch.qos.cal10n.sample.Colors]",
e.getMessage());
}
}
@Test
public void minimal() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH);
assertEquals("A", mc.getMessage(Minimal.A));
}
@Test
public void specialCharacters() {
MessageConveyor mc = new MessageConveyor(Locale.ENGLISH); | assertEquals("A label \n with linefeed and unicode", mc.getMessage(Labels.L0)); |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/util/TokenStream.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/Token.java
// enum TokenType {
// KEY,
// SEPARATOR,
// VALUE,
// TRAILING_BACKSLASH,
// EOL;
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import ch.qos.cal10n.MessageConveyorException;
import ch.qos.cal10n.util.Token.TokenType; | }
return tokenList;
}
private void tokenizeLine(List<Token> tokenList, String line) {
int len = line.length();
StringBuilder buf = new StringBuilder();
for (int pointer = 0; pointer < len; pointer++) {
char c = line.charAt(pointer);
switch (state) {
case START:
if (isWhiteSpace(c)) {
// same sate
} else if (c == '#') {
state = State.COMMENT;
return;
} else if (isNonWhiteSpaceSeparator(c)) {
state = State.SEPARATOR;
buf.append(c);
} else {
state = State.KEY;
buf.append(c);
}
break;
case KEY:
if (isWhiteSpace(c) || isNonWhiteSpaceSeparator(c)) {
String lexicalValue = LexicalUtil.convertSpecialCharacters(buf).toString(); | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/Token.java
// enum TokenType {
// KEY,
// SEPARATOR,
// VALUE,
// TRAILING_BACKSLASH,
// EOL;
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/TokenStream.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import ch.qos.cal10n.MessageConveyorException;
import ch.qos.cal10n.util.Token.TokenType;
}
return tokenList;
}
private void tokenizeLine(List<Token> tokenList, String line) {
int len = line.length();
StringBuilder buf = new StringBuilder();
for (int pointer = 0; pointer < len; pointer++) {
char c = line.charAt(pointer);
switch (state) {
case START:
if (isWhiteSpace(c)) {
// same sate
} else if (c == '#') {
state = State.COMMENT;
return;
} else if (isNonWhiteSpaceSeparator(c)) {
state = State.SEPARATOR;
buf.append(c);
} else {
state = State.KEY;
buf.append(c);
}
break;
case KEY:
if (isWhiteSpace(c) || isNonWhiteSpaceSeparator(c)) {
String lexicalValue = LexicalUtil.convertSpecialCharacters(buf).toString(); | tokenList.add(new Token(TokenType.KEY, lexicalValue)); |
qos-ch/cal10n | cal10n-api/src/test/java/ch/qos/cal10n/verifier/MyAllInOneColorVerificationTest.java | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
| import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
*
* @author Ceki Gülcü
*
*/
public class MyAllInOneColorVerificationTest {
@Test
public void all() { | // Path: cal10n-api/src/test/java/ch/qos/cal10n/sample/Colors.java
// @BaseName("colors")
// @LocaleData( { @Locale("en_UK"), @Locale("fr") })
// public enum Colors {
// // sub-class for testing purposes
// RED {
//
// },
// BLUE, GREEN;
// }
// Path: cal10n-api/src/test/java/ch/qos/cal10n/verifier/MyAllInOneColorVerificationTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import ch.qos.cal10n.sample.Colors;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.verifier;
/**
*
* @author Ceki Gülcü
*
*/
public class MyAllInOneColorVerificationTest {
@Test
public void all() { | IMessageKeyVerifier mcv = new MessageKeyVerifier(Colors.class); |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/processor/CAL10NAnnotationProcessor.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/Cal10nError.java
// public class Cal10nError {
//
// enum ErrorType {
// MISSING_BN_ANNOTATION, MISSING_LOCALE_DATA_ANNOTATION,
// FAILED_TO_FIND_RB, EMPTY_RB, EMPTY_ENUM, ABSENT_IN_RB, ABSENT_IN_ENUM;
// }
//
// final ErrorType errorType;
// final String key;
// final Locale locale;
// final String enumClassName;
// final String baseName;
//
// Cal10nError(ErrorType errorType, String key, String enumClassName,
// Locale locale, String baseName) {
// this.errorType = errorType;
// this.key = key;
// this.enumClassName = enumClassName;
// this.locale = locale;
// this.baseName = baseName;
// }
//
// public ErrorType getErrorType() {
// return errorType;
// }
//
// public String getKey() {
// return key;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// @Override
// public String toString() {
// switch (errorType) {
//
// case MISSING_BN_ANNOTATION:
// return "Missing @BaseName annotation in enum type ["
// + enumClassName + "]";
// case MISSING_LOCALE_DATA_ANNOTATION:
// return "Missing or empty @LocaleData annotation in enum type ["
// + enumClassName + "]. See "+MISSING_LOCALE_DATA_ANNOTATION_URL;
// case FAILED_TO_FIND_RB:
// return "Failed to locate resource bundle [" + baseName
// + "] for locale [" + locale + "] for enum type [" + enumClassName
// + "]";
// case EMPTY_RB:
// return "Empty resource bundle named [" + baseName
// + "] for locale [" + locale + "]";
// case EMPTY_ENUM:
// return "Empty enum type [" + enumClassName + "]";
// case ABSENT_IN_ENUM:
// return "Key [" + key + "] present in resource bundle named ["
// + baseName + "] for locale [" + locale
// + "] but absent in enum type [" + enumClassName + "]";
// case ABSENT_IN_RB:
// return "Key [" + key + "] present in enum type [" + enumClassName
// + "] but absent in resource bundle named [" + baseName
// + "] for locale [" + locale + "]";
//
// default:
// throw new IllegalStateException("Impossible to reach here");
// }
// }
// }
| import ch.qos.cal10n.BaseName;
import ch.qos.cal10n.verifier.Cal10nError;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic;
import java.util.List;
import java.util.Set; | package ch.qos.cal10n.verifier.processor;
@SupportedAnnotationTypes("ch.qos.cal10n.BaseName")
@SupportedSourceVersion(SourceVersion.RELEASE_5)
public class CAL10NAnnotationProcessor extends AbstractProcessor {
TypeElement baseNameTypeElement;
Filer filer;
@Override
public void init(ProcessingEnvironment env) {
super.init(env);
note("CAL10NAnnotationProcessor 0.8.1 initialized");
baseNameTypeElement = getType("ch.qos.cal10n.BaseName");
filer = env.getFiler();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> entityAnnotated =
roundEnv.getElementsAnnotatedWith(baseNameTypeElement);
for (TypeElement typeElement : ElementFilter.typesIn(entityAnnotated)) {
verify(typeElement);
}
return false;
}
private void verify(TypeElement typeElementForEnum) {
MessageKeyVerifierByTypeElement modelMessageKeyVerifier = new MessageKeyVerifierByTypeElement(typeElementForEnum, filer);
BaseName baseNameAnnotation = typeElementForEnum.getAnnotation(BaseName.class);
//note("performing verification for basename [" + baseNameAnnotation.value() +"]"); | // Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/Cal10nError.java
// public class Cal10nError {
//
// enum ErrorType {
// MISSING_BN_ANNOTATION, MISSING_LOCALE_DATA_ANNOTATION,
// FAILED_TO_FIND_RB, EMPTY_RB, EMPTY_ENUM, ABSENT_IN_RB, ABSENT_IN_ENUM;
// }
//
// final ErrorType errorType;
// final String key;
// final Locale locale;
// final String enumClassName;
// final String baseName;
//
// Cal10nError(ErrorType errorType, String key, String enumClassName,
// Locale locale, String baseName) {
// this.errorType = errorType;
// this.key = key;
// this.enumClassName = enumClassName;
// this.locale = locale;
// this.baseName = baseName;
// }
//
// public ErrorType getErrorType() {
// return errorType;
// }
//
// public String getKey() {
// return key;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// @Override
// public String toString() {
// switch (errorType) {
//
// case MISSING_BN_ANNOTATION:
// return "Missing @BaseName annotation in enum type ["
// + enumClassName + "]";
// case MISSING_LOCALE_DATA_ANNOTATION:
// return "Missing or empty @LocaleData annotation in enum type ["
// + enumClassName + "]. See "+MISSING_LOCALE_DATA_ANNOTATION_URL;
// case FAILED_TO_FIND_RB:
// return "Failed to locate resource bundle [" + baseName
// + "] for locale [" + locale + "] for enum type [" + enumClassName
// + "]";
// case EMPTY_RB:
// return "Empty resource bundle named [" + baseName
// + "] for locale [" + locale + "]";
// case EMPTY_ENUM:
// return "Empty enum type [" + enumClassName + "]";
// case ABSENT_IN_ENUM:
// return "Key [" + key + "] present in resource bundle named ["
// + baseName + "] for locale [" + locale
// + "] but absent in enum type [" + enumClassName + "]";
// case ABSENT_IN_RB:
// return "Key [" + key + "] present in enum type [" + enumClassName
// + "] but absent in resource bundle named [" + baseName
// + "] for locale [" + locale + "]";
//
// default:
// throw new IllegalStateException("Impossible to reach here");
// }
// }
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/processor/CAL10NAnnotationProcessor.java
import ch.qos.cal10n.BaseName;
import ch.qos.cal10n.verifier.Cal10nError;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic;
import java.util.List;
import java.util.Set;
package ch.qos.cal10n.verifier.processor;
@SupportedAnnotationTypes("ch.qos.cal10n.BaseName")
@SupportedSourceVersion(SourceVersion.RELEASE_5)
public class CAL10NAnnotationProcessor extends AbstractProcessor {
TypeElement baseNameTypeElement;
Filer filer;
@Override
public void init(ProcessingEnvironment env) {
super.init(env);
note("CAL10NAnnotationProcessor 0.8.1 initialized");
baseNameTypeElement = getType("ch.qos.cal10n.BaseName");
filer = env.getFiler();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> entityAnnotated =
roundEnv.getElementsAnnotatedWith(baseNameTypeElement);
for (TypeElement typeElement : ElementFilter.typesIn(entityAnnotated)) {
verify(typeElement);
}
return false;
}
private void verify(TypeElement typeElementForEnum) {
MessageKeyVerifierByTypeElement modelMessageKeyVerifier = new MessageKeyVerifierByTypeElement(typeElementForEnum, filer);
BaseName baseNameAnnotation = typeElementForEnum.getAnnotation(BaseName.class);
//note("performing verification for basename [" + baseNameAnnotation.value() +"]"); | List<Cal10nError> errorList = modelMessageKeyVerifier.verifyAllLocales(); |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/util/Parser.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/Token.java
// enum TokenType {
// KEY,
// SEPARATOR,
// VALUE,
// TRAILING_BACKSLASH,
// EOL;
// }
| import java.util.List;
import java.util.Map;
import ch.qos.cal10n.util.Token.TokenType;
import java.io.Reader; | /*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.util;
/**
*
* @author Ceki Gülcü
*
*/
// Given tokens k,s,v, \, and EOL
// ^ denoting the null token
// here is the grammar
// E = EOL | k s V | E | ^
// V = v EOL | v '\' Vopt
// Vopt = EOL V
public class Parser {
final Reader reader;
final Map<String, String> map;
List<Token> tokenList;
int pointer = 0;
Parser(Reader r, Map<String, String> map) {
this.reader = r;
this.map = map;
TokenStream ts = new TokenStream(reader);
tokenList = ts.tokenize();
}
void parseAndPopulate() {
E();
}
private void E() {
Token t = getNextToken();
if (t == null) {
// we are done
return;
}
switch (t.tokenType) {
case EOL:
break;
case KEY:
String k = t.getValue();
t = getNextToken(); | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/Token.java
// enum TokenType {
// KEY,
// SEPARATOR,
// VALUE,
// TRAILING_BACKSLASH,
// EOL;
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/Parser.java
import java.util.List;
import java.util.Map;
import ch.qos.cal10n.util.Token.TokenType;
import java.io.Reader;
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.util;
/**
*
* @author Ceki Gülcü
*
*/
// Given tokens k,s,v, \, and EOL
// ^ denoting the null token
// here is the grammar
// E = EOL | k s V | E | ^
// V = v EOL | v '\' Vopt
// Vopt = EOL V
public class Parser {
final Reader reader;
final Map<String, String> map;
List<Token> tokenList;
int pointer = 0;
Parser(Reader r, Map<String, String> map) {
this.reader = r;
this.map = map;
TokenStream ts = new TokenStream(reader);
tokenList = ts.tokenize();
}
void parseAndPopulate() {
E();
}
private void E() {
Token t = getNextToken();
if (t == null) {
// we are done
return;
}
switch (t.tokenType) {
case EOL:
break;
case KEY:
String k = t.getValue();
t = getNextToken(); | if (t.tokenType != TokenType.SEPARATOR) { |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*; | package ch.qos.cal10n.verifier;
/**
* Abstract class for verifying that for a given an enum type, the keys match those
* found in the corresponding resource bundles.
* <p/>
* <p>This class contains the bundle verification logic. Logic for extracting locate and key information
* should be provided by derived classes.</p>
*
* @author: Ceki Gulcu
* @since 0.8
*/
abstract public class AbstractMessageKeyVerifier implements IMessageKeyVerifier {
final String enumTypeAsStr; | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java
import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*;
package ch.qos.cal10n.verifier;
/**
* Abstract class for verifying that for a given an enum type, the keys match those
* found in the corresponding resource bundles.
* <p/>
* <p>This class contains the bundle verification logic. Logic for extracting locate and key information
* should be provided by derived classes.</p>
*
* @author: Ceki Gulcu
* @since 0.8
*/
abstract public class AbstractMessageKeyVerifier implements IMessageKeyVerifier {
final String enumTypeAsStr; | final AnnotationExtractor annotationExtractor; |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*; | protected String extractCharsetForLocale(Locale locale) {
return annotationExtractor.extractCharset(locale);
}
abstract protected List<String> extractKeysInEnum();
public String[] getLocaleNames() {
String[] localeNameArray = annotationExtractor.extractLocaleNames();
return localeNameArray;
}
public String getBaseName() {
String rbName = annotationExtractor.getBaseName();
return rbName;
}
public List<Cal10nError> verify(Locale locale) {
List<Cal10nError> errorList = new ArrayList<Cal10nError>();
String baseName = getBaseName();
if (baseName == null) {
errorList.add(new Cal10nError(MISSING_BN_ANNOTATION, "",
enumTypeAsStr, locale, ""));
return errorList;
}
String charset = extractCharsetForLocale(locale);
| // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java
import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*;
protected String extractCharsetForLocale(Locale locale) {
return annotationExtractor.extractCharset(locale);
}
abstract protected List<String> extractKeysInEnum();
public String[] getLocaleNames() {
String[] localeNameArray = annotationExtractor.extractLocaleNames();
return localeNameArray;
}
public String getBaseName() {
String rbName = annotationExtractor.getBaseName();
return rbName;
}
public List<Cal10nError> verify(Locale locale) {
List<Cal10nError> errorList = new ArrayList<Cal10nError>();
String baseName = getBaseName();
if (baseName == null) {
errorList.add(new Cal10nError(MISSING_BN_ANNOTATION, "",
enumTypeAsStr, locale, ""));
return errorList;
}
String charset = extractCharsetForLocale(locale);
| CAL10NBundleFinder cal10NResourceCAL10NBundleFinder = getResourceBundleFinder(); |
qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
| import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*; | strList.add(error.toString());
}
return strList;
}
protected Set<String> buildKeySetFromEnumeration(Enumeration<String> e) {
Set<String> set = new HashSet<String>();
while (e.hasMoreElements()) {
String s = e.nextElement();
set.add(s);
}
return set;
}
/**
* Verify all declared locales in one step.
*/
public List<Cal10nError> verifyAllLocales() {
List<Cal10nError> errorList = new ArrayList<Cal10nError>();
String[] localeNameArray = getLocaleNames();
ErrorFactory errorFactory = new ErrorFactory(enumTypeAsStr, null, getBaseName());
if (localeNameArray == null || localeNameArray.length == 0) {
errorList.add(errorFactory.buildError(MISSING_LOCALE_DATA_ANNOTATION, "*"));
return errorList;
}
for (String localeName : localeNameArray) { | // Path: cal10n-api/src/main/java/ch/qos/cal10n/util/AnnotationExtractor.java
// public interface AnnotationExtractor {
//
// public String getBaseName();
//
// public String[] extractLocaleNames();
//
// public Locale[] extractLocales();
//
// public String extractCharset(java.util.Locale juLocale);
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundleFinder.java
// public interface CAL10NBundleFinder {
// public CAL10NBundle getBundle(String baseName, Locale locale, String charset);
//
// }
//
// Path: cal10n-api/src/main/java/ch/qos/cal10n/util/MiscUtil.java
// public class MiscUtil {
//
// public static Locale toLocale(String localeName) {
// if (localeName == null) {
//
// }
// if (localeName.contains("_")) {
// String[] array = localeName.split("_");
// return new Locale(array[0], array[1]);
// } else {
// return new Locale(localeName);
// }
// }
//
// public static File urlToFile(URL url) {
// if(url.getProtocol() != "file") {
// return null;
// }
// String path = url.getPath();
// if(path == null)
// return null;
// File candidate = new File(path);
// if(candidate.exists()) {
// return candidate;
// } else {
// return null;
// }
// }
//
// }
// Path: cal10n-api/src/main/java/ch/qos/cal10n/verifier/AbstractMessageKeyVerifier.java
import ch.qos.cal10n.util.AnnotationExtractor;
import ch.qos.cal10n.util.CAL10NBundleFinder;
import ch.qos.cal10n.util.MiscUtil;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_LOCALE_DATA_ANNOTATION;
import static ch.qos.cal10n.verifier.Cal10nError.ErrorType.MISSING_BN_ANNOTATION;
import java.util.*;
strList.add(error.toString());
}
return strList;
}
protected Set<String> buildKeySetFromEnumeration(Enumeration<String> e) {
Set<String> set = new HashSet<String>();
while (e.hasMoreElements()) {
String s = e.nextElement();
set.add(s);
}
return set;
}
/**
* Verify all declared locales in one step.
*/
public List<Cal10nError> verifyAllLocales() {
List<Cal10nError> errorList = new ArrayList<Cal10nError>();
String[] localeNameArray = getLocaleNames();
ErrorFactory errorFactory = new ErrorFactory(enumTypeAsStr, null, getBaseName());
if (localeNameArray == null || localeNameArray.length == 0) {
errorList.add(errorFactory.buildError(MISSING_LOCALE_DATA_ANNOTATION, "*"));
return errorList;
}
for (String localeName : localeNameArray) { | Locale locale = MiscUtil.toLocale(localeName); |
Airpy/KeywordDrivenAutoTest | src/main/java/com/keyword/automation/action/CookieKeyword.java | // Path: src/main/java/com/keyword/automation/base/browser/Browsers.java
// public class Browsers {
// private static WebBrowser activeBrowser;
//
// public static WebBrowser getActiveBrowser() {
// return activeBrowser;
// }
//
// public static void setActiveBrowser(WebBrowser activeBrowser) {
// Browsers.activeBrowser = activeBrowser;
// }
//
// /**
// * 创建本地浏览器driver
// *
// * @param browserType 浏览器类型
// * @return WebBrowser对象
// */
// public static WebBrowser createDriver(BrowserType browserType) {
// WebBrowser webBrowser;
// switch (browserType) {
// case Chrome:
// webBrowser = new Chrome();
// break;
// case Firefox:
// webBrowser = new Firefox();
// break;
// case IE:
// webBrowser = new InternetExplorer();
// default:
// webBrowser = new Chrome();
// break;
// }
// setActiveBrowser(webBrowser);
// return webBrowser;
// }
//
// /**
// * 创建远程浏览器driver
// *
// * @param browserType browserType 浏览器类型
// * @param remoteUrl 远程地址
// * @return WebBrowser对象
// */
// public static WebBrowser createDriver(BrowserType browserType, String remoteUrl) {
// WebBrowser webBrowser;
// switch (browserType) {
// case Chrome:
// webBrowser = new Chrome(remoteUrl);
// break;
// case Firefox:
// webBrowser = new Firefox(remoteUrl);
// break;
// case IE:
// webBrowser = new InternetExplorer(remoteUrl);
// default:
// webBrowser = new Chrome(remoteUrl);
// break;
// }
// setActiveBrowser(webBrowser);
// return webBrowser;
// }
// }
//
// Path: src/main/java/com/keyword/automation/base/browser/WebCookies.java
// public class WebCookies {
// // 拼装cookie文件绝对路径
// public static final String cookiePath = System.getProperty("doc.dir") + Constants.COOKIE_FILE_PATH;
//
// /**
// * 把cookie追加写入cookie文件
// *
// * @param isDeleteFirst 是否先删除cookie文件
// */
// public static void writeCookieToFile(Cookie cookie, boolean isDeleteFirst) {
// String strCookie = cookie.getName() + ";" + cookie.getValue() + ";" + cookie.getDomain() + ";"
// + cookie.getPath() + ";" + cookie.getExpiry() + ";" + cookie.isSecure() + ";" + cookie.isHttpOnly();
// if (isDeleteFirst) {
// FileUtils.deleteFile(cookiePath);
// FileUtils.createFile(cookiePath);
// }
// FileUtils.writeFile(cookiePath, strCookie);
// }
//
// /**
// * 把cookies写入cookie文件
// *
// * @param cookies cookie集合
// */
// public static void writeCookiesToFile(Set<Cookie> cookies) {
// FileUtils.deleteFile(cookiePath);
// FileUtils.createFile(cookiePath);
// FileUtils.writeFile(cookiePath, cookies);
// }
//
// /**
// * 从文件中读取cookie加载到WebDriver
// */
// public static Set<Cookie> getAllCookiesFromFile() {
// return FileUtils.getAllCookiesFromFile(cookiePath);
// }
//
// /**
// * 从Cookie文件中根据Cookie名称获取Cookie值
// *
// * @param cookieName Cookie名称
// * @return Cookie值
// */
// public static String getCookieValueByNameFromFile(String cookieName) {
// Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
// String cookieValue = null;
// for (Cookie cookie : cookies) {
// if (cookie.getName().equalsIgnoreCase(cookieName)) {
// cookieValue = cookie.getValue();
// break;
// }
// }
// if (null != cookieValue) {
// return cookieValue;
// } else {
// throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
// }
// }
//
// /**
// * 从Cookie文件中根据Cookie名称获取Cookie
// *
// * @param cookieName Cookie名称
// * @return Cookie对象
// */
// public static Cookie getCookieByNameFromFile(String cookieName) {
// Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
// Cookie tempCookie = null;
// for (Cookie cookie : cookies) {
// if (cookie.getName().equalsIgnoreCase(cookieName)) {
// tempCookie = cookie;
// break;
// }
// }
// if (null != tempCookie) {
// return tempCookie;
// } else {
// throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
// }
// }
// }
| import java.util.Set;
import org.openqa.selenium.Cookie;
import com.keyword.automation.base.browser.Browsers;
import com.keyword.automation.base.browser.WebCookies; | package com.keyword.automation.action;
/**
* 封装Cookie操作关键字
*
* @author Amio_
*/
public class CookieKeyword {
// 不允许被初始化
private CookieKeyword() {
}
/**
* 通过cookieName、cookieValue添加Cookie
*
* @param cookieName Cookie名称
* @param CookieValue Cookie值
*/
public static void addCookie(String cookieName, String CookieValue) { | // Path: src/main/java/com/keyword/automation/base/browser/Browsers.java
// public class Browsers {
// private static WebBrowser activeBrowser;
//
// public static WebBrowser getActiveBrowser() {
// return activeBrowser;
// }
//
// public static void setActiveBrowser(WebBrowser activeBrowser) {
// Browsers.activeBrowser = activeBrowser;
// }
//
// /**
// * 创建本地浏览器driver
// *
// * @param browserType 浏览器类型
// * @return WebBrowser对象
// */
// public static WebBrowser createDriver(BrowserType browserType) {
// WebBrowser webBrowser;
// switch (browserType) {
// case Chrome:
// webBrowser = new Chrome();
// break;
// case Firefox:
// webBrowser = new Firefox();
// break;
// case IE:
// webBrowser = new InternetExplorer();
// default:
// webBrowser = new Chrome();
// break;
// }
// setActiveBrowser(webBrowser);
// return webBrowser;
// }
//
// /**
// * 创建远程浏览器driver
// *
// * @param browserType browserType 浏览器类型
// * @param remoteUrl 远程地址
// * @return WebBrowser对象
// */
// public static WebBrowser createDriver(BrowserType browserType, String remoteUrl) {
// WebBrowser webBrowser;
// switch (browserType) {
// case Chrome:
// webBrowser = new Chrome(remoteUrl);
// break;
// case Firefox:
// webBrowser = new Firefox(remoteUrl);
// break;
// case IE:
// webBrowser = new InternetExplorer(remoteUrl);
// default:
// webBrowser = new Chrome(remoteUrl);
// break;
// }
// setActiveBrowser(webBrowser);
// return webBrowser;
// }
// }
//
// Path: src/main/java/com/keyword/automation/base/browser/WebCookies.java
// public class WebCookies {
// // 拼装cookie文件绝对路径
// public static final String cookiePath = System.getProperty("doc.dir") + Constants.COOKIE_FILE_PATH;
//
// /**
// * 把cookie追加写入cookie文件
// *
// * @param isDeleteFirst 是否先删除cookie文件
// */
// public static void writeCookieToFile(Cookie cookie, boolean isDeleteFirst) {
// String strCookie = cookie.getName() + ";" + cookie.getValue() + ";" + cookie.getDomain() + ";"
// + cookie.getPath() + ";" + cookie.getExpiry() + ";" + cookie.isSecure() + ";" + cookie.isHttpOnly();
// if (isDeleteFirst) {
// FileUtils.deleteFile(cookiePath);
// FileUtils.createFile(cookiePath);
// }
// FileUtils.writeFile(cookiePath, strCookie);
// }
//
// /**
// * 把cookies写入cookie文件
// *
// * @param cookies cookie集合
// */
// public static void writeCookiesToFile(Set<Cookie> cookies) {
// FileUtils.deleteFile(cookiePath);
// FileUtils.createFile(cookiePath);
// FileUtils.writeFile(cookiePath, cookies);
// }
//
// /**
// * 从文件中读取cookie加载到WebDriver
// */
// public static Set<Cookie> getAllCookiesFromFile() {
// return FileUtils.getAllCookiesFromFile(cookiePath);
// }
//
// /**
// * 从Cookie文件中根据Cookie名称获取Cookie值
// *
// * @param cookieName Cookie名称
// * @return Cookie值
// */
// public static String getCookieValueByNameFromFile(String cookieName) {
// Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
// String cookieValue = null;
// for (Cookie cookie : cookies) {
// if (cookie.getName().equalsIgnoreCase(cookieName)) {
// cookieValue = cookie.getValue();
// break;
// }
// }
// if (null != cookieValue) {
// return cookieValue;
// } else {
// throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
// }
// }
//
// /**
// * 从Cookie文件中根据Cookie名称获取Cookie
// *
// * @param cookieName Cookie名称
// * @return Cookie对象
// */
// public static Cookie getCookieByNameFromFile(String cookieName) {
// Set<Cookie> cookies = FileUtils.getAllCookiesFromFile(cookiePath);
// Cookie tempCookie = null;
// for (Cookie cookie : cookies) {
// if (cookie.getName().equalsIgnoreCase(cookieName)) {
// tempCookie = cookie;
// break;
// }
// }
// if (null != tempCookie) {
// return tempCookie;
// } else {
// throw new RuntimeException("cookie文件中不存在cookie名为[" + cookieName + "]的cookie!");
// }
// }
// }
// Path: src/main/java/com/keyword/automation/action/CookieKeyword.java
import java.util.Set;
import org.openqa.selenium.Cookie;
import com.keyword.automation.base.browser.Browsers;
import com.keyword.automation.base.browser.WebCookies;
package com.keyword.automation.action;
/**
* 封装Cookie操作关键字
*
* @author Amio_
*/
public class CookieKeyword {
// 不允许被初始化
private CookieKeyword() {
}
/**
* 通过cookieName、cookieValue添加Cookie
*
* @param cookieName Cookie名称
* @param CookieValue Cookie值
*/
public static void addCookie(String cookieName, String CookieValue) { | Browsers.getActiveBrowser().addCookie(cookieName, CookieValue); |
Airpy/KeywordDrivenAutoTest | src/main/java/com/keyword/automation/base/browser/Browsers.java | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
| import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer; | package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) { | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
// Path: src/main/java/com/keyword/automation/base/browser/Browsers.java
import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer;
package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) { | case Chrome: |
Airpy/KeywordDrivenAutoTest | src/main/java/com/keyword/automation/base/browser/Browsers.java | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
| import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer; | package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) {
case Chrome:
webBrowser = new Chrome();
break; | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
// Path: src/main/java/com/keyword/automation/base/browser/Browsers.java
import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer;
package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) {
case Chrome:
webBrowser = new Chrome();
break; | case Firefox: |
Airpy/KeywordDrivenAutoTest | src/main/java/com/keyword/automation/base/browser/Browsers.java | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
| import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer; | package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) {
case Chrome:
webBrowser = new Chrome();
break;
case Firefox:
webBrowser = new Firefox();
break;
case IE: | // Path: src/main/java/com/keyword/automation/dirver/Chrome.java
// public class Chrome extends WebBrowser {
// /**
// * 本地初始化Chrome浏览器driver
// */
// public Chrome() {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_WIN);
// } else {
// System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + Constants.CHROME_PATH_MAC);
// }
// this.driver = new ChromeDriver();
// }
//
// /**
// * 使用remoteWebDriver远程初始化Chrome浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Chrome(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote Chrome driver.", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/Firefox.java
// public class Firefox extends WebBrowser {
// /**
// * 本地初始化Firefox浏览器driver
// */
// public Firefox() {
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("acceptSslCerts", false);
// FirefoxBrowserProfile firefoxProfile = new FirefoxBrowserProfile();
// String sProfile = firefoxProfile.getDefaultProfile();
// if (sProfile.equals("")) {
// this.driver = new FirefoxDriver();
// } else {
// try {
// FirefoxProfile profile = new FirefoxProfile(new File(sProfile));
// FirefoxBinary firefoxBinary = new FirefoxBinary(new File(firefoxProfile.getFirefoxBinInstallPath()));
// profile.setAcceptUntrustedCertificates(false);
// this.driver = new FirefoxDriver(firefoxBinary, profile);
// } catch (Exception e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// /**
// * 使用remoteWebDriver远程初始化Firefox浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public Firefox(String remoteUrl) {
// try {
// DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start firefox browser,please check!", e);
// }
// }
// }
//
// Path: src/main/java/com/keyword/automation/dirver/InternetExplorer.java
// public class InternetExplorer extends WebBrowser {
// /**
// * 本地初始化IE浏览器driver
// */
// public InternetExplorer() {
// System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + Constants.IE_PATH);
// InternetExplorerDriverService service = (InternetExplorerDriverService) ((InternetExplorerDriverService.Builder) new InternetExplorerDriverService.Builder()
// .usingAnyFreePort()).build();
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);// 关闭保护模式,IE默认为开启模式
// capabilities.setCapability("unexpectedAlertBehaviour", "accept");
// this.driver = new InternetExplorerDriver(service, capabilities);
// }
//
// /**
// * 使用remoteWebDriver远程初始化IE浏览器driver(暂未调测)
// *
// * @param remoteUrl 远程服务器的URL
// */
// public InternetExplorer(String remoteUrl) {
// try {
// DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
// this.driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
// } catch (Throwable e) {
// throw new RuntimeException("Failed to start remote IE driver.", e);
// }
// }
// }
// Path: src/main/java/com/keyword/automation/base/browser/Browsers.java
import com.keyword.automation.dirver.Chrome;
import com.keyword.automation.dirver.Firefox;
import com.keyword.automation.dirver.InternetExplorer;
package com.keyword.automation.base.browser;
/**
* 创建不同类型的driver
*
* @author Amio_
*/
public class Browsers {
private static WebBrowser activeBrowser;
public static WebBrowser getActiveBrowser() {
return activeBrowser;
}
public static void setActiveBrowser(WebBrowser activeBrowser) {
Browsers.activeBrowser = activeBrowser;
}
/**
* 创建本地浏览器driver
*
* @param browserType 浏览器类型
* @return WebBrowser对象
*/
public static WebBrowser createDriver(BrowserType browserType) {
WebBrowser webBrowser;
switch (browserType) {
case Chrome:
webBrowser = new Chrome();
break;
case Firefox:
webBrowser = new Firefox();
break;
case IE: | webBrowser = new InternetExplorer(); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/item/meta/ItemMetaSignalAmplifier.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
| import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
import net.minecraftforge.oredict.ShapedOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading; | package openccsensors.common.item.meta;
public class ItemMetaSignalAmplifier implements IItemMeta, IRequiresIconLoading {
private int id;
private IIcon icon;
public ItemMetaSignalAmplifier(int id) {
this.id = id;
| // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
// Path: src/main/java/openccsensors/common/item/meta/ItemMetaSignalAmplifier.java
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
import net.minecraftforge.oredict.ShapedOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
package openccsensors.common.item.meta;
public class ItemMetaSignalAmplifier implements IItemMeta, IRequiresIconLoading {
private int id;
private IIcon icon;
public ItemMetaSignalAmplifier(int id) {
this.id = id;
| OpenCCSensors.Items.genericItem.addMeta(this); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/client/gui/GuiSensor.java | // Path: src/main/java/openccsensors/common/container/ContainerSensor.java
// public class ContainerSensor extends Container {
//
// private TileEntitySensor sensor;
// private InventoryPlayer inventory;
// private int inventorySize;
//
// public ContainerSensor(InventoryPlayer _inventory, TileEntity _tile) {
//
// sensor = (TileEntitySensor)_tile;
// inventory = _inventory;
// inventorySize = sensor.getSizeInventory();
//
// addSlotToContainer(new Slot(sensor, 0, 8 + 4 * 18, 35));
//
// for (int j = 0; j < 3; j++) {
// for (int i1 = 0; i1 < 9; i1++) {
// addSlotToContainer(new Slot(inventory, i1 + j * 9 + 9,
// 8 + i1 * 18, 84 + j * 18));
// }
// }
//
// for (int k = 0; k < 9; k++) {
// addSlotToContainer(new Slot(inventory, k, 8 + k * 18, 142));
// }
// }
//
// @Override
// public boolean canInteractWith(EntityPlayer player) {
// return sensor.isUseableByPlayer(player);
// }
//
// @Override
// public ItemStack transferStackInSlot(EntityPlayer pl, int i) {
// ItemStack itemstack = null;
// Slot slot = (Slot) inventorySlots.get(i);
// if (slot != null && slot.getHasStack()) {
// ItemStack itemstack1 = slot.getStack();
// itemstack = itemstack1.copy();
// if (i < inventorySize) {
// if (!mergeItemStack(itemstack1, inventorySize, inventorySlots.size(), true))
// return null;
// } else if (!mergeItemStack(itemstack1, 0, inventorySize, false))
// return null;
// if (itemstack1.stackSize == 0) {
// slot.putStack(null);
// } else {
// slot.onSlotChanged();
// }
// }
// return itemstack;
// }
//
// }
| import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import openccsensors.common.container.ContainerSensor;
import org.lwjgl.opengl.GL11; | package openccsensors.client.gui;
public class GuiSensor extends GuiContainer {
public GuiSensor(InventoryPlayer inventory, TileEntity sensor) { | // Path: src/main/java/openccsensors/common/container/ContainerSensor.java
// public class ContainerSensor extends Container {
//
// private TileEntitySensor sensor;
// private InventoryPlayer inventory;
// private int inventorySize;
//
// public ContainerSensor(InventoryPlayer _inventory, TileEntity _tile) {
//
// sensor = (TileEntitySensor)_tile;
// inventory = _inventory;
// inventorySize = sensor.getSizeInventory();
//
// addSlotToContainer(new Slot(sensor, 0, 8 + 4 * 18, 35));
//
// for (int j = 0; j < 3; j++) {
// for (int i1 = 0; i1 < 9; i1++) {
// addSlotToContainer(new Slot(inventory, i1 + j * 9 + 9,
// 8 + i1 * 18, 84 + j * 18));
// }
// }
//
// for (int k = 0; k < 9; k++) {
// addSlotToContainer(new Slot(inventory, k, 8 + k * 18, 142));
// }
// }
//
// @Override
// public boolean canInteractWith(EntityPlayer player) {
// return sensor.isUseableByPlayer(player);
// }
//
// @Override
// public ItemStack transferStackInSlot(EntityPlayer pl, int i) {
// ItemStack itemstack = null;
// Slot slot = (Slot) inventorySlots.get(i);
// if (slot != null && slot.getHasStack()) {
// ItemStack itemstack1 = slot.getStack();
// itemstack = itemstack1.copy();
// if (i < inventorySize) {
// if (!mergeItemStack(itemstack1, inventorySize, inventorySlots.size(), true))
// return null;
// } else if (!mergeItemStack(itemstack1, 0, inventorySize, false))
// return null;
// if (itemstack1.stackSize == 0) {
// slot.putStack(null);
// } else {
// slot.onSlotChanged();
// }
// }
// return itemstack;
// }
//
// }
// Path: src/main/java/openccsensors/client/gui/GuiSensor.java
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import openccsensors.common.container.ContainerSensor;
import org.lwjgl.opengl.GL11;
package openccsensors.client.gui;
public class GuiSensor extends GuiContainer {
public GuiSensor(InventoryPlayer inventory, TileEntity sensor) { | super(new ContainerSensor(inventory, sensor)); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/block/BlockBasicSensor.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
| import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import openccsensors.OpenCCSensors;
import openccsensors.api.IBasicSensor;
import openccsensors.common.sensor.ProximitySensor;
import openccsensors.common.tileentity.basic.TileEntityBasicProximitySensor;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | package openccsensors.common.block;
public class BlockBasicSensor extends BlockContainer {
public static final int PROXIMITY_SENSOR_ID = 0;
public static class Icons {
public static IIcon top;
public static IIcon bottom;
public static IIcon sideAll;
public static IIcon sideOwner;
public static IIcon sidePlayers;
};
public BlockBasicSensor() {
super(Material.ground);
setHardness(0.5F); | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
// Path: src/main/java/openccsensors/common/block/BlockBasicSensor.java
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import openccsensors.OpenCCSensors;
import openccsensors.api.IBasicSensor;
import openccsensors.common.sensor.ProximitySensor;
import openccsensors.common.tileentity.basic.TileEntityBasicProximitySensor;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
package openccsensors.common.block;
public class BlockBasicSensor extends BlockContainer {
public static final int PROXIMITY_SENSOR_ID = 0;
public static class Icons {
public static IIcon top;
public static IIcon bottom;
public static IIcon sideAll;
public static IIcon sideOwner;
public static IIcon sidePlayers;
};
public BlockBasicSensor() {
super(Material.ground);
setHardness(0.5F); | setCreativeTab(OpenCCSensors.tabOpenCCSensors); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/sensor/MagicSensor.java | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
//
// Path: src/main/java/openccsensors/common/util/Mods.java
// public class Mods {
//
// /***
// * IndustrialCraft 2
// */
// public static final boolean IC2 = Loader.isModLoaded("IC2");
//
// /***
// * Applied Energistics
// */
// public static final boolean AE = Loader.isModLoaded("AppliedEnergistics");
//
// /***
// * Thermal Expansion
// */
// public static final boolean TE = Loader.isModLoaded("ThermalExpansion");
//
// /***
// * RotaryCraft
// */
// public static final boolean RC = Loader.isModLoaded("RotaryCraft");
//
// /***
// * ThaumCraft
// */
// public static final boolean TC = Loader.isModLoaded("ThaumCraft");
//
// /***
// * Ars Magica
// */
// public static final boolean AM = Loader.isModLoaded("ArsMagica");
//
// /***
// * RailCraft
// */
// public static final boolean RAIL = Loader.isModLoaded("Railcraft");
//
//
// /***
// * CoFH Core
// */
// private static boolean isCoFHCoreLoaded() {
// try {
// Class cls = Class.forName("cofh.api.energy.IEnergyProvider");
// return true;
// } catch (ClassNotFoundException e) {
// return false;
// }
// }
//
// public static final boolean COFH = isCoFHCoreLoaded();
//
// }
| import java.util.HashMap;
import cpw.mods.fml.common.Loader;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.MagicUtils;
import openccsensors.common.util.Mods; | package openccsensors.common.sensor;
public class MagicSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public boolean isValidTarget(Object tile) { | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
//
// Path: src/main/java/openccsensors/common/util/Mods.java
// public class Mods {
//
// /***
// * IndustrialCraft 2
// */
// public static final boolean IC2 = Loader.isModLoaded("IC2");
//
// /***
// * Applied Energistics
// */
// public static final boolean AE = Loader.isModLoaded("AppliedEnergistics");
//
// /***
// * Thermal Expansion
// */
// public static final boolean TE = Loader.isModLoaded("ThermalExpansion");
//
// /***
// * RotaryCraft
// */
// public static final boolean RC = Loader.isModLoaded("RotaryCraft");
//
// /***
// * ThaumCraft
// */
// public static final boolean TC = Loader.isModLoaded("ThaumCraft");
//
// /***
// * Ars Magica
// */
// public static final boolean AM = Loader.isModLoaded("ArsMagica");
//
// /***
// * RailCraft
// */
// public static final boolean RAIL = Loader.isModLoaded("Railcraft");
//
//
// /***
// * CoFH Core
// */
// private static boolean isCoFHCoreLoaded() {
// try {
// Class cls = Class.forName("cofh.api.energy.IEnergyProvider");
// return true;
// } catch (ClassNotFoundException e) {
// return false;
// }
// }
//
// public static final boolean COFH = isCoFHCoreLoaded();
//
// }
// Path: src/main/java/openccsensors/common/sensor/MagicSensor.java
import java.util.HashMap;
import cpw.mods.fml.common.Loader;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.MagicUtils;
import openccsensors.common.util.Mods;
package openccsensors.common.sensor;
public class MagicSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public boolean isValidTarget(Object tile) { | return (Mods.TC && MagicUtils.isValidAspectTarget(tile)) || |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/sensor/MagicSensor.java | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
//
// Path: src/main/java/openccsensors/common/util/Mods.java
// public class Mods {
//
// /***
// * IndustrialCraft 2
// */
// public static final boolean IC2 = Loader.isModLoaded("IC2");
//
// /***
// * Applied Energistics
// */
// public static final boolean AE = Loader.isModLoaded("AppliedEnergistics");
//
// /***
// * Thermal Expansion
// */
// public static final boolean TE = Loader.isModLoaded("ThermalExpansion");
//
// /***
// * RotaryCraft
// */
// public static final boolean RC = Loader.isModLoaded("RotaryCraft");
//
// /***
// * ThaumCraft
// */
// public static final boolean TC = Loader.isModLoaded("ThaumCraft");
//
// /***
// * Ars Magica
// */
// public static final boolean AM = Loader.isModLoaded("ArsMagica");
//
// /***
// * RailCraft
// */
// public static final boolean RAIL = Loader.isModLoaded("Railcraft");
//
//
// /***
// * CoFH Core
// */
// private static boolean isCoFHCoreLoaded() {
// try {
// Class cls = Class.forName("cofh.api.energy.IEnergyProvider");
// return true;
// } catch (ClassNotFoundException e) {
// return false;
// }
// }
//
// public static final boolean COFH = isCoFHCoreLoaded();
//
// }
| import java.util.HashMap;
import cpw.mods.fml.common.Loader;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.MagicUtils;
import openccsensors.common.util.Mods; | package openccsensors.common.sensor;
public class MagicSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public boolean isValidTarget(Object tile) {
return (Mods.TC && MagicUtils.isValidAspectTarget(tile)) ||
(Mods.AM && MagicUtils.isValidAspectTarget(tile));
}
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntity tile = (TileEntity) obj;
HashMap response = super.getDetails(tile, sensorPos);
if (Mods.TC) {
response.put("Aspects", MagicUtils.getMapOfAspects(world, obj, additional));
}
if (Mods.AM) {
response.putAll(MagicUtils.getMapOfArsMagicaPower(world, obj, additional));
}
return response;
}
@Override | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
//
// Path: src/main/java/openccsensors/common/util/Mods.java
// public class Mods {
//
// /***
// * IndustrialCraft 2
// */
// public static final boolean IC2 = Loader.isModLoaded("IC2");
//
// /***
// * Applied Energistics
// */
// public static final boolean AE = Loader.isModLoaded("AppliedEnergistics");
//
// /***
// * Thermal Expansion
// */
// public static final boolean TE = Loader.isModLoaded("ThermalExpansion");
//
// /***
// * RotaryCraft
// */
// public static final boolean RC = Loader.isModLoaded("RotaryCraft");
//
// /***
// * ThaumCraft
// */
// public static final boolean TC = Loader.isModLoaded("ThaumCraft");
//
// /***
// * Ars Magica
// */
// public static final boolean AM = Loader.isModLoaded("ArsMagica");
//
// /***
// * RailCraft
// */
// public static final boolean RAIL = Loader.isModLoaded("Railcraft");
//
//
// /***
// * CoFH Core
// */
// private static boolean isCoFHCoreLoaded() {
// try {
// Class cls = Class.forName("cofh.api.energy.IEnergyProvider");
// return true;
// } catch (ClassNotFoundException e) {
// return false;
// }
// }
//
// public static final boolean COFH = isCoFHCoreLoaded();
//
// }
// Path: src/main/java/openccsensors/common/sensor/MagicSensor.java
import java.util.HashMap;
import cpw.mods.fml.common.Loader;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.MagicUtils;
import openccsensors.common.util.Mods;
package openccsensors.common.sensor;
public class MagicSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public boolean isValidTarget(Object tile) {
return (Mods.TC && MagicUtils.isValidAspectTarget(tile)) ||
(Mods.AM && MagicUtils.isValidAspectTarget(tile));
}
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntity tile = (TileEntity) obj;
HashMap response = super.getDetails(tile, sensorPos);
if (Mods.TC) {
response.put("Aspects", MagicUtils.getMapOfAspects(world, obj, additional));
}
if (Mods.AM) {
response.putAll(MagicUtils.getMapOfArsMagicaPower(world, obj, additional));
}
return response;
}
@Override | public String[] getCustomMethods(ISensorTier tier) { |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/tileentity/TileEntityGauge.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraftforge.common.util.ForgeDirection;
import openccsensors.OpenCCSensors;
import openccsensors.api.IGaugeSensor;
import openccsensors.api.IMethodCallback;
import openccsensors.common.util.CallbackEventManager;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral; | super.writeToNBT(nbttagcompound);
}
public int getFacing() {
return (worldObj == null) ? 0 : this.getBlockMetadata();
}
public int getPercentage() {
return percentage;
}
@Override
public String getType() {
return "gauge";
}
@Override
public String[] getMethodNames() {
return eventManager.getMethodNames();
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws LuaException, InterruptedException {
return new Object[] {
eventManager.queueMethodCall(computer, method, arguments)
};
}
@Override
public void attach(IComputerAccess computer) { | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
// Path: src/main/java/openccsensors/common/tileentity/TileEntityGauge.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraftforge.common.util.ForgeDirection;
import openccsensors.OpenCCSensors;
import openccsensors.api.IGaugeSensor;
import openccsensors.api.IMethodCallback;
import openccsensors.common.util.CallbackEventManager;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
super.writeToNBT(nbttagcompound);
}
public int getFacing() {
return (worldObj == null) ? 0 : this.getBlockMetadata();
}
public int getPercentage() {
return percentage;
}
@Override
public String getType() {
return "gauge";
}
@Override
public String[] getMethodNames() {
return eventManager.getMethodNames();
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws LuaException, InterruptedException {
return new Object[] {
eventManager.queueMethodCall(computer, method, arguments)
};
}
@Override
public void attach(IComputerAccess computer) { | IMount mount = ComputerCraftAPI.createResourceMount(OpenCCSensors.class, "openccsensors", "openccsensors/mods/OCSLua/lua"); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/item/meta/ItemMetaRangeExtensionAntenna.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
| import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
import net.minecraftforge.oredict.ShapedOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading; | package openccsensors.common.item.meta;
public class ItemMetaRangeExtensionAntenna implements IItemMeta, IRequiresIconLoading {
private int id;
private IIcon icon;
public ItemMetaRangeExtensionAntenna(int id) {
this.id = id;
| // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
// Path: src/main/java/openccsensors/common/item/meta/ItemMetaRangeExtensionAntenna.java
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
import net.minecraftforge.oredict.ShapedOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
package openccsensors.common.item.meta;
public class ItemMetaRangeExtensionAntenna implements IItemMeta, IRequiresIconLoading {
private int id;
private IIcon icon;
public ItemMetaRangeExtensionAntenna(int id) {
this.id = id;
| OpenCCSensors.Items.genericItem.addMeta(this); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/peripheral/LuaMount.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import openccsensors.OpenCCSensors;
import dan200.computercraft.api.filesystem.IMount; | package openccsensors.common.peripheral;
public class LuaMount implements IMount {
@Override
public boolean exists(String path) throws IOException { | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
// Path: src/main/java/openccsensors/common/peripheral/LuaMount.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import openccsensors.OpenCCSensors;
import dan200.computercraft.api.filesystem.IMount;
package openccsensors.common.peripheral;
public class LuaMount implements IMount {
@Override
public boolean exists(String path) throws IOException { | File file = new File(new File(OpenCCSensors.EXTRACTED_LUA_PATH), path); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/item/ItemGeneric.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | package openccsensors.common.item;
public class ItemGeneric extends Item {
private HashMap<Integer, IItemMeta> metaitems = new HashMap<Integer, IItemMeta>();
public ItemGeneric() {
super();
setHasSubtypes(true);
setMaxDamage(0);
setMaxStackSize(64); | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
// Path: src/main/java/openccsensors/common/item/ItemGeneric.java
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
package openccsensors.common.item;
public class ItemGeneric extends Item {
private HashMap<Integer, IItemMeta> metaitems = new HashMap<Integer, IItemMeta>();
public ItemGeneric() {
super();
setHasSubtypes(true);
setMaxDamage(0);
setMaxStackSize(64); | setCreativeTab(OpenCCSensors.tabOpenCCSensors); |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/item/ItemGeneric.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | setMaxStackSize(64);
setCreativeTab(OpenCCSensors.tabOpenCCSensors);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, List subItems) {
OpenCCSensors.turtleUpgradeSensor.addTurtlesToCreative(subItems);
for (Entry<Integer, IItemMeta> entry : metaitems.entrySet()) {
if (entry.getValue().displayInCreative()) {
subItems.add(new ItemStack(item, 1, entry.getKey()));
}
}
}
public void addMeta(IItemMeta meta) {
metaitems.put(meta.getId(), meta);
}
public IItemMeta getMeta(ItemStack stack) {
return getMeta(stack.getItemDamage());
}
public IItemMeta getMeta(int id) {
return metaitems.get(id);
}
@Override
public void registerIcons(IIconRegister iconRegister) {
for (Entry<Integer, IItemMeta> entry : metaitems.entrySet()) { | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/IItemMeta.java
// public interface IItemMeta {
// public int getId();
// public boolean displayInCreative();
// public IIcon getIcon();
// public String getName();
// ItemStack newItemStack(int size);
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
// Path: src/main/java/openccsensors/common/item/ItemGeneric.java
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import openccsensors.OpenCCSensors;
import openccsensors.api.IItemMeta;
import openccsensors.api.IRequiresIconLoading;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
setMaxStackSize(64);
setCreativeTab(OpenCCSensors.tabOpenCCSensors);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, List subItems) {
OpenCCSensors.turtleUpgradeSensor.addTurtlesToCreative(subItems);
for (Entry<Integer, IItemMeta> entry : metaitems.entrySet()) {
if (entry.getValue().displayInCreative()) {
subItems.add(new ItemStack(item, 1, entry.getKey()));
}
}
}
public void addMeta(IItemMeta meta) {
metaitems.put(meta.getId(), meta);
}
public IItemMeta getMeta(ItemStack stack) {
return getMeta(stack.getItemDamage());
}
public IItemMeta getMeta(int id) {
return metaitems.get(id);
}
@Override
public void registerIcons(IIconRegister iconRegister) {
for (Entry<Integer, IItemMeta> entry : metaitems.entrySet()) { | if (entry.getValue() instanceof IRequiresIconLoading) { |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/SensorTier.java | // Path: src/main/java/openccsensors/api/EnumItemRarity.java
// public enum EnumItemRarity {
// COMMON,
// UNCOMMON,
// RARE,
// EPIC
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
| import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import openccsensors.api.EnumItemRarity;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensorTier; | package openccsensors.common;
public class SensorTier implements ISensorTier, IRequiresIconLoading {
private String name; | // Path: src/main/java/openccsensors/api/EnumItemRarity.java
// public enum EnumItemRarity {
// COMMON,
// UNCOMMON,
// RARE,
// EPIC
// }
//
// Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
// Path: src/main/java/openccsensors/common/SensorTier.java
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import openccsensors.api.EnumItemRarity;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensorTier;
package openccsensors.common;
public class SensorTier implements ISensorTier, IRequiresIconLoading {
private String name; | private EnumItemRarity rarity; |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/sensor/SonicSensor.java | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
| import java.util.HashMap;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier; | package openccsensors.common.sensor;
public class SonicSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
private static final int BASE_RANGE = 1;
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
Vec3 target = (Vec3) obj;
int x = (int) target.xCoord;
int y = (int) target.yCoord;
int z = (int) target.zCoord;
Block block = world.getBlock(x, y, z);
HashMap response = new HashMap();
String type = "UNKNOWN";
if (block != null && block.getMaterial() != null) {
if (block.getMaterial().isLiquid()) {
type = "LIQUID";
} else if (block.getMaterial().isSolid()) {
type = "SOLID";
}
}
response.put("Type", type);
HashMap position = new HashMap();
position.put("X", x - sensorPos.posX);
position.put("Y", y - sensorPos.posY);
position.put("Z", z - sensorPos.posZ);
response.put("Position", position);
return response;
}
@Override | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
// Path: src/main/java/openccsensors/common/sensor/SonicSensor.java
import java.util.HashMap;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
package openccsensors.common.sensor;
public class SonicSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
private static final int BASE_RANGE = 1;
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
Vec3 target = (Vec3) obj;
int x = (int) target.xCoord;
int y = (int) target.yCoord;
int z = (int) target.zCoord;
Block block = world.getBlock(x, y, z);
HashMap response = new HashMap();
String type = "UNKNOWN";
if (block != null && block.getMaterial() != null) {
if (block.getMaterial().isLiquid()) {
type = "LIQUID";
} else if (block.getMaterial().isSolid()) {
type = "SOLID";
}
}
response.put("Type", type);
HashMap position = new HashMap();
position.put("X", x - sensorPos.posX);
position.put("Y", y - sensorPos.posY);
position.put("Z", z - sensorPos.posZ);
response.put("Position", position);
return response;
}
@Override | public HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier) { |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/util/RecipeUtils.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/SensorCard.java
// public class SensorCard {
//
// private ISensor sensor;
// private ISensorTier tier;
//
// public SensorCard(ISensor sensor, ISensorTier tier) {
// this.sensor = sensor;
// this.tier = tier;
// }
//
// public ISensorTier getTier() {
// return tier;
// }
//
// public ISensor getSensor() {
// return sensor;
// }
//
// public IIcon getIconForRenderPass(int pass) {
// if (pass == 0) {
// return getSensor().getIcon();
// }
// return getTier().getIcon();
// }
//
// }
| import java.lang.reflect.Field;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.SensorCard; | package openccsensors.common.util;
public class RecipeUtils {
public static void addTier1Recipe(ItemStack input, ItemStack output) {
CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(
output,
new Object[] {
"rpr",
"rrr",
"aaa",
Character.valueOf('r'), new ItemStack((Item)Item.itemRegistry.getObject("redstone")),
Character.valueOf('a'), new ItemStack((Item)Item.itemRegistry.getObject("paper")),
Character.valueOf('p'), input
}
));
}
public static void addTier2Recipe(ItemStack input, ItemStack output) {
CraftingManager.getInstance().getRecipeList().add(new ShapelessOreRecipe(
output,
input, | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/SensorCard.java
// public class SensorCard {
//
// private ISensor sensor;
// private ISensorTier tier;
//
// public SensorCard(ISensor sensor, ISensorTier tier) {
// this.sensor = sensor;
// this.tier = tier;
// }
//
// public ISensorTier getTier() {
// return tier;
// }
//
// public ISensor getSensor() {
// return sensor;
// }
//
// public IIcon getIconForRenderPass(int pass) {
// if (pass == 0) {
// return getSensor().getIcon();
// }
// return getTier().getIcon();
// }
//
// }
// Path: src/main/java/openccsensors/common/util/RecipeUtils.java
import java.lang.reflect.Field;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.SensorCard;
package openccsensors.common.util;
public class RecipeUtils {
public static void addTier1Recipe(ItemStack input, ItemStack output) {
CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(
output,
new Object[] {
"rpr",
"rrr",
"aaa",
Character.valueOf('r'), new ItemStack((Item)Item.itemRegistry.getObject("redstone")),
Character.valueOf('a'), new ItemStack((Item)Item.itemRegistry.getObject("paper")),
Character.valueOf('p'), input
}
));
}
public static void addTier2Recipe(ItemStack input, ItemStack output) {
CraftingManager.getInstance().getRecipeList().add(new ShapelessOreRecipe(
output,
input, | OpenCCSensors.Items.rangeExtensionAntenna.newItemStack(1) |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/util/RecipeUtils.java | // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/SensorCard.java
// public class SensorCard {
//
// private ISensor sensor;
// private ISensorTier tier;
//
// public SensorCard(ISensor sensor, ISensorTier tier) {
// this.sensor = sensor;
// this.tier = tier;
// }
//
// public ISensorTier getTier() {
// return tier;
// }
//
// public ISensor getSensor() {
// return sensor;
// }
//
// public IIcon getIconForRenderPass(int pass) {
// if (pass == 0) {
// return getSensor().getIcon();
// }
// return getTier().getIcon();
// }
//
// }
| import java.lang.reflect.Field;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.SensorCard; |
public static void addGaugeRecipe() {
CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(
new ItemStack(OpenCCSensors.Blocks.gaugeBlock),
new Object[] {
"grm",
Character.valueOf('g'), new ItemStack((Block)Block.blockRegistry.getObject("glass_pane")),
Character.valueOf('r'), new ItemStack((Item)Item.itemRegistry.getObject("redstone")),
Character.valueOf('m'), new ItemStack(getMonitor(), 1, 2)
}
));
}
private static Block getMonitor() {
Block monitor = null;
try {
Class cc = Class.forName("dan200.computercraft.ComputerCraft$Blocks");
if (cc != null) {
Field peripheralField = cc.getDeclaredField("peripheral");
if (peripheralField != null) {
monitor = (Block) peripheralField.get(cc);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return monitor;
}
public static void addProxSensorBlockRecipe() {
| // Path: src/main/java/openccsensors/OpenCCSensors.java
// @Mod( modid = "OCS", name = "OpenCCSensors", version = "1.7.5", dependencies = "required-after:ComputerCraft;after:CCTurtle;after:BuildCraft|Core;after:IC2;after:Thaumcraft;after:AppliedEnergistics;after:RailCraft;after:ArsMagica;after:UniversalElectricity;after:ThermalExpansion;after:RotaryCraft")
// public class OpenCCSensors {
//
// public static class Blocks
// {
// public static BlockSensor sensorBlock;
// public static BlockGauge gaugeBlock;
// public static BlockBasicSensor basicSensorBlock;
// }
//
// public static class Config
// {
// public static int sensorBlockID;
// public static int basicSensorBlockID;
// public static int gaugeBlockID;
// public static int sensorCardID;
// public static int genericItemID;
// public static boolean turtlePeripheralEnabled;
// public static boolean enableAnalytics;
// }
//
// public static class Tiers {
// public static SensorTier tier1;
// public static SensorTier tier2;
// public static SensorTier tier3;
// public static SensorTier tier4;
// }
//
// public static TurtleUpgradeSensor turtleUpgradeSensor;
//
//
// public static class Items
// {
// public static ItemGeneric genericItem;
// public static ItemSensorCard sensorCard;
//
// public static IItemMeta rangeExtensionAntenna;
// public static IItemMeta signalAmplifier;
// public static IItemMeta advancedAmplifier;
// }
//
// public static int renderId;
//
// public static class Sensors {
//
// public static ProximitySensor proximitySensor;
// public static MinecartSensor minecartSensor;
// public static DroppedItemSensor droppedItemSensor;
// public static InventorySensor inventorySensor;
// public static SignSensor signSensor;
// public static SonicSensor sonicSensor;
// public static TankSensor tankSensor;
// public static WorldSensor worldSensor;
// public static MagicSensor magicSensor;
// public static MachineSensor machineSensor;
// public static PowerSensor powerSensor;
// public static CropSensor cropSensor;
// }
//
// public static String LUA_PATH;
// public static String EXTRACTED_LUA_PATH;
//
// public static LuaMount mount = new LuaMount();
//
// public static CreativeTabs tabOpenCCSensors = new CreativeTabs("tabOpenCCSensors") {
// public ItemStack getIconItemStack() {
// return new ItemStack(Blocks.sensorBlock, 1, 0);
// }
//
// @Override
// public Item getTabIconItem() {
// return Items.sensorCard;
// }
// };
//
// @Instance( value = "OCS" )
// public static OpenCCSensors instance;
//
// @SidedProxy( clientSide = "openccsensors.client.ClientProxy", serverSide = "openccsensors.common.CommonProxy" )
// public static CommonProxy proxy;
//
// @EventHandler
// public void init( FMLInitializationEvent evt )
// {
// OCSLog.init();
//
// OCSLog.info( "OpenCCSensors version %s starting", FMLCommonHandler.instance().findContainerFor(instance).getVersion() );
//
// proxy.init();
//
// proxy.registerRenderInformation();
// }
//
// @EventHandler
// public void preInit( FMLPreInitializationEvent evt )
// {
//
// LUA_PATH = "/assets/openccsensors/lua";
// EXTRACTED_LUA_PATH = String.format("mods/OCSLua/%s/lua", FMLCommonHandler.instance().findContainerFor(OpenCCSensors.instance).getVersion());
//
// Configuration configFile = new Configuration(evt.getSuggestedConfigurationFile());
//
// Property prop = configFile.get("general", "turtlePeripheralEnabled", true);
// prop.comment = "Turtle Peripheral Enabled";
// Config.turtlePeripheralEnabled = prop.getBoolean(true);
//
//
// configFile.save();
//
// }
// }
//
// Path: src/main/java/openccsensors/api/SensorCard.java
// public class SensorCard {
//
// private ISensor sensor;
// private ISensorTier tier;
//
// public SensorCard(ISensor sensor, ISensorTier tier) {
// this.sensor = sensor;
// this.tier = tier;
// }
//
// public ISensorTier getTier() {
// return tier;
// }
//
// public ISensor getSensor() {
// return sensor;
// }
//
// public IIcon getIconForRenderPass(int pass) {
// if (pass == 0) {
// return getSensor().getIcon();
// }
// return getTier().getIcon();
// }
//
// }
// Path: src/main/java/openccsensors/common/util/RecipeUtils.java
import java.lang.reflect.Field;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import openccsensors.OpenCCSensors;
import openccsensors.api.SensorCard;
public static void addGaugeRecipe() {
CraftingManager.getInstance().getRecipeList().add(new ShapedOreRecipe(
new ItemStack(OpenCCSensors.Blocks.gaugeBlock),
new Object[] {
"grm",
Character.valueOf('g'), new ItemStack((Block)Block.blockRegistry.getObject("glass_pane")),
Character.valueOf('r'), new ItemStack((Item)Item.itemRegistry.getObject("redstone")),
Character.valueOf('m'), new ItemStack(getMonitor(), 1, 2)
}
));
}
private static Block getMonitor() {
Block monitor = null;
try {
Class cc = Class.forName("dan200.computercraft.ComputerCraft$Blocks");
if (cc != null) {
Field peripheralField = cc.getDeclaredField("peripheral");
if (peripheralField != null) {
monitor = (Block) peripheralField.get(cc);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return monitor;
}
public static void addProxSensorBlockRecipe() {
| Entry<Integer, SensorCard> entry = OpenCCSensors.Items.sensorCard.getEntryForSensorAndTier( |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/sensor/SignSensor.java | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
| import java.util.HashMap;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier; | package openccsensors.common.sensor;
public class SignSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntitySign sign = (TileEntitySign) obj;
HashMap response = super.getDetails(sign, sensorPos);
if (additional) {
String signText = "";
for (int i = 0; i < sign.signText.length; i++) {
signText = signText + sign.signText[i];
if (i < 3 && sign.signText[i] != "") {
signText = signText + " ";
}
}
response.put("Text", signText.trim());
}
return response;
}
@Override
public boolean isValidTarget(Object target) {
return target instanceof TileEntitySign;
}
@Override | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
// Path: src/main/java/openccsensors/common/sensor/SignSensor.java
import java.util.HashMap;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
package openccsensors.common.sensor;
public class SignSensor extends TileSensor implements ISensor, IRequiresIconLoading {
private IIcon icon;
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntitySign sign = (TileEntitySign) obj;
HashMap response = super.getDetails(sign, sensorPos);
if (additional) {
String signText = "";
for (int i = 0; i < sign.signText.length; i++) {
signText = signText + sign.signText[i];
if (i < 3 && sign.signText[i] != "") {
signText = signText + " ";
}
}
response.put("Text", signText.trim());
}
return response;
}
@Override
public boolean isValidTarget(Object target) {
return target instanceof TileEntitySign;
}
@Override | public String[] getCustomMethods(ISensorTier tier) { |
Cloudhunter/OpenCCSensors | src/main/java/openccsensors/common/sensor/TankSensor.java | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
| import java.util.HashMap;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import openccsensors.api.IGaugeSensor;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.TankUtils; | package openccsensors.common.sensor;
public class TankSensor extends TileSensor implements ISensor, IRequiresIconLoading, IGaugeSensor {
private IIcon icon;
private String[] gaugeProperties = new String[] {
"PercentFull"
};
@Override
public boolean isValidTarget(Object tile) {
if (tile instanceof IFluidHandler) {
FluidTankInfo[] tanks = ((IFluidHandler)tile).getTankInfo(ForgeDirection.UNKNOWN);
if (tanks != null) {
return tanks.length > 0;
}
}
return false;
}
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntity tile = (TileEntity) obj;
HashMap response = super.getDetails(tile, sensorPos);
response.put("Tanks", TankUtils.fluidHandlerToMap((IFluidHandler)tile));
return response;
}
@Override | // Path: src/main/java/openccsensors/api/IRequiresIconLoading.java
// public interface IRequiresIconLoading {
// public void loadIcon(IIconRegister iconRegistry);
// }
//
// Path: src/main/java/openccsensors/api/ISensor.java
// public interface ISensor {
// HashMap getDetails(World world, Object obj, ChunkCoordinates location, boolean additional);
// HashMap getTargets(World world, ChunkCoordinates location, ISensorTier tier);
// String[] getCustomMethods(ISensorTier tier);
// Object callCustomMethod(World world, ChunkCoordinates location, int methodID, Object[] args, ISensorTier tier) throws Exception;
// String getName();
// IIcon getIcon();
// ItemStack getUniqueRecipeItem();
// }
//
// Path: src/main/java/openccsensors/api/ISensorTier.java
// public interface ISensorTier {
//
// public EnumItemRarity getRarity();
// public double getMultiplier();
// public String getName();
// public IIcon getIcon();
//
// }
// Path: src/main/java/openccsensors/common/sensor/TankSensor.java
import java.util.HashMap;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import openccsensors.api.IGaugeSensor;
import openccsensors.api.IRequiresIconLoading;
import openccsensors.api.ISensor;
import openccsensors.api.ISensorTier;
import openccsensors.common.util.TankUtils;
package openccsensors.common.sensor;
public class TankSensor extends TileSensor implements ISensor, IRequiresIconLoading, IGaugeSensor {
private IIcon icon;
private String[] gaugeProperties = new String[] {
"PercentFull"
};
@Override
public boolean isValidTarget(Object tile) {
if (tile instanceof IFluidHandler) {
FluidTankInfo[] tanks = ((IFluidHandler)tile).getTankInfo(ForgeDirection.UNKNOWN);
if (tanks != null) {
return tanks.length > 0;
}
}
return false;
}
@Override
public HashMap getDetails(World world, Object obj, ChunkCoordinates sensorPos, boolean additional) {
TileEntity tile = (TileEntity) obj;
HashMap response = super.getDetails(tile, sensorPos);
response.put("Tanks", TankUtils.fluidHandlerToMap((IFluidHandler)tile));
return response;
}
@Override | public String[] getCustomMethods(ISensorTier tier) { |
tonikolaba/MrTower | src/al/artofsoul/data/MrTower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
| import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger; | package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
// Path: src/al/artofsoul/data/MrTower.java
import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger;
package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls | BeginSession(); |
tonikolaba/MrTower | src/al/artofsoul/data/MrTower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
| import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger; | package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
// main game loop
while (!Display.isCloseRequested()) { | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
// Path: src/al/artofsoul/data/MrTower.java
import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger;
package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
// main game loop
while (!Display.isCloseRequested()) { | Ora.update(); |
tonikolaba/MrTower | src/al/artofsoul/data/MrTower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
| import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger; | package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
// main game loop
while (!Display.isCloseRequested()) {
Ora.update(); | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void BeginSession(){
//
// Display.setTitle("Mr Tower");
// try {
// Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
// Display.create();
// } catch (LWJGLException e) {
// e.printStackTrace();
// }
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, WIDTH, HEIGHT, 0, 1, -1); //camera that project the screen
// glMatrixMode(GL_MODELVIEW);
// glEnable(GL_TEXTURE_2D);
// glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public class Ora {
//
// private static boolean paused = false;
// public static long lastFrame, totalTime;
// public static float d = 0, multiplier = 1;
//
//
// public static long merrKohen(){
// return Sys.getTime() * 1000 / Sys.getTimerResolution();
// }
//
// public static float merrDelta(){
// long currentTime = merrKohen();
// int delta = (int) (currentTime - lastFrame);
// lastFrame = merrKohen();
// //System.out.println(delta * 0.01f);
// if (delta * 0.001f > 0.05f)
// return 0.05f;
// return delta * 0.001f;
// }
//
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
//
// public static float TotalTime (){
// return totalTime;
// }
//
// public static float Multiplier(){
// return multiplier;
// }
//
// public static void update(){
// d = merrDelta();
// totalTime += d; // njesoj: totalTime = totalTime + d;
//
// }
//
// public static void ChangeMultiplier(float change){
// if (multiplier + change < -1 && multiplier + change > 7){
// } else {
// multiplier += change;
// }
//
// }
//
// public static void Pause(){
// if (paused)
// paused = false;
// else
// paused = true;
// }
//
// }
//
// Path: src/al/artofsoul/ndihma/StateManger.java
// public class StateManger {
//
// public static enum GameState {
// MAINMENU, GAME, EDITOR
// }
//
// public static GameState gameState = GameState.MAINMENU;
// public static MainMenu mainMenu;
// public static Game game;
// public static Editor editor;
//
// public static long nextSecond = System.currentTimeMillis() + 1000;
// public static int framesInLastSecond = 0;
// public static int framesInCurrentSecond = 0;
//
// static PllakaFusha map = LoadMap("res/map/harta"); // when the map is reading
//
// /*
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
// {0, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
// {0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
// */
//
//
// public static void update(){
// switch(gameState){
// case MAINMENU:
// if (mainMenu == null)
// mainMenu = new MainMenu();
// mainMenu.update();
// break;
// case GAME:
// if (game == null)
// game = new Game(map);
// game.update();
// break;
// case EDITOR:
// if (editor == null)
// editor = new Editor();
// editor.update();
// break;
// }
//
// long currentTime = System.currentTimeMillis();
// if (currentTime > nextSecond) {
// nextSecond += 1000;
// framesInLastSecond = framesInCurrentSecond;
// framesInCurrentSecond = 0;
// System.out.println(framesInLastSecond + "fps");
// }
// framesInCurrentSecond++;
// }
//
// public static void setState(GameState newState) {
// gameState = newState;
// }
//
// }
// Path: src/al/artofsoul/data/MrTower.java
import static al.artofsoul.ndihma.Artist.BeginSession;
import org.lwjgl.opengl.Display;
import al.artofsoul.ndihma.Ora;
import al.artofsoul.ndihma.StateManger;
package al.artofsoul.data;
public class MrTower {
public MrTower(){
//Call static method in Artist class to initialize OpenGL calls
BeginSession();
// main game loop
while (!Display.isCloseRequested()) {
Ora.update(); | StateManger.update(); |
tonikolaba/MrTower | src/al/artofsoul/data/Tower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
| import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture; | private float findDistance(Armiku e) {
float xDistance = Math.abs(e.getX() - x);
float yDistance = Math.abs(e.getY() - y);
return xDistance + yDistance;
}
private float calculateAngle () {
double angleTemp = Math.atan2(target.getY() - y, target.getX() - x);
return (float) Math.toDegrees(angleTemp) - 90;
}
//abstarct method for 'shoot', must be override in subclasses
public abstract void shoot (Armiku target);
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
| // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
// Path: src/al/artofsoul/data/Tower.java
import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture;
private float findDistance(Armiku e) {
float xDistance = Math.abs(e.getX() - x);
float yDistance = Math.abs(e.getY() - y);
return xDistance + yDistance;
}
private float calculateAngle () {
double angleTemp = Math.atan2(target.getY() - y, target.getX() - x);
return (float) Math.toDegrees(angleTemp) - 90;
}
//abstarct method for 'shoot', must be override in subclasses
public abstract void shoot (Armiku target);
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
| timeSinceLastShot += Delta(); |
tonikolaba/MrTower | src/al/artofsoul/data/Tower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
| import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture; | }
//abstarct method for 'shoot', must be override in subclasses
public abstract void shoot (Armiku target);
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
timeSinceLastShot += Delta();
for (Projectile p: projectiles)
p.update();
draw();
}
public void draw() { | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
// Path: src/al/artofsoul/data/Tower.java
import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture;
}
//abstarct method for 'shoot', must be override in subclasses
public abstract void shoot (Armiku target);
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
timeSinceLastShot += Delta();
for (Projectile p: projectiles)
p.update();
draw();
}
public void draw() { | VizatoKatrorTex(textures[0], x, y, width, height); |
tonikolaba/MrTower | src/al/artofsoul/data/Tower.java | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
| import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture; |
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
timeSinceLastShot += Delta();
for (Projectile p: projectiles)
p.update();
draw();
}
public void draw() {
VizatoKatrorTex(textures[0], x, y, width, height);
if (textures.length > 1)
for(int i = 1; i < textures.length; i++) | // Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTex(Texture tex, float x, float y, float width, float height){
// tex.bind();
// glTranslatef(x, y, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Artist.java
// public static void VizatoKatrorTexRot(Texture tex, float x, float y, float width, float height, float angle){
// tex.bind();
// glTranslatef(x + width / 2, y + height / 2, 0);
// glRotatef(angle, 0, 0, 1);
// glTranslatef( - width / 2, - height / 2, 0);
// glBegin(GL_QUADS);
// glTexCoord2f(0, 0);
// glVertex2f(0, 0);
// glTexCoord2f(1, 0);
// glVertex2f(width, 0);
// glTexCoord2f(1, 1);
// glVertex2f(width, height);
// glTexCoord2f(0, 1);
// glVertex2f(0, height);
// glEnd();
// glLoadIdentity();
//
// }
//
// Path: src/al/artofsoul/ndihma/Ora.java
// public static float Delta(){
// if (paused)
// return 0;
// else
// return d * multiplier;
// }
// Path: src/al/artofsoul/data/Tower.java
import static al.artofsoul.ndihma.Artist.VizatoKatrorTex;
import static al.artofsoul.ndihma.Artist.VizatoKatrorTexRot;
import static al.artofsoul.ndihma.Ora.Delta;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.opengl.Texture;
public void updateEnemyLists(CopyOnWriteArrayList<Armiku> newList) {
armiqt = newList;
}
public void update(){
if (!targeted ) { //|| target.getHiddenHealth() < 0 ) {
target = acquireTarget();
} else {
angle = calculateAngle();
if (timeSinceLastShot > firingSpeed) {
shoot(target);
timeSinceLastShot = 0;
}
}
if (target == null || target.isAlive() == false)
targeted = false;
timeSinceLastShot += Delta();
for (Projectile p: projectiles)
p.update();
draw();
}
public void draw() {
VizatoKatrorTex(textures[0], x, y, width, height);
if (textures.length > 1)
for(int i = 1; i < textures.length; i++) | VizatoKatrorTexRot(textures[i], x, y, width, height, angle); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/controllers/AudioRecordController.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import com.rai220.securityalarmbot.utils.L;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; | package com.rai220.securityalarmbot.controllers;
/**
*
*/
public class AudioRecordController {
public static final int SECONDS = 20;
private ExecutorService executor = Executors.newSingleThreadExecutor();
private MediaRecorder mRecorder = null;
private Future future = null;
public AudioRecordController() {
}
public void recordAndTransfer(final IAudioRecorder audioRecorder) {
if (future != null && !future.isDone()) {
future.cancel(true);
}
future = executor.submit(new Runnable() {
@Override
public void run() {
String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Telephoto/audio_" + System.currentTimeMillis() + ".3gp";
try { | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/controllers/AudioRecordController.java
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import com.rai220.securityalarmbot.utils.L;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
package com.rai220.securityalarmbot.controllers;
/**
*
*/
public class AudioRecordController {
public static final int SECONDS = 20;
private ExecutorService executor = Executors.newSingleThreadExecutor();
private MediaRecorder mRecorder = null;
private Future future = null;
public AudioRecordController() {
}
public void recordAndTransfer(final IAudioRecorder audioRecorder) {
if (future != null && !future.isDone()) {
future.cancel(true);
}
future = executor.submit(new Runnable() {
@Override
public void run() {
String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Telephoto/audio_" + System.currentTimeMillis() + ".3gp";
try { | L.i("Start audio recording"); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/LogsActivity.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot;
/**
* Created by rai220 on 11/3/16.
*/
public class LogsActivity extends Activity {
private EditText editText = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs);
}
@Override
protected void onPostResume() {
super.onPostResume();
editText = (EditText)findViewById(R.id.logsEditText); | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/LogsActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot;
/**
* Created by rai220 on 11/3/16.
*/
public class LogsActivity extends Activity {
private EditText editText = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs);
}
@Override
protected void onPostResume() {
super.onPostResume();
editText = (EditText)findViewById(R.id.logsEditText); | editText.setText(L.logsToString()); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java | // Path: app/src/main/java/com/rai220/securityalarmbot/model/IncomingMessage.java
// public class IncomingMessage {
//
// private String phone;
// private String name;
// private String message;
//
// public IncomingMessage(String phone, String name, String message) {
// this.phone = phone;
// this.name = name;
// this.message = message;
// }
//
// public IncomingMessage(String phone, String message) {
// this.phone = phone;
// this.message = message;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
| import android.location.Location;
import com.pengrad.telegrambot.model.request.Keyboard;
import com.rai220.securityalarmbot.model.IncomingMessage;
import java.io.File;
import java.util.List; | package com.rai220.securityalarmbot.telegram;
/**
*
*/
public interface ISenderService {
void sendMessage(Long id, String message);
void sendMessage(Long id, String message, Keyboard keyboard);
void sendMessageToAll(String message);
void sendMessageToAll(String message, Keyboard keyboard); | // Path: app/src/main/java/com/rai220/securityalarmbot/model/IncomingMessage.java
// public class IncomingMessage {
//
// private String phone;
// private String name;
// private String message;
//
// public IncomingMessage(String phone, String name, String message) {
// this.phone = phone;
// this.name = name;
// this.message = message;
// }
//
// public IncomingMessage(String phone, String message) {
// this.phone = phone;
// this.message = message;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
import android.location.Location;
import com.pengrad.telegrambot.model.request.Keyboard;
import com.rai220.securityalarmbot.model.IncomingMessage;
import java.io.File;
import java.util.List;
package com.rai220.securityalarmbot.telegram;
/**
*
*/
public interface ISenderService {
void sendMessage(Long id, String message);
void sendMessage(Long id, String message, Keyboard keyboard);
void sendMessageToAll(String message);
void sendMessageToAll(String message, Keyboard keyboard); | void sendMessageToAll(List<IncomingMessage> incomingMessageList); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec | private SensitivityType type; |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec
private SensitivityType type;
private Context context; | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec
private SensitivityType type;
private Context context; | private ISenderService service; |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec
private SensitivityType type;
private Context context;
private ISenderService service;
private float mPosition = 0;
private long alarmTime = 0;
public void init(ISenderService service, Context context, SensitivityType type) {
mPosition = 0;
this.service = service;
this.context = context;
this.type = type;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float xy_angle = event.values[0]; //Плоскость XY
float xz_angle = event.values[1]; //Плоскость XZ
float zy_angle = event.values[2]; //Плоскость ZY
float sum = (xy_angle + xz_angle + zy_angle);
if (mPosition == 0) {
mPosition = sum;
}
float vibrationLevel = Math.abs(mPosition - sum);
if (vibrationLevel > 0.5) { | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/types/SensitivityType.java
// public enum SensitivityType implements ICommand {
// HIGH("High", 30f, 0.5f),
// MEDIUM("Medium", 50f, 5f),
// LOW("Low", 70f, 10f);
//
// private String name;
// private float mdValue;
// private float shakeValue;
//
// SensitivityType(String name, float mdValue, float shakeValue) {
// this.name = name;
// this.mdValue = mdValue;
// this.shakeValue = shakeValue;
// }
//
// @Override
// public String getCommand() {
// return "/" + getName().toLowerCase();
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getDescription() {
// return "";
// }
//
// @Override
// public boolean isEnable() {
// return true;
// }
//
// @Override
// public boolean isHide() {
// return false;
// }
//
// @Override
// public boolean execute(Message message, Prefs prefs) {
// return false;
// }
//
// @Override
// public Collection<ICommand> execute(Message message) {
// return null;
// }
//
// public float getMdValue() {
// return mdValue;
// }
//
// public float getShakeValue() {
// return shakeValue;
// }
//
// public static SensitivityType getByName(String name) {
// for (SensitivityType type : values()) {
// if (name.equals(type.getName())) {
// return type;
// }
// }
// return null;
// }
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/telegram/ISenderService.java
// public interface ISenderService {
// void sendMessage(Long id, String message);
// void sendMessage(Long id, String message, Keyboard keyboard);
// void sendMessageToAll(String message);
// void sendMessageToAll(String message, Keyboard keyboard);
// void sendMessageToAll(List<IncomingMessage> incomingMessageList);
//
// void sendDocument(Long id, byte[] document, String fileName);
//
// void notifyToOthers(int userId, String message);
//
// void sendPhoto(Long id, byte[] photo);
// void sendPhoto(Long id, byte[] photo, String caption);
// void sendPhotoToAll(byte[] photo);
// void sendPhotoToAll(byte[] photo, String caption);
//
// void sendLocation(Long id, Location location);
//
// void sendAudio(Long chatId, File audio);
//
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/listeners/SensorListener.java
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import com.rai220.securityalarmbot.R;
import com.rai220.securityalarmbot.commands.types.SensitivityType;
import com.rai220.securityalarmbot.telegram.ISenderService;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class SensorListener implements SensorEventListener {
private static final int TIMEOUT = 10000; // 10sec
private SensitivityType type;
private Context context;
private ISenderService service;
private float mPosition = 0;
private long alarmTime = 0;
public void init(ISenderService service, Context context, SensitivityType type) {
mPosition = 0;
this.service = service;
this.context = context;
this.type = type;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float xy_angle = event.values[0]; //Плоскость XY
float xz_angle = event.values[1]; //Плоскость XZ
float zy_angle = event.values[2]; //Плоскость ZY
float sum = (xy_angle + xz_angle + zy_angle);
if (mPosition == 0) {
mPosition = sum;
}
float vibrationLevel = Math.abs(mPosition - sum);
if (vibrationLevel > 0.5) { | L.d("Diff: " + vibrationLevel); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/model/TimeStats.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/Constants.java
// public class Constants {
// public static final String LS = System.getProperty("line.separator");
//
// public static final String ACTION_SEND_PHOTO = "ACTION_SEND_PHOTO";
//
// public static final String SERVICE_ACTION = "SERVICE_ACTION";
// public static final String EXTRA_USER_ID = "EXTRA_USER_ID";
//
// public static final String DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm:ss";
// }
| import com.rai220.securityalarmbot.utils.Constants;
import org.joda.time.DateTime; | this.batteryTemperature = batteryTemperature;
this.batteryLevel = batteryLevel;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public DateTime getDateTime() {
return dateTime;
}
public Float getBatteryTemperature() {
return batteryTemperature;
}
public void setBatteryTemperature(float batteryTemperature) {
this.batteryTemperature = batteryTemperature;
}
public Float getBatteryLevel() {
return batteryLevel;
}
public void setBatteryLevel(float batteryLevel) {
this.batteryLevel = batteryLevel;
}
@Override
public String toString() { | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/Constants.java
// public class Constants {
// public static final String LS = System.getProperty("line.separator");
//
// public static final String ACTION_SEND_PHOTO = "ACTION_SEND_PHOTO";
//
// public static final String SERVICE_ACTION = "SERVICE_ACTION";
// public static final String EXTRA_USER_ID = "EXTRA_USER_ID";
//
// public static final String DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm:ss";
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/model/TimeStats.java
import com.rai220.securityalarmbot.utils.Constants;
import org.joda.time.DateTime;
this.batteryTemperature = batteryTemperature;
this.batteryLevel = batteryLevel;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public DateTime getDateTime() {
return dateTime;
}
public Float getBatteryTemperature() {
return batteryTemperature;
}
public void setBatteryTemperature(float batteryTemperature) {
this.batteryTemperature = batteryTemperature;
}
public Float getBatteryLevel() {
return batteryLevel;
}
public void setBatteryLevel(float batteryLevel) {
this.batteryLevel = batteryLevel;
}
@Override
public String toString() { | return "Date: " + dateTime.toString(Constants.DATE_TIME_PATTERN) + |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/TelephotoFirebaseInstanceIDService.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.app.Service;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot;
/**
* Created by rai220 on 11/24/16.
*/
public class TelephotoFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String fbToken = FirebaseInstanceId.getInstance().getToken(); | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/TelephotoFirebaseInstanceIDService.java
import android.app.Service;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot;
/**
* Created by rai220 on 11/24/16.
*/
public class TelephotoFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String fbToken = FirebaseInstanceId.getInstance().getToken(); | L.i("Firebase token: " + fbToken); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/photo/ClarifyAiHelper.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import com.google.gson.Gson;
import com.rai220.securityalarmbot.utils.L;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response; | return false;
}
public static List<String> clarify(byte[] jpeg) {
try {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("encoded_data", "file.jpg", MultipartBody.create(MediaType.parse("image/jpeg"), jpeg))
.build();
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + "nc8xqOaMYTJp7fMZiUbi396r7ZFkeB")
.url("https://api.clarifai.com/v1/tag/")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Map obj = gson.fromJson(result, Map.class);
List resultsList = (List) obj.get("results");
if (resultsList.size() > 0) {
Map res = (Map) ((Map) resultsList.get(0)).get("result");
Map tag = (Map) res.get("tag");
List classes = (List) tag.get("classes");
List<String> myClasses = (List) tag.get("classes");
for (int i = 0; i < classes.size(); i++) {
myClasses.add(classes.get(i).toString().toUpperCase());
}
return myClasses;
} | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/photo/ClarifyAiHelper.java
import com.google.gson.Gson;
import com.rai220.securityalarmbot.utils.L;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
return false;
}
public static List<String> clarify(byte[] jpeg) {
try {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("encoded_data", "file.jpg", MultipartBody.create(MediaType.parse("image/jpeg"), jpeg))
.build();
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + "nc8xqOaMYTJp7fMZiUbi396r7ZFkeB")
.url("https://api.clarifai.com/v1/tag/")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Map obj = gson.fromJson(result, Map.class);
List resultsList = (List) obj.get("results");
if (resultsList.size() > 0) {
Map res = (Map) ((Map) resultsList.get(0)).get("result");
Map tag = (Map) res.get("tag");
List classes = (List) tag.get("classes");
List<String> myClasses = (List) tag.get("classes");
for (int i = 0; i < classes.size(); i++) {
myClasses.add(classes.get(i).toString().toUpperCase());
}
return myClasses;
} | L.i(result); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/controllers/LocationController.java | // Path: app/src/main/java/com/rai220/securityalarmbot/listeners/GpsLocationListener.java
// public class GpsLocationListener implements LocationListener {
// private OnChangeCallback callback;
//
// public GpsLocationListener(OnChangeCallback callback) {
// this.callback = callback;
// }
//
// @Override
// public void onLocationChanged(Location location) {
// L.i(String.format("Latitude: %.3f, Longitude: %.3f", location.getLatitude(), location.getLongitude()));
// callback.updateLocation(location);
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
//
// public interface OnChangeCallback {
// void updateLocation(Location location);
// }
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.rai220.securityalarmbot.listeners.GpsLocationListener;
import com.rai220.securityalarmbot.utils.L;
import java.util.List;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION; | package com.rai220.securityalarmbot.controllers;
/**
*
*/
public class LocationController implements GpsLocationListener.OnChangeCallback {
private final Object monitor = new Object();
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private Location mLastLocation;
private volatile int callUpdateCount = 0;
private Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 1;
while (!Thread.currentThread().isInterrupted() && i <= 60) {
Thread.sleep(1000);
i++;
}
stop();
} catch (InterruptedException ignore) {
}
}
});
@Override
public void updateLocation(Location location) {
mLastLocation = location;
callUpdateCount++; | // Path: app/src/main/java/com/rai220/securityalarmbot/listeners/GpsLocationListener.java
// public class GpsLocationListener implements LocationListener {
// private OnChangeCallback callback;
//
// public GpsLocationListener(OnChangeCallback callback) {
// this.callback = callback;
// }
//
// @Override
// public void onLocationChanged(Location location) {
// L.i(String.format("Latitude: %.3f, Longitude: %.3f", location.getLatitude(), location.getLongitude()));
// callback.updateLocation(location);
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
//
// public interface OnChangeCallback {
// void updateLocation(Location location);
// }
// }
//
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/controllers/LocationController.java
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.rai220.securityalarmbot.listeners.GpsLocationListener;
import com.rai220.securityalarmbot.utils.L;
import java.util.List;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
package com.rai220.securityalarmbot.controllers;
/**
*
*/
public class LocationController implements GpsLocationListener.OnChangeCallback {
private final Object monitor = new Object();
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private Location mLastLocation;
private volatile int callUpdateCount = 0;
private Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 1;
while (!Thread.currentThread().isInterrupted() && i <= 60) {
Thread.sleep(1000);
i++;
}
stop();
} catch (InterruptedException ignore) {
}
}
});
@Override
public void updateLocation(Location location) {
mLastLocation = location;
callUpdateCount++; | L.i("accuracy: " + location.getAccuracy()); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/photo/ImageShot.java | // Path: app/src/main/java/com/rai220/securityalarmbot/prefs/PrefsController.java
// public class PrefsController {
// public static final PrefsController instance = new PrefsController();
//
// private static final String PREFS_CODE = "PREFS_CODE";
// private static final String TELEGRAM_BOT_TOKEN = "TELEGRAM_BOT_TOKEN";
// private static final String AUTORUN = "AUTORUN";
// private static final String IS_HELP_SHOWN = "IS_HELP_SHOWN";
// private static final String LAST_MD_DETECTED = "LAST_MD_DETECTED";
// private static final String IS_PRO = "IS_PRO";
//
// private volatile SharedPreferences preferences;
// private volatile Prefs prefs = null;
//
// public synchronized void init(Context context) {
// if (preferences == null) {
// preferences = PreferenceManager.getDefaultSharedPreferences(context);
// }
// }
//
// private PrefsController() {
// }
//
// public boolean hasToken() {
// return !Strings.isNullOrEmpty(getToken());
// }
//
// public String getToken() {
// return preferences.getString(TELEGRAM_BOT_TOKEN, "");
// }
//
// public void setToken(String newToken) {
// newToken = newToken.replaceAll("\\s+", "");
// preferences.edit().putString(TELEGRAM_BOT_TOKEN, newToken).apply();
// }
//
// public boolean isHelpShown() {
// return preferences.getBoolean(IS_HELP_SHOWN, false);
// }
//
// public void setHelpShown(boolean isShown) {
// preferences.edit().putBoolean(IS_HELP_SHOWN, isShown).apply();
// }
//
// public synchronized void setPrefs(Prefs prefs) {
// String toSave = prefsGson.toJson(prefs);
// L.i("Writing settings: " + toSave);
// preferences.edit().putString(PREFS_CODE, toSave).apply();
// this.prefs = prefs;
// }
//
// public synchronized Prefs getPrefs() {
// if (this.prefs == null) {
// String prefsJson = preferences.getString(PREFS_CODE, null);
// L.i("Reading settings: " + prefsJson);
// if (prefsJson == null) {
// prefs = new Prefs();
// } else {
// prefs = prefsGson.fromJson(prefsJson, Prefs.class);
// }
// }
// return prefs;
// }
//
// public void setAutorun(boolean isAutorunEnabled) {
// preferences.edit().putBoolean(AUTORUN, isAutorunEnabled).apply();
// }
//
// public boolean isAutorunEnabled() {
// return preferences.getBoolean(AUTORUN, false);
// }
//
// public void setPassword(String password) {
// Prefs prefs = getPrefs();
// String newPass = null;
// if (!Strings.isNullOrEmpty(password)) {
// password = password.replaceAll("\\s+", "");
// newPass = password.equals(prefs.password) ? password : FabricUtils.crypt(password);
// }
// if (newPass != null && (prefs.password == null || !newPass.equals(prefs.password))) {
// prefs.removeRegisterUsers();
// }
// prefs.password = newPass;
// setPrefs(prefs);
// }
//
// public String getPassword() {
// return getPrefs().password;
// }
//
// public void updateLastMdDetected() {
// preferences.edit().putLong(LAST_MD_DETECTED, System.currentTimeMillis()).apply();
// }
//
// public long getLastMdDetected() {
// return preferences.getLong(LAST_MD_DETECTED, 0L);
// }
//
// public void makePro() {
// preferences.edit().putBoolean(IS_PRO, true).apply();
// }
//
// public boolean isPro() {
// return preferences.getBoolean(IS_PRO, false);
// }
//
// public void unmakePro() {
// preferences.edit().putBoolean(IS_PRO, false).apply();
// }
// }
| import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import com.rai220.securityalarmbot.prefs.PrefsController;
import java.io.ByteArrayOutputStream;
import boofcv.android.VisualizeImageData; | public Camera.Parameters getParameters() {
return parameters;
}
public void setParameters(Camera.Parameters parameters) {
this.parameters = parameters;
}
public byte[] toGoodQuality() {
return imgToByte(true);
}
public byte[] toYuvByteArray() {
return imgToByte(false);
}
private byte[] imgToByte(boolean quality) {
Camera.Parameters parameters = getParameters();
int width = parameters.getPreviewSize().width;
int height = parameters.getPreviewSize().height;
YuvImage yuv = new YuvImage(getImage(), parameters.getPreviewFormat(), width, height, null);
ByteArrayOutputStream out =
new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
byte[] compressed = out.toByteArray();
Bitmap newBmp = BitmapFactory.decodeByteArray(compressed, 0, compressed.length);
Matrix mat = new Matrix(); | // Path: app/src/main/java/com/rai220/securityalarmbot/prefs/PrefsController.java
// public class PrefsController {
// public static final PrefsController instance = new PrefsController();
//
// private static final String PREFS_CODE = "PREFS_CODE";
// private static final String TELEGRAM_BOT_TOKEN = "TELEGRAM_BOT_TOKEN";
// private static final String AUTORUN = "AUTORUN";
// private static final String IS_HELP_SHOWN = "IS_HELP_SHOWN";
// private static final String LAST_MD_DETECTED = "LAST_MD_DETECTED";
// private static final String IS_PRO = "IS_PRO";
//
// private volatile SharedPreferences preferences;
// private volatile Prefs prefs = null;
//
// public synchronized void init(Context context) {
// if (preferences == null) {
// preferences = PreferenceManager.getDefaultSharedPreferences(context);
// }
// }
//
// private PrefsController() {
// }
//
// public boolean hasToken() {
// return !Strings.isNullOrEmpty(getToken());
// }
//
// public String getToken() {
// return preferences.getString(TELEGRAM_BOT_TOKEN, "");
// }
//
// public void setToken(String newToken) {
// newToken = newToken.replaceAll("\\s+", "");
// preferences.edit().putString(TELEGRAM_BOT_TOKEN, newToken).apply();
// }
//
// public boolean isHelpShown() {
// return preferences.getBoolean(IS_HELP_SHOWN, false);
// }
//
// public void setHelpShown(boolean isShown) {
// preferences.edit().putBoolean(IS_HELP_SHOWN, isShown).apply();
// }
//
// public synchronized void setPrefs(Prefs prefs) {
// String toSave = prefsGson.toJson(prefs);
// L.i("Writing settings: " + toSave);
// preferences.edit().putString(PREFS_CODE, toSave).apply();
// this.prefs = prefs;
// }
//
// public synchronized Prefs getPrefs() {
// if (this.prefs == null) {
// String prefsJson = preferences.getString(PREFS_CODE, null);
// L.i("Reading settings: " + prefsJson);
// if (prefsJson == null) {
// prefs = new Prefs();
// } else {
// prefs = prefsGson.fromJson(prefsJson, Prefs.class);
// }
// }
// return prefs;
// }
//
// public void setAutorun(boolean isAutorunEnabled) {
// preferences.edit().putBoolean(AUTORUN, isAutorunEnabled).apply();
// }
//
// public boolean isAutorunEnabled() {
// return preferences.getBoolean(AUTORUN, false);
// }
//
// public void setPassword(String password) {
// Prefs prefs = getPrefs();
// String newPass = null;
// if (!Strings.isNullOrEmpty(password)) {
// password = password.replaceAll("\\s+", "");
// newPass = password.equals(prefs.password) ? password : FabricUtils.crypt(password);
// }
// if (newPass != null && (prefs.password == null || !newPass.equals(prefs.password))) {
// prefs.removeRegisterUsers();
// }
// prefs.password = newPass;
// setPrefs(prefs);
// }
//
// public String getPassword() {
// return getPrefs().password;
// }
//
// public void updateLastMdDetected() {
// preferences.edit().putLong(LAST_MD_DETECTED, System.currentTimeMillis()).apply();
// }
//
// public long getLastMdDetected() {
// return preferences.getLong(LAST_MD_DETECTED, 0L);
// }
//
// public void makePro() {
// preferences.edit().putBoolean(IS_PRO, true).apply();
// }
//
// public boolean isPro() {
// return preferences.getBoolean(IS_PRO, false);
// }
//
// public void unmakePro() {
// preferences.edit().putBoolean(IS_PRO, false).apply();
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/photo/ImageShot.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import com.rai220.securityalarmbot.prefs.PrefsController;
import java.io.ByteArrayOutputStream;
import boofcv.android.VisualizeImageData;
public Camera.Parameters getParameters() {
return parameters;
}
public void setParameters(Camera.Parameters parameters) {
this.parameters = parameters;
}
public byte[] toGoodQuality() {
return imgToByte(true);
}
public byte[] toYuvByteArray() {
return imgToByte(false);
}
private byte[] imgToByte(boolean quality) {
Camera.Parameters parameters = getParameters();
int width = parameters.getPreviewSize().width;
int height = parameters.getPreviewSize().height;
YuvImage yuv = new YuvImage(getImage(), parameters.getPreviewFormat(), width, height, null);
ByteArrayOutputStream out =
new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
byte[] compressed = out.toByteArray();
Bitmap newBmp = BitmapFactory.decodeByteArray(compressed, 0, compressed.length);
Matrix mat = new Matrix(); | mat.postRotate(PrefsController.instance.getPrefs().getCameraPrefs(cameraId).angle); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/listeners/GpsLocationListener.java | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
| import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import com.rai220.securityalarmbot.utils.L; | package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class GpsLocationListener implements LocationListener {
private OnChangeCallback callback;
public GpsLocationListener(OnChangeCallback callback) {
this.callback = callback;
}
@Override
public void onLocationChanged(Location location) { | // Path: app/src/main/java/com/rai220/securityalarmbot/utils/L.java
// public class L {
// private static final String TAG = "SecurityAlarmBot";
//
// private static final int MAX_LOG_SIZE = 10 * 1000;
// private static final LinkedList<String> logs = new LinkedList<>();
//
// private L() {
// }
//
// public static void e(String error) {
// Log.e(TAG, error);
// saveToLog("e", error);
// }
//
// public static void e(Throwable th) {
// e(null, th);
// }
//
// public static void e(String message, Throwable th) {
// Log.e(TAG, "", th);
// StackTraceElement[] stack = th.getStackTrace();
// StackTraceElement lastElement = stack[stack.length - 1];
// String where = lastElement.getClassName() + ":" + lastElement.getLineNumber();
// Answers.getInstance().logCustom(new CustomEvent("Error").putCustomAttribute("error_text", where));
// if (message != null) {
// Crashlytics.log(message);
// }
// Crashlytics.logException(th);
//
// saveToLog("e", where);
// }
//
// public static void i(Object obj) {
// saveToLog("I", "" + obj);
// Log.i(TAG, "" + obj);
// }
//
// public static void d(Object obj) {
// Log.d(TAG, "" + obj);
// }
//
// public static String logsToString() {
// synchronized (logs) {
// return Joiner.on("\n").join(logs);
// }
// }
//
// private static void saveToLog(String level, String text) {
// synchronized (logs) {
// logs.addLast("" + System.currentTimeMillis() + " (" + level + ") " + text);
// if (logs.size() > MAX_LOG_SIZE) {
// logs.removeFirst();
// }
// }
// }
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/listeners/GpsLocationListener.java
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import com.rai220.securityalarmbot.utils.L;
package com.rai220.securityalarmbot.listeners;
/**
*
*/
public class GpsLocationListener implements LocationListener {
private OnChangeCallback callback;
public GpsLocationListener(OnChangeCallback callback) {
this.callback = callback;
}
@Override
public void onLocationChanged(Location location) { | L.i(String.format("Latitude: %.3f, Longitude: %.3f", location.getLatitude(), location.getLongitude())); |
Rai220/Telephoto | app/src/main/java/com/rai220/securityalarmbot/utils/KeyboardUtils.java | // Path: app/src/main/java/com/rai220/securityalarmbot/commands/ICommand.java
// public interface ICommand {
//
// /**
// * Returns unique command (starts with '/')
// *
// * @return command
// */
// String getCommand();
//
// /**
// * Returns name of command (using into button)
// *
// * @return short name of command
// */
// String getName();
//
// /**
// * Returns description of command
// *
// * @return long description about command (what to do)
// */
// String getDescription();
//
// /**
// * Enable or disable command function
// *
// * @return true if enabled
// */
// boolean isEnable();
//
// /**
// * Visible or hide command function
// *
// * @return true if hide
// */
// boolean isHide();
//
// /**
// * Execute command
// *
// * @param message incoming message
// * @param prefs
// * @return true if success
// */
// boolean execute(Message message, Prefs prefs);
//
// Collection<ICommand> execute(Message message);
//
// }
| import com.pengrad.telegrambot.model.request.ReplyKeyboardMarkup;
import com.rai220.securityalarmbot.commands.ICommand;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List; | package com.rai220.securityalarmbot.utils;
/**
*
*/
public class KeyboardUtils {
private KeyboardUtils() {
}
| // Path: app/src/main/java/com/rai220/securityalarmbot/commands/ICommand.java
// public interface ICommand {
//
// /**
// * Returns unique command (starts with '/')
// *
// * @return command
// */
// String getCommand();
//
// /**
// * Returns name of command (using into button)
// *
// * @return short name of command
// */
// String getName();
//
// /**
// * Returns description of command
// *
// * @return long description about command (what to do)
// */
// String getDescription();
//
// /**
// * Enable or disable command function
// *
// * @return true if enabled
// */
// boolean isEnable();
//
// /**
// * Visible or hide command function
// *
// * @return true if hide
// */
// boolean isHide();
//
// /**
// * Execute command
// *
// * @param message incoming message
// * @param prefs
// * @return true if success
// */
// boolean execute(Message message, Prefs prefs);
//
// Collection<ICommand> execute(Message message);
//
// }
// Path: app/src/main/java/com/rai220/securityalarmbot/utils/KeyboardUtils.java
import com.pengrad.telegrambot.model.request.ReplyKeyboardMarkup;
import com.rai220.securityalarmbot.commands.ICommand;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
package com.rai220.securityalarmbot.utils;
/**
*
*/
public class KeyboardUtils {
private KeyboardUtils() {
}
| public static ReplyKeyboardMarkup getKeyboard(Collection<ICommand> values) { |
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/service/impl/RoleServiceImpl.java | // Path: src/main/java/com/smates/dbc2/mapper/RoleDao.java
// public interface RoleDao {
//
// /**
// * 查询所有的role记录
// * @return
// */
// public List<Role> getAllRoles();
//
// }
//
// Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoleService.java
// public interface RoleService {
//
// /**
// * 获取角色列表
// * @return
// */
// public List<Role> getAllRoles();
//
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoleDao;
import com.smates.dbc2.po.Role;
import com.smates.dbc2.service.RoleService;
| package com.smates.dbc2.service.impl;
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
| // Path: src/main/java/com/smates/dbc2/mapper/RoleDao.java
// public interface RoleDao {
//
// /**
// * 查询所有的role记录
// * @return
// */
// public List<Role> getAllRoles();
//
// }
//
// Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoleService.java
// public interface RoleService {
//
// /**
// * 获取角色列表
// * @return
// */
// public List<Role> getAllRoles();
//
// }
// Path: src/main/java/com/smates/dbc2/service/impl/RoleServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoleDao;
import com.smates.dbc2.po.Role;
import com.smates.dbc2.service.RoleService;
package com.smates.dbc2.service.impl;
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
| private RoleDao roleDao;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/service/impl/RoleServiceImpl.java | // Path: src/main/java/com/smates/dbc2/mapper/RoleDao.java
// public interface RoleDao {
//
// /**
// * 查询所有的role记录
// * @return
// */
// public List<Role> getAllRoles();
//
// }
//
// Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoleService.java
// public interface RoleService {
//
// /**
// * 获取角色列表
// * @return
// */
// public List<Role> getAllRoles();
//
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoleDao;
import com.smates.dbc2.po.Role;
import com.smates.dbc2.service.RoleService;
| package com.smates.dbc2.service.impl;
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
private RoleDao roleDao;
@Override
| // Path: src/main/java/com/smates/dbc2/mapper/RoleDao.java
// public interface RoleDao {
//
// /**
// * 查询所有的role记录
// * @return
// */
// public List<Role> getAllRoles();
//
// }
//
// Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoleService.java
// public interface RoleService {
//
// /**
// * 获取角色列表
// * @return
// */
// public List<Role> getAllRoles();
//
// }
// Path: src/main/java/com/smates/dbc2/service/impl/RoleServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoleDao;
import com.smates.dbc2.po.Role;
import com.smates.dbc2.service.RoleService;
package com.smates.dbc2.service.impl;
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
private RoleDao roleDao;
@Override
| public List<Role> getAllRoles() {
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/mapper/MenuDao.java | // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/CostumMenu.java
// public class CostumMenu extends Menu {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int pageNo;
// private int pageSize;
// private int startCount;
//
// public int getStartCount() {
// return startCount;
// }
//
// public void setStartCount(int startCount) {
// this.startCount = startCount;
// }
//
// public int getPageNo() {
// return pageNo;
// }
//
// public void setPageNo(int pageNo) {
// this.pageNo = pageNo;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
// }
| import java.util.List;
import com.smates.dbc2.po.Menu;
import com.smates.dbc2.vo.ComboBoxRow;
import com.smates.dbc2.vo.CostumMenu;
| package com.smates.dbc2.mapper;
public interface MenuDao {
/**
* 获取所有菜单,一级菜单和二级菜单
* @return
*/
public List<Menu> getMenuByRole(Integer role);
/**
* 向s_menu中插入一条数据
* @param menu
*/
public void addMenu(Menu menu);
/**
* 得到所有的一级菜单
* @return
*/
| // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/CostumMenu.java
// public class CostumMenu extends Menu {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int pageNo;
// private int pageSize;
// private int startCount;
//
// public int getStartCount() {
// return startCount;
// }
//
// public void setStartCount(int startCount) {
// this.startCount = startCount;
// }
//
// public int getPageNo() {
// return pageNo;
// }
//
// public void setPageNo(int pageNo) {
// this.pageNo = pageNo;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
// }
// Path: src/main/java/com/smates/dbc2/mapper/MenuDao.java
import java.util.List;
import com.smates.dbc2.po.Menu;
import com.smates.dbc2.vo.ComboBoxRow;
import com.smates.dbc2.vo.CostumMenu;
package com.smates.dbc2.mapper;
public interface MenuDao {
/**
* 获取所有菜单,一级菜单和二级菜单
* @return
*/
public List<Menu> getMenuByRole(Integer role);
/**
* 向s_menu中插入一条数据
* @param menu
*/
public void addMenu(Menu menu);
/**
* 得到所有的一级菜单
* @return
*/
| public List<ComboBoxRow> getParentMenu();
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/mapper/MenuDao.java | // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/CostumMenu.java
// public class CostumMenu extends Menu {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int pageNo;
// private int pageSize;
// private int startCount;
//
// public int getStartCount() {
// return startCount;
// }
//
// public void setStartCount(int startCount) {
// this.startCount = startCount;
// }
//
// public int getPageNo() {
// return pageNo;
// }
//
// public void setPageNo(int pageNo) {
// this.pageNo = pageNo;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
// }
| import java.util.List;
import com.smates.dbc2.po.Menu;
import com.smates.dbc2.vo.ComboBoxRow;
import com.smates.dbc2.vo.CostumMenu;
| package com.smates.dbc2.mapper;
public interface MenuDao {
/**
* 获取所有菜单,一级菜单和二级菜单
* @return
*/
public List<Menu> getMenuByRole(Integer role);
/**
* 向s_menu中插入一条数据
* @param menu
*/
public void addMenu(Menu menu);
/**
* 得到所有的一级菜单
* @return
*/
public List<ComboBoxRow> getParentMenu();
/**
* 获取所有的菜单
* @return
*/
| // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/vo/CostumMenu.java
// public class CostumMenu extends Menu {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private int pageNo;
// private int pageSize;
// private int startCount;
//
// public int getStartCount() {
// return startCount;
// }
//
// public void setStartCount(int startCount) {
// this.startCount = startCount;
// }
//
// public int getPageNo() {
// return pageNo;
// }
//
// public void setPageNo(int pageNo) {
// this.pageNo = pageNo;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
// }
// Path: src/main/java/com/smates/dbc2/mapper/MenuDao.java
import java.util.List;
import com.smates.dbc2.po.Menu;
import com.smates.dbc2.vo.ComboBoxRow;
import com.smates.dbc2.vo.CostumMenu;
package com.smates.dbc2.mapper;
public interface MenuDao {
/**
* 获取所有菜单,一级菜单和二级菜单
* @return
*/
public List<Menu> getMenuByRole(Integer role);
/**
* 向s_menu中插入一条数据
* @param menu
*/
public void addMenu(Menu menu);
/**
* 得到所有的一级菜单
* @return
*/
public List<ComboBoxRow> getParentMenu();
/**
* 获取所有的菜单
* @return
*/
| public List<Menu> getAllMenu(CostumMenu costumMenu);
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/controller/RoleController.java | // Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
| import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.Role;
| package com.smates.dbc2.controller;
@Controller
public class RoleController extends BaseController{
public Logger logger = Logger.getLogger(RoleController.class);
@RequestMapping("getAllRole")
@ResponseBody
| // Path: src/main/java/com/smates/dbc2/po/Role.java
// public class Role {
// private int id;
// private String roleName;
//
// public Role() {
// }
//
// public Role(int id, String roleName) {
// this.id = id;
// this.roleName = roleName;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getRoleName() {
// return roleName;
// }
//
// public void setRoleName(String roleName) {
// this.roleName = roleName;
// }
//
// }
// Path: src/main/java/com/smates/dbc2/controller/RoleController.java
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.Role;
package com.smates.dbc2.controller;
@Controller
public class RoleController extends BaseController{
public Logger logger = Logger.getLogger(RoleController.class);
@RequestMapping("getAllRole")
@ResponseBody
| public List<Role> getAllRole(){
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/service/UserService.java | // Path: src/main/java/com/smates/dbc2/po/User.java
// public class User implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String accountNumber;
//
// private String nickName;
//
// private String password;
//
// private Integer role;
//
// private Date createDate;
//
// private String eMail;
//
// private String image;
//
// public User(Integer id, String accountNumber, String nickName, String password, Integer role, Date createDate,
// String eMail) {
// this.id = id;
// this.accountNumber = accountNumber;
// this.nickName = nickName;
// this.password = password;
// this.role = role;
// this.createDate = createDate;
// this.eMail = eMail;
// this.image = "000.jpg";
// }
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Integer getRole() {
// return role;
// }
//
// public void setRole(Integer role) {
// this.role = role;
// }
//
// public String geteMail() {
// return eMail;
// }
//
// public void seteMail(String eMail) {
// this.eMail = eMail;
// }
//
// public static long getSerialversionuid() {
// return serialVersionUID;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public User() {
// }
//
// @Override
// public String toString() {
// return "User [id=" + id + ", accountNumber=" + accountNumber + ", nickName=" + nickName + ", password="
// + password + ", role=" + role + ", createDate=" + createDate + ", eMail=" + eMail
// + "]";
// }
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
| import java.util.List;
import com.smates.dbc2.po.User;
import com.smates.dbc2.vo.ComboBoxRow;
| package com.smates.dbc2.service;
/**
* 用户相关service
*
* @author baijw12
*
*/
public interface UserService {
/**
* 获取当前登录用户accountnumber
*
* @return
*/
public String getCurrentUserActNum();
/**
* 根据accountNumber查找user
*
* @param accountNumber
* @return
*/
| // Path: src/main/java/com/smates/dbc2/po/User.java
// public class User implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String accountNumber;
//
// private String nickName;
//
// private String password;
//
// private Integer role;
//
// private Date createDate;
//
// private String eMail;
//
// private String image;
//
// public User(Integer id, String accountNumber, String nickName, String password, Integer role, Date createDate,
// String eMail) {
// this.id = id;
// this.accountNumber = accountNumber;
// this.nickName = nickName;
// this.password = password;
// this.role = role;
// this.createDate = createDate;
// this.eMail = eMail;
// this.image = "000.jpg";
// }
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public String getNickName() {
// return nickName;
// }
//
// public void setNickName(String nickName) {
// this.nickName = nickName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Integer getRole() {
// return role;
// }
//
// public void setRole(Integer role) {
// this.role = role;
// }
//
// public String geteMail() {
// return eMail;
// }
//
// public void seteMail(String eMail) {
// this.eMail = eMail;
// }
//
// public static long getSerialversionuid() {
// return serialVersionUID;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public User() {
// }
//
// @Override
// public String toString() {
// return "User [id=" + id + ", accountNumber=" + accountNumber + ", nickName=" + nickName + ", password="
// + password + ", role=" + role + ", createDate=" + createDate + ", eMail=" + eMail
// + "]";
// }
// }
//
// Path: src/main/java/com/smates/dbc2/vo/ComboBoxRow.java
// public class ComboBoxRow {
// private String id;
// private String text;
//
// public ComboBoxRow() {
// }
//
// public ComboBoxRow(String id, String text) {
// this.id = id;
// this.text = text;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// }
// Path: src/main/java/com/smates/dbc2/service/UserService.java
import java.util.List;
import com.smates.dbc2.po.User;
import com.smates.dbc2.vo.ComboBoxRow;
package com.smates.dbc2.service;
/**
* 用户相关service
*
* @author baijw12
*
*/
public interface UserService {
/**
* 获取当前登录用户accountnumber
*
* @return
*/
public String getCurrentUserActNum();
/**
* 根据accountNumber查找user
*
* @param accountNumber
* @return
*/
| public User getUserByAccountNumber(String accountNumber);
|
MarchMachao/ZHFS-WEB | src/com/smates/app/dao/ItemMapper.java | // Path: src/com/smates/app/pojo/Item.java
// public class Item {
// private String itemId;
//
// private String itemName;
//
// private Double itemPrice;
//
// private String orderId;
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId == null ? null : itemId.trim();
// }
//
// public String getItemName() {
// return itemName;
// }
//
// public void setItemName(String itemName) {
// this.itemName = itemName == null ? null : itemName.trim();
// }
//
// public Double getItemPrice() {
// return itemPrice;
// }
//
// public void setItemPrice(Double itemPrice) {
// this.itemPrice = itemPrice;
// }
//
// public String getOrderId() {
// return orderId;
// }
//
// public void setOrderId(String orderId) {
// this.orderId = orderId == null ? null : orderId.trim();
// }
// }
| import com.smates.app.pojo.Item;
| package com.smates.app.dao;
public interface ItemMapper {
int deleteByPrimaryKey(String itemId);
| // Path: src/com/smates/app/pojo/Item.java
// public class Item {
// private String itemId;
//
// private String itemName;
//
// private Double itemPrice;
//
// private String orderId;
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId == null ? null : itemId.trim();
// }
//
// public String getItemName() {
// return itemName;
// }
//
// public void setItemName(String itemName) {
// this.itemName = itemName == null ? null : itemName.trim();
// }
//
// public Double getItemPrice() {
// return itemPrice;
// }
//
// public void setItemPrice(Double itemPrice) {
// this.itemPrice = itemPrice;
// }
//
// public String getOrderId() {
// return orderId;
// }
//
// public void setOrderId(String orderId) {
// this.orderId = orderId == null ? null : orderId.trim();
// }
// }
// Path: src/com/smates/app/dao/ItemMapper.java
import com.smates.app.pojo.Item;
package com.smates.app.dao;
public interface ItemMapper {
int deleteByPrimaryKey(String itemId);
| int insert(Item record);
|
MarchMachao/ZHFS-WEB | src/test/java/com/smates/dbc2/test/TagInformationTest.java | // Path: src/main/java/com/smates/dbc2/mapper/TagInformationDao.java
// public interface TagInformationDao {
//
// /**
// * 通过标签号获取该标签持有人的信息
// * @return
// */
// public List<TagInformation> getAllUsefulTag(Page page);
//
// /**
// * 获取数据总数量(用于分页)
// *
// * @return
// */
// public int countSum();
//
// /**
// * 向该表中插入一条数据
// */
// public void addTagInfoByTagNum(TagInformation tagInfo);
//
// /**
// * 根据标签号删除数据
// * @param tagNum
// */
// public void deleteTagInfoByTagNum(Integer tagNum);
//
// /**
// * 更新标签持有人信息
// * @param tagInfo
// */
// public void updateTagInformation(TagInformation tagInfo);
// }
| import com.smates.dbc2.mapper.TagInformationDao;
| package com.smates.dbc2.test;
public class TagInformationTest {
public void testSelect(){
| // Path: src/main/java/com/smates/dbc2/mapper/TagInformationDao.java
// public interface TagInformationDao {
//
// /**
// * 通过标签号获取该标签持有人的信息
// * @return
// */
// public List<TagInformation> getAllUsefulTag(Page page);
//
// /**
// * 获取数据总数量(用于分页)
// *
// * @return
// */
// public int countSum();
//
// /**
// * 向该表中插入一条数据
// */
// public void addTagInfoByTagNum(TagInformation tagInfo);
//
// /**
// * 根据标签号删除数据
// * @param tagNum
// */
// public void deleteTagInfoByTagNum(Integer tagNum);
//
// /**
// * 更新标签持有人信息
// * @param tagInfo
// */
// public void updateTagInformation(TagInformation tagInfo);
// }
// Path: src/test/java/com/smates/dbc2/test/TagInformationTest.java
import com.smates.dbc2.mapper.TagInformationDao;
package com.smates.dbc2.test;
public class TagInformationTest {
public void testSelect(){
| TagInformationDao tagInformationDao = null;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/service/impl/RoomLocationServiceImpl.java | // Path: src/main/java/com/smates/dbc2/mapper/RoomLocationDao.java
// public interface RoomLocationDao {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
//
// Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoomLocationDao;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
| package com.smates.dbc2.service.impl;
@Service
public class RoomLocationServiceImpl implements RoomLocationService {
@Autowired
| // Path: src/main/java/com/smates/dbc2/mapper/RoomLocationDao.java
// public interface RoomLocationDao {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
//
// Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
// Path: src/main/java/com/smates/dbc2/service/impl/RoomLocationServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoomLocationDao;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
package com.smates.dbc2.service.impl;
@Service
public class RoomLocationServiceImpl implements RoomLocationService {
@Autowired
| private RoomLocationDao roomLocationDao;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/service/impl/RoomLocationServiceImpl.java | // Path: src/main/java/com/smates/dbc2/mapper/RoomLocationDao.java
// public interface RoomLocationDao {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
//
// Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoomLocationDao;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
| package com.smates.dbc2.service.impl;
@Service
public class RoomLocationServiceImpl implements RoomLocationService {
@Autowired
private RoomLocationDao roomLocationDao;
@Override
| // Path: src/main/java/com/smates/dbc2/mapper/RoomLocationDao.java
// public interface RoomLocationDao {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
//
// Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
// Path: src/main/java/com/smates/dbc2/service/impl/RoomLocationServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smates.dbc2.mapper.RoomLocationDao;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
package com.smates.dbc2.service.impl;
@Service
public class RoomLocationServiceImpl implements RoomLocationService {
@Autowired
private RoomLocationDao roomLocationDao;
@Override
| public List<RoomLocation> getRoomLocation() {
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/vo/MenuCheckboxVo.java | // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
| import java.util.List;
import com.smates.dbc2.po.Menu;
| package com.smates.dbc2.vo;
public class MenuCheckboxVo {
private String menuId;
private String menuName;
private String parentId;
private String menuUrl;
private Integer order;
private String[] permition;
| // Path: src/main/java/com/smates/dbc2/po/Menu.java
// public class Menu implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// private String menuId;
// private String menuName;
// private String parentId;
// private String menuUrl;
// private Integer order;
// private String permition;
// private List<Menu> submenus;
//
// public Menu() {
// }
//
// public Menu(String menuId, String menuName, String parentId, String menuUrl, Integer order, String permition,
// List<Menu> submenus) {
// this.menuId = menuId;
// this.menuName = menuName;
// this.parentId = parentId;
// this.menuUrl = menuUrl;
// this.order = order;
// this.permition = permition;
// this.submenus = submenus;
// }
//
// public String getMenuId() {
// return menuId;
// }
//
// public void setMenuId(String menuId) {
// this.menuId = menuId;
// }
//
// public String getMenuName() {
// return menuName;
// }
//
// public void setMenuName(String menuName) {
// this.menuName = menuName;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// public String getMenuUrl() {
// return menuUrl;
// }
//
// public void setMenuUrl(String menuUrl) {
// this.menuUrl = menuUrl;
// }
//
// public Integer getOrder() {
// return order;
// }
//
// public void setOrder(Integer order) {
// this.order = order;
// }
//
// public List<Menu> getSubmenus() {
// return submenus;
// }
//
// public void setSubmenus(List<Menu> submenus) {
// this.submenus = submenus;
// }
//
// public String getPermition() {
// return permition;
// }
//
// public void setPermition(String permition) {
// this.permition = permition;
// }
//
// @Override
// public String toString() {
// return "Menu [menuId=" + menuId + ", menuName=" + menuName + ", parentId=" + parentId + ", menuUrl=" + menuUrl
// + ", order=" + order + ", submenus=" + submenus + "]";
// }
//
// }
// Path: src/main/java/com/smates/dbc2/vo/MenuCheckboxVo.java
import java.util.List;
import com.smates.dbc2.po.Menu;
package com.smates.dbc2.vo;
public class MenuCheckboxVo {
private String menuId;
private String menuName;
private String parentId;
private String menuUrl;
private Integer order;
private String[] permition;
| private List<Menu> submenus;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/qniu/QniuHelper.java | // Path: src/main/java/com/smates/dbc2/utils/SysConst.java
// public class SysConst {
//
// //md5加密时用到的盐值
// public static final String SALTSOURCE = "baijw";
//
// //七牛云外连接域名
// public static final String QNIUYUNURL = "http://ohyi4k153.bkt.clouddn.com/";
//
// //七牛云图片处理样式
// public static final String QNIUYUNSTYLE = "?imageView2/2/w/80/h/100/interlace/0/q/50";
//
// //资源type
// public static final String VIP = "0";
// public static final String LEARN = "1";
// public static final String GAME = "2";
//
// }
| import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.smates.dbc2.utils.SysConst;
| } catch (Exception e) {
}
}
/**
* 删除七牛云上的文件
*
* @param fileName
* 文件名
*/
public void deleteFile(String fileName) {
// 实例化一个BucketManager对象
BucketManager bucketManager = new BucketManager(auth);
try {
// 调用delete方法移动文件
bucketManager.delete(bucketname, fileName);
logger.info("文件" + fileName + "已删除");
} catch (QiniuException e) {
// 捕获异常信息
Response r = e.response;
logger.info(r.toString());
}
}
/**
* 给用户的头像图片加格式,缩放 100px*80px
* @param imageName 图片文件名
* @return
*/
public String formateUserHeadIcon(String imageName){
| // Path: src/main/java/com/smates/dbc2/utils/SysConst.java
// public class SysConst {
//
// //md5加密时用到的盐值
// public static final String SALTSOURCE = "baijw";
//
// //七牛云外连接域名
// public static final String QNIUYUNURL = "http://ohyi4k153.bkt.clouddn.com/";
//
// //七牛云图片处理样式
// public static final String QNIUYUNSTYLE = "?imageView2/2/w/80/h/100/interlace/0/q/50";
//
// //资源type
// public static final String VIP = "0";
// public static final String LEARN = "1";
// public static final String GAME = "2";
//
// }
// Path: src/main/java/com/smates/dbc2/qniu/QniuHelper.java
import java.io.IOException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.smates.dbc2.utils.SysConst;
} catch (Exception e) {
}
}
/**
* 删除七牛云上的文件
*
* @param fileName
* 文件名
*/
public void deleteFile(String fileName) {
// 实例化一个BucketManager对象
BucketManager bucketManager = new BucketManager(auth);
try {
// 调用delete方法移动文件
bucketManager.delete(bucketname, fileName);
logger.info("文件" + fileName + "已删除");
} catch (QiniuException e) {
// 捕获异常信息
Response r = e.response;
logger.info(r.toString());
}
}
/**
* 给用户的头像图片加格式,缩放 100px*80px
* @param imageName 图片文件名
* @return
*/
public String formateUserHeadIcon(String imageName){
| return imageName+SysConst.QNIUYUNSTYLE;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/controller/RoomLocationController.java | // Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
| import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
| package com.smates.dbc2.controller;
/**
*
* @author 刘晓庆
*
*/
@Controller
public class RoomLocationController {
private Logger logger = Logger.getLogger(RoomLocationController.class);
@Autowired
| // Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
// Path: src/main/java/com/smates/dbc2/controller/RoomLocationController.java
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
package com.smates.dbc2.controller;
/**
*
* @author 刘晓庆
*
*/
@Controller
public class RoomLocationController {
private Logger logger = Logger.getLogger(RoomLocationController.class);
@Autowired
| private RoomLocationService roomLocationService;
|
MarchMachao/ZHFS-WEB | src/main/java/com/smates/dbc2/controller/RoomLocationController.java | // Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
| import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
| package com.smates.dbc2.controller;
/**
*
* @author 刘晓庆
*
*/
@Controller
public class RoomLocationController {
private Logger logger = Logger.getLogger(RoomLocationController.class);
@Autowired
private RoomLocationService roomLocationService;
@ResponseBody
@RequestMapping(value = "getRoomLocation")
| // Path: src/main/java/com/smates/dbc2/po/RoomLocation.java
// public class RoomLocation {
// private String tagNum;
// private String roomName;
// private Integer roomNum;
//
// public RoomLocation() {
// super();
// }
//
// public RoomLocation(String tagNum, String roomName, Integer roomNum) {
// this.tagNum = tagNum;
// this.roomName = roomName;
// this.roomNum = roomNum;
// }
//
// public String getTagNum() {
// return tagNum;
// }
//
// public void setTagNum(String tagNum) {
// this.tagNum = tagNum;
// }
//
// public String getRoomName() {
// return roomName;
// }
//
// public void setRoomName(String roomName) {
// this.roomName = roomName;
// }
//
// public Integer getRoomNum() {
// return roomNum;
// }
//
// public void setRoomNum(Integer roomNum) {
// this.roomNum = roomNum;
// }
//
// @Override
// public String toString() {
// return "RoomLocation [tagNum=" + tagNum + ", roomName=" + roomName + ", roomNum=" + roomNum + "]";
// }
//
// }
//
// Path: src/main/java/com/smates/dbc2/service/RoomLocationService.java
// public interface RoomLocationService {
// /**
// * 查询位置信息
// *
// * @return
// */
// public List<RoomLocation> getRoomLocation();
// }
// Path: src/main/java/com/smates/dbc2/controller/RoomLocationController.java
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smates.dbc2.po.RoomLocation;
import com.smates.dbc2.service.RoomLocationService;
package com.smates.dbc2.controller;
/**
*
* @author 刘晓庆
*
*/
@Controller
public class RoomLocationController {
private Logger logger = Logger.getLogger(RoomLocationController.class);
@Autowired
private RoomLocationService roomLocationService;
@ResponseBody
@RequestMapping(value = "getRoomLocation")
| public List<RoomLocation> getRoomLocation() {
|
tomzo/gocd-yaml-config-plugin | src/test/java/cd/go/plugin/config/yaml/transforms/RootTransformTest.java | // Path: src/main/java/cd/go/plugin/config/yaml/JsonConfigCollection.java
// public class JsonConfigCollection {
// private static final int DEFAULT_VERSION = 1;
// private final Gson gson;
//
// private Set<Integer> uniqueVersions = new HashSet<>();
// private JsonObject mainObject = new JsonObject();
// private JsonArray environments = new JsonArray();
// private JsonArray pipelines = new JsonArray();
// private JsonArray errors = new JsonArray();
//
// public JsonConfigCollection() {
// gson = new Gson();
//
// updateTargetVersionTo(DEFAULT_VERSION);
// mainObject.add("environments", environments);
// mainObject.add("pipelines", pipelines);
// mainObject.add("errors", errors);
// }
//
// protected JsonArray getEnvironments() {
// return environments;
// }
//
// public void addEnvironment(JsonElement environment, String location) {
// environments.add(environment);
// environment.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonObject getJsonObject() {
// return mainObject;
// }
//
// public void addPipeline(JsonElement pipeline, String location) {
// pipelines.add(pipeline);
// pipeline.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonArray getPipelines() {
// return pipelines;
// }
//
// public JsonArray getErrors() {
// return errors;
// }
//
// public void addError(String message, String location) {
// this.addError(new PluginError(message, location));
// }
//
// public void addError(PluginError error) {
// errors.add(gson.toJsonTree(error));
// }
//
// public void append(JsonConfigCollection other) {
// this.environments.addAll(other.environments);
// this.pipelines.addAll(other.pipelines);
// this.errors.addAll(other.errors);
// this.uniqueVersions.addAll(other.uniqueVersions);
// }
//
// public void updateFormatVersionFound(int version) {
// uniqueVersions.add(version);
// updateTargetVersionTo(version);
// }
//
// public void updateTargetVersionFromFiles() {
// if (uniqueVersions.size() > 1) {
// throw new RuntimeException("Versions across files are not unique. Found versions: " + uniqueVersions + ". There can only be one version across the whole repository.");
// }
// updateTargetVersionTo(uniqueVersions.iterator().hasNext() ? uniqueVersions.iterator().next() : DEFAULT_VERSION);
// }
//
// private void updateTargetVersionTo(int targetVersion) {
// mainObject.remove("target_version");
// mainObject.add("target_version", new JsonPrimitive(targetVersion));
// }
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static Object readYamlObject(String path) throws IOException {
// YamlConfig config = new YamlConfig();
// config.setAllowDuplicates(false);
// YamlReader reader = new YamlReader(TestUtils.createReader(path), config);
// return reader.read();
// }
| import cd.go.plugin.config.yaml.JsonConfigCollection;
import cd.go.plugin.config.yaml.YamlConfigException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static cd.go.plugin.config.yaml.TestUtils.readYamlObject;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock; | package cd.go.plugin.config.yaml.transforms;
public class RootTransformTest {
private RootTransform rootTransform;
private PipelineTransform pipelineTransform;
private EnvironmentsTransform environmentsTransform;
@Before
public void Setup() {
pipelineTransform = mock(PipelineTransform.class);
environmentsTransform = mock(EnvironmentsTransform.class);
rootTransform = new RootTransform(pipelineTransform, environmentsTransform);
}
@Test
public void shouldTransformEmptyRoot() throws IOException { | // Path: src/main/java/cd/go/plugin/config/yaml/JsonConfigCollection.java
// public class JsonConfigCollection {
// private static final int DEFAULT_VERSION = 1;
// private final Gson gson;
//
// private Set<Integer> uniqueVersions = new HashSet<>();
// private JsonObject mainObject = new JsonObject();
// private JsonArray environments = new JsonArray();
// private JsonArray pipelines = new JsonArray();
// private JsonArray errors = new JsonArray();
//
// public JsonConfigCollection() {
// gson = new Gson();
//
// updateTargetVersionTo(DEFAULT_VERSION);
// mainObject.add("environments", environments);
// mainObject.add("pipelines", pipelines);
// mainObject.add("errors", errors);
// }
//
// protected JsonArray getEnvironments() {
// return environments;
// }
//
// public void addEnvironment(JsonElement environment, String location) {
// environments.add(environment);
// environment.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonObject getJsonObject() {
// return mainObject;
// }
//
// public void addPipeline(JsonElement pipeline, String location) {
// pipelines.add(pipeline);
// pipeline.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonArray getPipelines() {
// return pipelines;
// }
//
// public JsonArray getErrors() {
// return errors;
// }
//
// public void addError(String message, String location) {
// this.addError(new PluginError(message, location));
// }
//
// public void addError(PluginError error) {
// errors.add(gson.toJsonTree(error));
// }
//
// public void append(JsonConfigCollection other) {
// this.environments.addAll(other.environments);
// this.pipelines.addAll(other.pipelines);
// this.errors.addAll(other.errors);
// this.uniqueVersions.addAll(other.uniqueVersions);
// }
//
// public void updateFormatVersionFound(int version) {
// uniqueVersions.add(version);
// updateTargetVersionTo(version);
// }
//
// public void updateTargetVersionFromFiles() {
// if (uniqueVersions.size() > 1) {
// throw new RuntimeException("Versions across files are not unique. Found versions: " + uniqueVersions + ". There can only be one version across the whole repository.");
// }
// updateTargetVersionTo(uniqueVersions.iterator().hasNext() ? uniqueVersions.iterator().next() : DEFAULT_VERSION);
// }
//
// private void updateTargetVersionTo(int targetVersion) {
// mainObject.remove("target_version");
// mainObject.add("target_version", new JsonPrimitive(targetVersion));
// }
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static Object readYamlObject(String path) throws IOException {
// YamlConfig config = new YamlConfig();
// config.setAllowDuplicates(false);
// YamlReader reader = new YamlReader(TestUtils.createReader(path), config);
// return reader.read();
// }
// Path: src/test/java/cd/go/plugin/config/yaml/transforms/RootTransformTest.java
import cd.go.plugin.config.yaml.JsonConfigCollection;
import cd.go.plugin.config.yaml.YamlConfigException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static cd.go.plugin.config.yaml.TestUtils.readYamlObject;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
package cd.go.plugin.config.yaml.transforms;
public class RootTransformTest {
private RootTransform rootTransform;
private PipelineTransform pipelineTransform;
private EnvironmentsTransform environmentsTransform;
@Before
public void Setup() {
pipelineTransform = mock(PipelineTransform.class);
environmentsTransform = mock(EnvironmentsTransform.class);
rootTransform = new RootTransform(pipelineTransform, environmentsTransform);
}
@Test
public void shouldTransformEmptyRoot() throws IOException { | JsonConfigCollection empty = readRootYaml("empty"); |
tomzo/gocd-yaml-config-plugin | src/test/java/cd/go/plugin/config/yaml/transforms/RootTransformTest.java | // Path: src/main/java/cd/go/plugin/config/yaml/JsonConfigCollection.java
// public class JsonConfigCollection {
// private static final int DEFAULT_VERSION = 1;
// private final Gson gson;
//
// private Set<Integer> uniqueVersions = new HashSet<>();
// private JsonObject mainObject = new JsonObject();
// private JsonArray environments = new JsonArray();
// private JsonArray pipelines = new JsonArray();
// private JsonArray errors = new JsonArray();
//
// public JsonConfigCollection() {
// gson = new Gson();
//
// updateTargetVersionTo(DEFAULT_VERSION);
// mainObject.add("environments", environments);
// mainObject.add("pipelines", pipelines);
// mainObject.add("errors", errors);
// }
//
// protected JsonArray getEnvironments() {
// return environments;
// }
//
// public void addEnvironment(JsonElement environment, String location) {
// environments.add(environment);
// environment.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonObject getJsonObject() {
// return mainObject;
// }
//
// public void addPipeline(JsonElement pipeline, String location) {
// pipelines.add(pipeline);
// pipeline.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonArray getPipelines() {
// return pipelines;
// }
//
// public JsonArray getErrors() {
// return errors;
// }
//
// public void addError(String message, String location) {
// this.addError(new PluginError(message, location));
// }
//
// public void addError(PluginError error) {
// errors.add(gson.toJsonTree(error));
// }
//
// public void append(JsonConfigCollection other) {
// this.environments.addAll(other.environments);
// this.pipelines.addAll(other.pipelines);
// this.errors.addAll(other.errors);
// this.uniqueVersions.addAll(other.uniqueVersions);
// }
//
// public void updateFormatVersionFound(int version) {
// uniqueVersions.add(version);
// updateTargetVersionTo(version);
// }
//
// public void updateTargetVersionFromFiles() {
// if (uniqueVersions.size() > 1) {
// throw new RuntimeException("Versions across files are not unique. Found versions: " + uniqueVersions + ". There can only be one version across the whole repository.");
// }
// updateTargetVersionTo(uniqueVersions.iterator().hasNext() ? uniqueVersions.iterator().next() : DEFAULT_VERSION);
// }
//
// private void updateTargetVersionTo(int targetVersion) {
// mainObject.remove("target_version");
// mainObject.add("target_version", new JsonPrimitive(targetVersion));
// }
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static Object readYamlObject(String path) throws IOException {
// YamlConfig config = new YamlConfig();
// config.setAllowDuplicates(false);
// YamlReader reader = new YamlReader(TestUtils.createReader(path), config);
// return reader.read();
// }
| import cd.go.plugin.config.yaml.JsonConfigCollection;
import cd.go.plugin.config.yaml.YamlConfigException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static cd.go.plugin.config.yaml.TestUtils.readYamlObject;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock; | @Test
public void shouldRecognizeAndUpdateVersion() throws Exception {
assertTargetVersion(readRootYaml("version_not_present").getJsonObject(), 1);
assertTargetVersion(readRootYaml("version_1").getJsonObject(), 1);
assertTargetVersion(readRootYaml("version_2").getJsonObject(), 2);
}
@Test
public void shouldPreserveOrderOfPipelines() throws IOException {
MaterialTransform materialTransform = mock(MaterialTransform.class);
StageTransform stageTransform = mock(StageTransform.class);
EnvironmentVariablesTransform environmentTransform = mock(EnvironmentVariablesTransform.class);
ParameterTransform parameterTransform = mock(ParameterTransform.class);
pipelineTransform = new PipelineTransform(materialTransform, stageTransform, environmentTransform, parameterTransform);
rootTransform = new RootTransform(pipelineTransform, environmentsTransform);
JsonConfigCollection collection = readRootYaml("pipeline_order");
JsonArray pipelines = collection.getJsonObject().get("pipelines").getAsJsonArray();
assertThat(pipelines.get(0).getAsJsonObject().get("name").getAsString(), is("pipe1"));
assertThat(pipelines.get(1).getAsJsonObject().get("name").getAsString(), is("pipe2"));
assertThat(pipelines.get(2).getAsJsonObject().get("name").getAsString(), is("pipe3"));
}
@Test(expected = YamlReader.YamlReaderException.class)
public void shouldNotTransformRootWhenYAMLHasDuplicateKeys() throws IOException {
readRootYaml("duplicate.materials.pipe");
fail("should have thrown duplicate keys error");
}
private JsonConfigCollection readRootYaml(String caseFile) throws IOException { | // Path: src/main/java/cd/go/plugin/config/yaml/JsonConfigCollection.java
// public class JsonConfigCollection {
// private static final int DEFAULT_VERSION = 1;
// private final Gson gson;
//
// private Set<Integer> uniqueVersions = new HashSet<>();
// private JsonObject mainObject = new JsonObject();
// private JsonArray environments = new JsonArray();
// private JsonArray pipelines = new JsonArray();
// private JsonArray errors = new JsonArray();
//
// public JsonConfigCollection() {
// gson = new Gson();
//
// updateTargetVersionTo(DEFAULT_VERSION);
// mainObject.add("environments", environments);
// mainObject.add("pipelines", pipelines);
// mainObject.add("errors", errors);
// }
//
// protected JsonArray getEnvironments() {
// return environments;
// }
//
// public void addEnvironment(JsonElement environment, String location) {
// environments.add(environment);
// environment.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonObject getJsonObject() {
// return mainObject;
// }
//
// public void addPipeline(JsonElement pipeline, String location) {
// pipelines.add(pipeline);
// pipeline.getAsJsonObject().add("location", new JsonPrimitive(location));
// }
//
// public JsonArray getPipelines() {
// return pipelines;
// }
//
// public JsonArray getErrors() {
// return errors;
// }
//
// public void addError(String message, String location) {
// this.addError(new PluginError(message, location));
// }
//
// public void addError(PluginError error) {
// errors.add(gson.toJsonTree(error));
// }
//
// public void append(JsonConfigCollection other) {
// this.environments.addAll(other.environments);
// this.pipelines.addAll(other.pipelines);
// this.errors.addAll(other.errors);
// this.uniqueVersions.addAll(other.uniqueVersions);
// }
//
// public void updateFormatVersionFound(int version) {
// uniqueVersions.add(version);
// updateTargetVersionTo(version);
// }
//
// public void updateTargetVersionFromFiles() {
// if (uniqueVersions.size() > 1) {
// throw new RuntimeException("Versions across files are not unique. Found versions: " + uniqueVersions + ". There can only be one version across the whole repository.");
// }
// updateTargetVersionTo(uniqueVersions.iterator().hasNext() ? uniqueVersions.iterator().next() : DEFAULT_VERSION);
// }
//
// private void updateTargetVersionTo(int targetVersion) {
// mainObject.remove("target_version");
// mainObject.add("target_version", new JsonPrimitive(targetVersion));
// }
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static Object readYamlObject(String path) throws IOException {
// YamlConfig config = new YamlConfig();
// config.setAllowDuplicates(false);
// YamlReader reader = new YamlReader(TestUtils.createReader(path), config);
// return reader.read();
// }
// Path: src/test/java/cd/go/plugin/config/yaml/transforms/RootTransformTest.java
import cd.go.plugin.config.yaml.JsonConfigCollection;
import cd.go.plugin.config.yaml.YamlConfigException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static cd.go.plugin.config.yaml.TestUtils.readYamlObject;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
@Test
public void shouldRecognizeAndUpdateVersion() throws Exception {
assertTargetVersion(readRootYaml("version_not_present").getJsonObject(), 1);
assertTargetVersion(readRootYaml("version_1").getJsonObject(), 1);
assertTargetVersion(readRootYaml("version_2").getJsonObject(), 2);
}
@Test
public void shouldPreserveOrderOfPipelines() throws IOException {
MaterialTransform materialTransform = mock(MaterialTransform.class);
StageTransform stageTransform = mock(StageTransform.class);
EnvironmentVariablesTransform environmentTransform = mock(EnvironmentVariablesTransform.class);
ParameterTransform parameterTransform = mock(ParameterTransform.class);
pipelineTransform = new PipelineTransform(materialTransform, stageTransform, environmentTransform, parameterTransform);
rootTransform = new RootTransform(pipelineTransform, environmentsTransform);
JsonConfigCollection collection = readRootYaml("pipeline_order");
JsonArray pipelines = collection.getJsonObject().get("pipelines").getAsJsonArray();
assertThat(pipelines.get(0).getAsJsonObject().get("name").getAsString(), is("pipe1"));
assertThat(pipelines.get(1).getAsJsonObject().get("name").getAsString(), is("pipe2"));
assertThat(pipelines.get(2).getAsJsonObject().get("name").getAsString(), is("pipe3"));
}
@Test(expected = YamlReader.YamlReaderException.class)
public void shouldNotTransformRootWhenYAMLHasDuplicateKeys() throws IOException {
readRootYaml("duplicate.materials.pipe");
fail("should have thrown duplicate keys error");
}
private JsonConfigCollection readRootYaml(String caseFile) throws IOException { | return rootTransform.transform(readYamlObject("parts/roots/" + caseFile + ".yaml"), "test code"); |
tomzo/gocd-yaml-config-plugin | src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentsTransform.java | // Path: src/main/java/cd/go/plugin/config/yaml/YamlUtils.java
// public static void addOptionalStringList(JsonObject jsonObject, Map<String, Object> yamlSource, String jsonField, String yamlFieldName) {
// JsonArray value = getOptionalStringList(yamlSource, yamlFieldName);
// if (value != null)
// jsonObject.add(jsonField, value);
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentVariablesTransform.java
// public static final String JSON_ENV_VAR_FIELD = "environment_variables";
| import cd.go.plugin.config.yaml.YamlConfigException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Map;
import static cd.go.plugin.config.yaml.YamlUtils.addOptionalStringList;
import static cd.go.plugin.config.yaml.transforms.EnvironmentVariablesTransform.JSON_ENV_VAR_FIELD; | package cd.go.plugin.config.yaml.transforms;
public class EnvironmentsTransform {
private static final String JSON_ENV_NAME_FIELD = "name";
private EnvironmentVariablesTransform environmentVariablesTransform;
public EnvironmentsTransform(EnvironmentVariablesTransform environmentVariablesTransform) {
this.environmentVariablesTransform = environmentVariablesTransform;
}
public JsonObject transform(Object yamlObject) {
Map<String, Object> map = (Map<String, Object>) yamlObject;
for (Map.Entry<String, Object> entry : map.entrySet()) {
return transform(entry);
}
throw new RuntimeException("expected environments hash to have 1 item");
}
public JsonObject transform(Map.Entry<String, Object> env) {
String envName = env.getKey();
JsonObject envJson = new JsonObject();
envJson.addProperty(JSON_ENV_NAME_FIELD, envName);
Object envObj = env.getValue();
if (envObj == null)
return envJson;
if (!(envObj instanceof Map))
throw new YamlConfigException("Expected environment to be a hash");
Map<String, Object> envMap = (Map<String, Object>) envObj; | // Path: src/main/java/cd/go/plugin/config/yaml/YamlUtils.java
// public static void addOptionalStringList(JsonObject jsonObject, Map<String, Object> yamlSource, String jsonField, String yamlFieldName) {
// JsonArray value = getOptionalStringList(yamlSource, yamlFieldName);
// if (value != null)
// jsonObject.add(jsonField, value);
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentVariablesTransform.java
// public static final String JSON_ENV_VAR_FIELD = "environment_variables";
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentsTransform.java
import cd.go.plugin.config.yaml.YamlConfigException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Map;
import static cd.go.plugin.config.yaml.YamlUtils.addOptionalStringList;
import static cd.go.plugin.config.yaml.transforms.EnvironmentVariablesTransform.JSON_ENV_VAR_FIELD;
package cd.go.plugin.config.yaml.transforms;
public class EnvironmentsTransform {
private static final String JSON_ENV_NAME_FIELD = "name";
private EnvironmentVariablesTransform environmentVariablesTransform;
public EnvironmentsTransform(EnvironmentVariablesTransform environmentVariablesTransform) {
this.environmentVariablesTransform = environmentVariablesTransform;
}
public JsonObject transform(Object yamlObject) {
Map<String, Object> map = (Map<String, Object>) yamlObject;
for (Map.Entry<String, Object> entry : map.entrySet()) {
return transform(entry);
}
throw new RuntimeException("expected environments hash to have 1 item");
}
public JsonObject transform(Map.Entry<String, Object> env) {
String envName = env.getKey();
JsonObject envJson = new JsonObject();
envJson.addProperty(JSON_ENV_NAME_FIELD, envName);
Object envObj = env.getValue();
if (envObj == null)
return envJson;
if (!(envObj instanceof Map))
throw new YamlConfigException("Expected environment to be a hash");
Map<String, Object> envMap = (Map<String, Object>) envObj; | addOptionalStringList(envJson, envMap, "agents", "agents"); |
tomzo/gocd-yaml-config-plugin | src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentsTransform.java | // Path: src/main/java/cd/go/plugin/config/yaml/YamlUtils.java
// public static void addOptionalStringList(JsonObject jsonObject, Map<String, Object> yamlSource, String jsonField, String yamlFieldName) {
// JsonArray value = getOptionalStringList(yamlSource, yamlFieldName);
// if (value != null)
// jsonObject.add(jsonField, value);
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentVariablesTransform.java
// public static final String JSON_ENV_VAR_FIELD = "environment_variables";
| import cd.go.plugin.config.yaml.YamlConfigException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Map;
import static cd.go.plugin.config.yaml.YamlUtils.addOptionalStringList;
import static cd.go.plugin.config.yaml.transforms.EnvironmentVariablesTransform.JSON_ENV_VAR_FIELD; | package cd.go.plugin.config.yaml.transforms;
public class EnvironmentsTransform {
private static final String JSON_ENV_NAME_FIELD = "name";
private EnvironmentVariablesTransform environmentVariablesTransform;
public EnvironmentsTransform(EnvironmentVariablesTransform environmentVariablesTransform) {
this.environmentVariablesTransform = environmentVariablesTransform;
}
public JsonObject transform(Object yamlObject) {
Map<String, Object> map = (Map<String, Object>) yamlObject;
for (Map.Entry<String, Object> entry : map.entrySet()) {
return transform(entry);
}
throw new RuntimeException("expected environments hash to have 1 item");
}
public JsonObject transform(Map.Entry<String, Object> env) {
String envName = env.getKey();
JsonObject envJson = new JsonObject();
envJson.addProperty(JSON_ENV_NAME_FIELD, envName);
Object envObj = env.getValue();
if (envObj == null)
return envJson;
if (!(envObj instanceof Map))
throw new YamlConfigException("Expected environment to be a hash");
Map<String, Object> envMap = (Map<String, Object>) envObj;
addOptionalStringList(envJson, envMap, "agents", "agents");
addOptionalStringList(envJson, envMap, "pipelines", "pipelines");
JsonArray jsonEnvVariables = environmentVariablesTransform.transform(envMap);
if (jsonEnvVariables != null && jsonEnvVariables.size() > 0) | // Path: src/main/java/cd/go/plugin/config/yaml/YamlUtils.java
// public static void addOptionalStringList(JsonObject jsonObject, Map<String, Object> yamlSource, String jsonField, String yamlFieldName) {
// JsonArray value = getOptionalStringList(yamlSource, yamlFieldName);
// if (value != null)
// jsonObject.add(jsonField, value);
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentVariablesTransform.java
// public static final String JSON_ENV_VAR_FIELD = "environment_variables";
// Path: src/main/java/cd/go/plugin/config/yaml/transforms/EnvironmentsTransform.java
import cd.go.plugin.config.yaml.YamlConfigException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Map;
import static cd.go.plugin.config.yaml.YamlUtils.addOptionalStringList;
import static cd.go.plugin.config.yaml.transforms.EnvironmentVariablesTransform.JSON_ENV_VAR_FIELD;
package cd.go.plugin.config.yaml.transforms;
public class EnvironmentsTransform {
private static final String JSON_ENV_NAME_FIELD = "name";
private EnvironmentVariablesTransform environmentVariablesTransform;
public EnvironmentsTransform(EnvironmentVariablesTransform environmentVariablesTransform) {
this.environmentVariablesTransform = environmentVariablesTransform;
}
public JsonObject transform(Object yamlObject) {
Map<String, Object> map = (Map<String, Object>) yamlObject;
for (Map.Entry<String, Object> entry : map.entrySet()) {
return transform(entry);
}
throw new RuntimeException("expected environments hash to have 1 item");
}
public JsonObject transform(Map.Entry<String, Object> env) {
String envName = env.getKey();
JsonObject envJson = new JsonObject();
envJson.addProperty(JSON_ENV_NAME_FIELD, envName);
Object envObj = env.getValue();
if (envObj == null)
return envJson;
if (!(envObj instanceof Map))
throw new YamlConfigException("Expected environment to be a hash");
Map<String, Object> envMap = (Map<String, Object>) envObj;
addOptionalStringList(envJson, envMap, "agents", "agents");
addOptionalStringList(envJson, envMap, "pipelines", "pipelines");
JsonArray jsonEnvVariables = environmentVariablesTransform.transform(envMap);
if (jsonEnvVariables != null && jsonEnvVariables.size() > 0) | envJson.add(JSON_ENV_VAR_FIELD, jsonEnvVariables); |
tomzo/gocd-yaml-config-plugin | src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java | // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
| import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*; | package cd.go.plugin.config.yaml;
public class YamlConfigPluginIntegrationTest {
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
private YamlConfigPlugin plugin;
private GoApplicationAccessor goAccessor;
private JsonParser parser;
@Before
public void setUp() {
plugin = new YamlConfigPlugin();
goAccessor = mock(GoApplicationAccessor.class);
plugin.initializeGoApplicationAccessor(goAccessor);
GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
parser = new JsonParser();
}
@Test
public void respondsToParseContentRequest() throws Exception {
final Gson gson = new Gson();
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", ConfigRepoMessages.REQ_PARSE_CONTENT);
StringWriter w = new StringWriter(); | // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
// Path: src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java
import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
package cd.go.plugin.config.yaml;
public class YamlConfigPluginIntegrationTest {
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
private YamlConfigPlugin plugin;
private GoApplicationAccessor goAccessor;
private JsonParser parser;
@Before
public void setUp() {
plugin = new YamlConfigPlugin();
goAccessor = mock(GoApplicationAccessor.class);
plugin.initializeGoApplicationAccessor(goAccessor);
GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
parser = new JsonParser();
}
@Test
public void respondsToParseContentRequest() throws Exception {
final Gson gson = new Gson();
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", ConfigRepoMessages.REQ_PARSE_CONTENT);
StringWriter w = new StringWriter(); | IOUtils.copy(getResourceAsStream("examples/simple.gocd.yaml"), w); |
tomzo/gocd-yaml-config-plugin | src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java | // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
| import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*; | @Before
public void setUp() {
plugin = new YamlConfigPlugin();
goAccessor = mock(GoApplicationAccessor.class);
plugin.initializeGoApplicationAccessor(goAccessor);
GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
parser = new JsonParser();
}
@Test
public void respondsToParseContentRequest() throws Exception {
final Gson gson = new Gson();
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", ConfigRepoMessages.REQ_PARSE_CONTENT);
StringWriter w = new StringWriter();
IOUtils.copy(getResourceAsStream("examples/simple.gocd.yaml"), w);
request.setRequestBody(gson.toJson(
Collections.singletonMap("contents",
Collections.singletonMap("simple.gocd.yaml", w.toString())
)
));
GoPluginApiResponse response = plugin.handle(request);
assertEquals(SUCCESS_RESPONSE_CODE, response.responseCode());
JsonObject responseJsonObject = getJsonObjectFromResponse(response);
assertNoError(responseJsonObject);
JsonArray pipelines = responseJsonObject.get("pipelines").getAsJsonArray();
assertThat(pipelines.size(), is(1)); | // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
// Path: src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java
import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@Before
public void setUp() {
plugin = new YamlConfigPlugin();
goAccessor = mock(GoApplicationAccessor.class);
plugin.initializeGoApplicationAccessor(goAccessor);
GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
parser = new JsonParser();
}
@Test
public void respondsToParseContentRequest() throws Exception {
final Gson gson = new Gson();
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", ConfigRepoMessages.REQ_PARSE_CONTENT);
StringWriter w = new StringWriter();
IOUtils.copy(getResourceAsStream("examples/simple.gocd.yaml"), w);
request.setRequestBody(gson.toJson(
Collections.singletonMap("contents",
Collections.singletonMap("simple.gocd.yaml", w.toString())
)
));
GoPluginApiResponse response = plugin.handle(request);
assertEquals(SUCCESS_RESPONSE_CODE, response.responseCode());
JsonObject responseJsonObject = getJsonObjectFromResponse(response);
assertNoError(responseJsonObject);
JsonArray pipelines = responseJsonObject.get("pipelines").getAsJsonArray();
assertThat(pipelines.size(), is(1)); | JsonObject expected = (JsonObject) readJsonObject("examples.out/simple.gocd.json"); |
tomzo/gocd-yaml-config-plugin | src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java | // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
| import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*; | String requestBody = null;
parseDirectoryRequest.setRequestBody(requestBody);
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldRespondBadRequestToParseDirectoryRequestWhenRequestBodyIsEmpty() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest parseDirectoryRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "parse-directory");
parseDirectoryRequest.setRequestBody("{}");
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldRespondBadRequestToParseDirectoryRequestWhenRequestBodyIsNotJson() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest parseDirectoryRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "parse-directory");
parseDirectoryRequest.setRequestBody("{bla");
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldConsumePluginSettingsOnConfigChangeRequest() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", REQ_PLUGIN_SETTINGS_CHANGED);
request.setRequestBody("{\"file_pattern\": \"*.foo.gocd.yaml\"}");
| // Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// static InputStream getResourceAsStream(String resource) {
// final InputStream in
// = getContextClassLoader().getResourceAsStream(resource);
//
// return in == null ? TestUtils.class.getResourceAsStream(resource) : in;
// }
//
// Path: src/test/java/cd/go/plugin/config/yaml/TestUtils.java
// public static JsonElement readJsonObject(String path) {
// JsonParser parser = new JsonParser();
// return parser.parse(TestUtils.createReader(path));
// }
// Path: src/test/java/cd/go/plugin/config/yaml/YamlConfigPluginIntegrationTest.java
import com.google.gson.*;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.request.DefaultGoPluginApiRequest;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Base64;
import java.util.Collections;
import static cd.go.plugin.config.yaml.ConfigRepoMessages.REQ_PLUGIN_SETTINGS_CHANGED;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.TestUtils.getResourceAsStream;
import static cd.go.plugin.config.yaml.TestUtils.readJsonObject;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
String requestBody = null;
parseDirectoryRequest.setRequestBody(requestBody);
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldRespondBadRequestToParseDirectoryRequestWhenRequestBodyIsEmpty() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest parseDirectoryRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "parse-directory");
parseDirectoryRequest.setRequestBody("{}");
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldRespondBadRequestToParseDirectoryRequestWhenRequestBodyIsNotJson() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest parseDirectoryRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "parse-directory");
parseDirectoryRequest.setRequestBody("{bla");
GoPluginApiResponse response = plugin.handle(parseDirectoryRequest);
assertThat(response.responseCode(), is(DefaultGoPluginApiResponse.BAD_REQUEST));
}
@Test
public void shouldConsumePluginSettingsOnConfigChangeRequest() throws UnhandledRequestTypeException {
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("configrepo", "2.0", REQ_PLUGIN_SETTINGS_CHANGED);
request.setRequestBody("{\"file_pattern\": \"*.foo.gocd.yaml\"}");
| assertEquals(DEFAULT_FILE_PATTERN, plugin.getFilePattern()); |
tomzo/gocd-yaml-config-plugin | src/main/java/cd/go/plugin/config/yaml/YamlConfigPlugin.java | // Path: src/main/java/cd/go/plugin/config/yaml/transforms/RootTransform.java
// public class RootTransform {
// private PipelineTransform pipelineTransform;
// private EnvironmentsTransform environmentsTransform;
//
// public RootTransform() {
// EnvironmentVariablesTransform environmentVarsTransform = new EnvironmentVariablesTransform();
// MaterialTransform material = new MaterialTransform();
// ParameterTransform parameterTransform = new ParameterTransform();
// JobTransform job = new JobTransform(environmentVarsTransform, new TaskTransform());
// StageTransform stage = new StageTransform(environmentVarsTransform, job);
// this.pipelineTransform = new PipelineTransform(material, stage, environmentVarsTransform, parameterTransform);
// this.environmentsTransform = new EnvironmentsTransform(environmentVarsTransform);
// }
//
// public RootTransform(PipelineTransform pipelineTransform, EnvironmentsTransform environmentsTransform) {
// this.pipelineTransform = pipelineTransform;
// this.environmentsTransform = environmentsTransform;
// }
//
// public String inverseTransformPipeline(Map<String, Object> pipeline) {
// Map<String, Object> result = new LinkedTreeMap<>();
// result.put("format_version", 10);
// result.put("pipelines", pipelineTransform.inverseTransform(pipeline));
// return YamlUtils.dump(result);
// }
//
// public JsonConfigCollection transform(Object rootObj, String location) {
// JsonConfigCollection partialConfig = new JsonConfigCollection();
// Map<String, Object> rootMap = (Map<String, Object>) rootObj;
// // must obtain format_version first
// int formatVersion = 1;
// for (Map.Entry<String, Object> pe : rootMap.entrySet()) {
// if ("format_version".equalsIgnoreCase(pe.getKey())) {
// formatVersion = Integer.valueOf((String) pe.getValue());
// partialConfig.updateFormatVersionFound(formatVersion);
// }
// }
// for (Map.Entry<String, Object> pe : rootMap.entrySet()) {
// if ("pipelines".equalsIgnoreCase(pe.getKey())) {
// if (pe.getValue() == null)
// continue;
// Map<String, Object> pipelines = (Map<String, Object>) pe.getValue();
// for (Map.Entry<String, Object> pipe : pipelines.entrySet()) {
// try {
// JsonElement jsonPipeline = pipelineTransform.transform(pipe, formatVersion);
// partialConfig.addPipeline(jsonPipeline, location);
// } catch (Exception ex) {
// partialConfig.addError(new PluginError(
// String.format("Failed to parse pipeline %s; %s", pipe.getKey(), ex.getMessage()), location));
// }
// }
// } else if ("environments".equalsIgnoreCase(pe.getKey())) {
// if (pe.getValue() == null)
// continue;
// Map<String, Object> environments = (Map<String, Object>) pe.getValue();
// for (Map.Entry<String, Object> env : environments.entrySet()) {
// try {
// JsonElement jsonEnvironment = environmentsTransform.transform(env);
// partialConfig.addEnvironment(jsonEnvironment, location);
// } catch (Exception ex) {
// partialConfig.addError(new PluginError(
// String.format("Failed to parse environment %s; %s", env.getKey(), ex.getMessage()), location));
// }
// }
// } else if (!"common".equalsIgnoreCase(pe.getKey()) && !"format_version".equalsIgnoreCase(pe.getKey()))
// throw new YamlConfigException(pe.getKey() + " is invalid, expected format_version, pipelines, environments, or common");
// }
// return partialConfig;
// }
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String PLUGIN_SETTINGS_FILE_PATTERN = "file_pattern";
| import cd.go.plugin.config.yaml.transforms.RootTransform;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.PluginSettings.PLUGIN_SETTINGS_FILE_PATTERN;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.*;
import static java.lang.String.format; | return handlePipelineExportRequest(request);
case REQ_GET_CAPABILITIES:
return success(gson.toJson(new Capabilities()));
case REQ_PLUGIN_SETTINGS_CHANGED:
configurePlugin(PluginSettings.fromJson(request.requestBody()));
return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, "");
case REQ_GET_ICON:
return handleGetIconRequest();
default:
throw new UnhandledRequestTypeException(requestName);
}
}
private GoPluginApiResponse handleGetIconRequest() {
try {
JsonObject jsonObject = new JsonObject();
byte[] contents = IOUtils.toByteArray(getClass().getResourceAsStream("/yaml.svg"));
jsonObject.addProperty("content_type", "image/svg+xml");
jsonObject.addProperty("data", Base64.getEncoder().encodeToString(contents));
return success(gson.toJson(jsonObject));
} catch (IOException e) {
return error(e.getMessage());
}
}
String getFilePattern() {
if (null != settings && !isBlank(settings.getFilePattern())) {
return settings.getFilePattern();
} | // Path: src/main/java/cd/go/plugin/config/yaml/transforms/RootTransform.java
// public class RootTransform {
// private PipelineTransform pipelineTransform;
// private EnvironmentsTransform environmentsTransform;
//
// public RootTransform() {
// EnvironmentVariablesTransform environmentVarsTransform = new EnvironmentVariablesTransform();
// MaterialTransform material = new MaterialTransform();
// ParameterTransform parameterTransform = new ParameterTransform();
// JobTransform job = new JobTransform(environmentVarsTransform, new TaskTransform());
// StageTransform stage = new StageTransform(environmentVarsTransform, job);
// this.pipelineTransform = new PipelineTransform(material, stage, environmentVarsTransform, parameterTransform);
// this.environmentsTransform = new EnvironmentsTransform(environmentVarsTransform);
// }
//
// public RootTransform(PipelineTransform pipelineTransform, EnvironmentsTransform environmentsTransform) {
// this.pipelineTransform = pipelineTransform;
// this.environmentsTransform = environmentsTransform;
// }
//
// public String inverseTransformPipeline(Map<String, Object> pipeline) {
// Map<String, Object> result = new LinkedTreeMap<>();
// result.put("format_version", 10);
// result.put("pipelines", pipelineTransform.inverseTransform(pipeline));
// return YamlUtils.dump(result);
// }
//
// public JsonConfigCollection transform(Object rootObj, String location) {
// JsonConfigCollection partialConfig = new JsonConfigCollection();
// Map<String, Object> rootMap = (Map<String, Object>) rootObj;
// // must obtain format_version first
// int formatVersion = 1;
// for (Map.Entry<String, Object> pe : rootMap.entrySet()) {
// if ("format_version".equalsIgnoreCase(pe.getKey())) {
// formatVersion = Integer.valueOf((String) pe.getValue());
// partialConfig.updateFormatVersionFound(formatVersion);
// }
// }
// for (Map.Entry<String, Object> pe : rootMap.entrySet()) {
// if ("pipelines".equalsIgnoreCase(pe.getKey())) {
// if (pe.getValue() == null)
// continue;
// Map<String, Object> pipelines = (Map<String, Object>) pe.getValue();
// for (Map.Entry<String, Object> pipe : pipelines.entrySet()) {
// try {
// JsonElement jsonPipeline = pipelineTransform.transform(pipe, formatVersion);
// partialConfig.addPipeline(jsonPipeline, location);
// } catch (Exception ex) {
// partialConfig.addError(new PluginError(
// String.format("Failed to parse pipeline %s; %s", pipe.getKey(), ex.getMessage()), location));
// }
// }
// } else if ("environments".equalsIgnoreCase(pe.getKey())) {
// if (pe.getValue() == null)
// continue;
// Map<String, Object> environments = (Map<String, Object>) pe.getValue();
// for (Map.Entry<String, Object> env : environments.entrySet()) {
// try {
// JsonElement jsonEnvironment = environmentsTransform.transform(env);
// partialConfig.addEnvironment(jsonEnvironment, location);
// } catch (Exception ex) {
// partialConfig.addError(new PluginError(
// String.format("Failed to parse environment %s; %s", env.getKey(), ex.getMessage()), location));
// }
// }
// } else if (!"common".equalsIgnoreCase(pe.getKey()) && !"format_version".equalsIgnoreCase(pe.getKey()))
// throw new YamlConfigException(pe.getKey() + " is invalid, expected format_version, pipelines, environments, or common");
// }
// return partialConfig;
// }
// }
//
// Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String DEFAULT_FILE_PATTERN = "**/*.gocd.yaml,**/*.gocd.yml";
//
// Path: src/main/java/cd/go/plugin/config/yaml/PluginSettings.java
// static final String PLUGIN_SETTINGS_FILE_PATTERN = "file_pattern";
// Path: src/main/java/cd/go/plugin/config/yaml/YamlConfigPlugin.java
import cd.go.plugin.config.yaml.transforms.RootTransform;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.thoughtworks.go.plugin.api.GoApplicationAccessor;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.api.annotation.Extension;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.logging.Logger;
import com.thoughtworks.go.plugin.api.request.GoApiRequest;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.GoApiResponse;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import static cd.go.plugin.config.yaml.PluginSettings.DEFAULT_FILE_PATTERN;
import static cd.go.plugin.config.yaml.PluginSettings.PLUGIN_SETTINGS_FILE_PATTERN;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.*;
import static java.lang.String.format;
return handlePipelineExportRequest(request);
case REQ_GET_CAPABILITIES:
return success(gson.toJson(new Capabilities()));
case REQ_PLUGIN_SETTINGS_CHANGED:
configurePlugin(PluginSettings.fromJson(request.requestBody()));
return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, "");
case REQ_GET_ICON:
return handleGetIconRequest();
default:
throw new UnhandledRequestTypeException(requestName);
}
}
private GoPluginApiResponse handleGetIconRequest() {
try {
JsonObject jsonObject = new JsonObject();
byte[] contents = IOUtils.toByteArray(getClass().getResourceAsStream("/yaml.svg"));
jsonObject.addProperty("content_type", "image/svg+xml");
jsonObject.addProperty("data", Base64.getEncoder().encodeToString(contents));
return success(gson.toJson(jsonObject));
} catch (IOException e) {
return error(e.getMessage());
}
}
String getFilePattern() {
if (null != settings && !isBlank(settings.getFilePattern())) {
return settings.getFilePattern();
} | return DEFAULT_FILE_PATTERN; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.