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
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolverTest.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static pl.jalokim.utils.reflection.InvokableReflectionUtils.invokeMethod; import java.util.Arrays; import java.util.Optional; import org.junit.Test; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; public class NumberJsonTypeResolverTest { @Test public void test_01_WillNotConvertAsNumber() { // given NumberJsonTypeResolver numberJsonTypeResolver = new NumberJsonTypeResolver(); // when Optional<Number> numberOpt = invokeMethod(numberJsonTypeResolver, "returnConcreteValueWhenCanBeResolved",
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolverTest.java import static org.assertj.core.api.Assertions.assertThat; import static pl.jalokim.utils.reflection.InvokableReflectionUtils.invokeMethod; import java.util.Arrays; import java.util.Optional; import org.junit.Test; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives; public class NumberJsonTypeResolverTest { @Test public void test_01_WillNotConvertAsNumber() { // given NumberJsonTypeResolver numberJsonTypeResolver = new NumberJsonTypeResolver(); // when Optional<Number> numberOpt = invokeMethod(numberJsonTypeResolver, "returnConcreteValueWhenCanBeResolved",
Arrays.asList(PrimitiveJsonTypesResolver.class, String.class, String.class),
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/object/MergableObject.java
// Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java // public class MergeObjectException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { // this(oldJsonElement.toStringJson(), elementToAdd.toStringJson(), currentPathMetadata); // } // // @VisibleForTesting // public MergeObjectException(String oldJsonElementValue, String elementToAddValue, PathMetadata currentPathMetadata) { // super(format("Cannot merge objects with different types:%n Old object: %s%n New object: %s%n problematic key: '%s'%n with value: %s", // oldJsonElementValue, elementToAddValue, currentPathMetadata.getOriginalPropertyKey(), currentPathMetadata.getRawValue())); // } // }
import pl.jalokim.propertiestojson.path.PathMetadata; import pl.jalokim.propertiestojson.util.exception.MergeObjectException;
package pl.jalokim.propertiestojson.object; @SuppressWarnings("unchecked") public interface MergableObject<T extends AbstractJsonType> {
// Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java // public class MergeObjectException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { // this(oldJsonElement.toStringJson(), elementToAdd.toStringJson(), currentPathMetadata); // } // // @VisibleForTesting // public MergeObjectException(String oldJsonElementValue, String elementToAddValue, PathMetadata currentPathMetadata) { // super(format("Cannot merge objects with different types:%n Old object: %s%n New object: %s%n problematic key: '%s'%n with value: %s", // oldJsonElementValue, elementToAddValue, currentPathMetadata.getOriginalPropertyKey(), currentPathMetadata.getRawValue())); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/object/MergableObject.java import pl.jalokim.propertiestojson.path.PathMetadata; import pl.jalokim.propertiestojson.util.exception.MergeObjectException; package pl.jalokim.propertiestojson.object; @SuppressWarnings("unchecked") public interface MergableObject<T extends AbstractJsonType> {
static void mergeObjectIfPossible(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/object/MergableObject.java
// Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java // public class MergeObjectException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { // this(oldJsonElement.toStringJson(), elementToAdd.toStringJson(), currentPathMetadata); // } // // @VisibleForTesting // public MergeObjectException(String oldJsonElementValue, String elementToAddValue, PathMetadata currentPathMetadata) { // super(format("Cannot merge objects with different types:%n Old object: %s%n New object: %s%n problematic key: '%s'%n with value: %s", // oldJsonElementValue, elementToAddValue, currentPathMetadata.getOriginalPropertyKey(), currentPathMetadata.getRawValue())); // } // }
import pl.jalokim.propertiestojson.path.PathMetadata; import pl.jalokim.propertiestojson.util.exception.MergeObjectException;
package pl.jalokim.propertiestojson.object; @SuppressWarnings("unchecked") public interface MergableObject<T extends AbstractJsonType> { static void mergeObjectIfPossible(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { MergableObject oldObject = (MergableObject) oldJsonElement; if (oldObject.getClass().isAssignableFrom(elementToAdd.getClass())) { oldObject.merge(elementToAdd, currentPathMetadata); } else {
// Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java // public class MergeObjectException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { // this(oldJsonElement.toStringJson(), elementToAdd.toStringJson(), currentPathMetadata); // } // // @VisibleForTesting // public MergeObjectException(String oldJsonElementValue, String elementToAddValue, PathMetadata currentPathMetadata) { // super(format("Cannot merge objects with different types:%n Old object: %s%n New object: %s%n problematic key: '%s'%n with value: %s", // oldJsonElementValue, elementToAddValue, currentPathMetadata.getOriginalPropertyKey(), currentPathMetadata.getRawValue())); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/object/MergableObject.java import pl.jalokim.propertiestojson.path.PathMetadata; import pl.jalokim.propertiestojson.util.exception.MergeObjectException; package pl.jalokim.propertiestojson.object; @SuppressWarnings("unchecked") public interface MergableObject<T extends AbstractJsonType> { static void mergeObjectIfPossible(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) { MergableObject oldObject = (MergableObject) oldJsonElement; if (oldObject.getClass().isAssignableFrom(elementToAdd.getClass())) { oldObject.merge(elementToAdd, currentPathMetadata); } else {
throw new MergeObjectException(oldJsonElement, elementToAdd, currentPathMetadata);
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/util/PropertiesToJsonConverterFilterTest.java
// Path: src/test/java/pl/jalokim/propertiestojson/domain/MainObject.java // @Getter // @Setter // public class MainObject { // // private Man man; // private Insurance insurance; // private String field1; // private String field2; // }
import com.google.gson.Gson; import java.io.IOException; import java.io.InputStream; import org.assertj.core.api.Assertions; import org.junit.Test; import pl.jalokim.propertiestojson.domain.MainObject;
package pl.jalokim.propertiestojson.util; public class PropertiesToJsonConverterFilterTest extends AbstractPropertiesToJsonConverterTest { @Test public void parsePropertiesOnlyByIncludedKeys() { //when String json = new PropertiesToJsonConverter().convertToJson(initProperlyPropertiesMap(), "man.groups", "man.hoobies", "insurance.cost"); // then assertJsonIsAsExpected(json); } @Test public void parseInputStreamOnlyByIncludedKeys() throws IOException { // given InputStream inputStream = getPropertiesFromFile(); // when String json = new PropertiesToJsonConverter().convertToJson(inputStream, "man.groups", "man.hoobies", "insurance.cost"); // then assertJsonIsAsExpected(json); } private void assertJsonIsAsExpected(String json) { Gson gson = new Gson();
// Path: src/test/java/pl/jalokim/propertiestojson/domain/MainObject.java // @Getter // @Setter // public class MainObject { // // private Man man; // private Insurance insurance; // private String field1; // private String field2; // } // Path: src/test/java/pl/jalokim/propertiestojson/util/PropertiesToJsonConverterFilterTest.java import com.google.gson.Gson; import java.io.IOException; import java.io.InputStream; import org.assertj.core.api.Assertions; import org.junit.Test; import pl.jalokim.propertiestojson.domain.MainObject; package pl.jalokim.propertiestojson.util; public class PropertiesToJsonConverterFilterTest extends AbstractPropertiesToJsonConverterTest { @Test public void parsePropertiesOnlyByIncludedKeys() { //when String json = new PropertiesToJsonConverter().convertToJson(initProperlyPropertiesMap(), "man.groups", "man.hoobies", "insurance.cost"); // then assertJsonIsAsExpected(json); } @Test public void parseInputStreamOnlyByIncludedKeys() throws IOException { // given InputStream inputStream = getPropertiesFromFile(); // when String json = new PropertiesToJsonConverter().convertToJson(inputStream, "man.groups", "man.hoobies", "insurance.cost"); // then assertJsonIsAsExpected(json); } private void assertJsonIsAsExpected(String json) { Gson gson = new Gson();
MainObject mainObject = gson.fromJson(json, MainObject.class);
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/util/exception/CannotOverrideFieldException.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType;
package pl.jalokim.propertiestojson.util.exception; public class CannotOverrideFieldException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String CANNOT_OVERRIDE_VALUE = "Cannot override value at path: '%s', current value is: '%s', problematic property key: '%s'";
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/CannotOverrideFieldException.java import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType; package pl.jalokim.propertiestojson.util.exception; public class CannotOverrideFieldException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String CANNOT_OVERRIDE_VALUE = "Cannot override value at path: '%s', current value is: '%s', problematic property key: '%s'";
public CannotOverrideFieldException(String currentPath, AbstractJsonType currentValue, String propertyKey) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/hierarchy/HierarchyClassResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // }
import static pl.jalokim.utils.string.StringUtils.concatElementsAsLines; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import lombok.Data; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException;
findDifferenceInSuperClasses(searchContext, resolverClass, instanceClass); findDifferenceForSuperInterfaces(searchContext, resolverClass, getSuperInterfaces(instanceClass)); } } } if (searchContext.getFoundClasses().isEmpty()) { return null; } if (searchContext.getFoundClasses().size() == 1) { return searchContext.getFoundClasses().get(0); } List<Class<?>> foundClasses = searchContext.getFoundClasses(); Optional<Class<?>> onlyObjectTypeOpt = foundClasses.stream() .filter(type -> !type.isInterface() && !type.isEnum()) .findAny(); if (onlyObjectTypeOpt.isPresent()) { if (onlyObjectTypeOpt.get() != Object.class) { return onlyObjectTypeOpt.get(); } List<Class<?>> foundInterfaces = new ArrayList<>(foundClasses); foundInterfaces.remove(onlyObjectTypeOpt.get()); if (foundInterfaces.size() == 1) { return foundInterfaces.get(0); } foundClasses = foundInterfaces; }
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/hierarchy/HierarchyClassResolver.java import static pl.jalokim.utils.string.StringUtils.concatElementsAsLines; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import lombok.Data; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException; findDifferenceInSuperClasses(searchContext, resolverClass, instanceClass); findDifferenceForSuperInterfaces(searchContext, resolverClass, getSuperInterfaces(instanceClass)); } } } if (searchContext.getFoundClasses().isEmpty()) { return null; } if (searchContext.getFoundClasses().size() == 1) { return searchContext.getFoundClasses().get(0); } List<Class<?>> foundClasses = searchContext.getFoundClasses(); Optional<Class<?>> onlyObjectTypeOpt = foundClasses.stream() .filter(type -> !type.isInterface() && !type.isEnum()) .findAny(); if (onlyObjectTypeOpt.isPresent()) { if (onlyObjectTypeOpt.get() != Object.class) { return onlyObjectTypeOpt.get(); } List<Class<?>> foundInterfaces = new ArrayList<>(foundClasses); foundInterfaces.remove(onlyObjectTypeOpt.get()); if (foundInterfaces.size() == 1) { return foundInterfaces.get(0); } foundClasses = foundInterfaces; }
throw new ParsePropertiesException(String.format(ERROR_MSG,
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/object/StringJsonType.java
// Path: src/main/java/pl/jalokim/propertiestojson/util/StringToJsonStringWrapper.java // public final class StringToJsonStringWrapper { // // private static final String JSON_STRING_SCHEMA = "\"%s\""; // // private StringToJsonStringWrapper() { // } // // public static String wrap(String textToWrap) { // return String.format(JSON_STRING_SCHEMA, textToWrap.replace("\"", "\\\"")); // } // // }
import pl.jalokim.propertiestojson.util.StringToJsonStringWrapper;
package pl.jalokim.propertiestojson.object; public class StringJsonType extends PrimitiveJsonType<String> { public StringJsonType(String value) { super(value); } @Override public String toStringJson() {
// Path: src/main/java/pl/jalokim/propertiestojson/util/StringToJsonStringWrapper.java // public final class StringToJsonStringWrapper { // // private static final String JSON_STRING_SCHEMA = "\"%s\""; // // private StringToJsonStringWrapper() { // } // // public static String wrap(String textToWrap) { // return String.format(JSON_STRING_SCHEMA, textToWrap.replace("\"", "\\\"")); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/object/StringJsonType.java import pl.jalokim.propertiestojson.util.StringToJsonStringWrapper; package pl.jalokim.propertiestojson.object; public class StringJsonType extends PrimitiveJsonType<String> { public StringJsonType(String value) { super(value); } @Override public String toStringJson() {
return StringToJsonStringWrapper.wrap(value);
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java // public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Number convertedValue, // String propertyKey) { // return Optional.of(new NumberJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java // public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { // // public static Number convertToNumber(String propertyValue) { // Number number = convertToNumberFromText(propertyValue); // if (number != null && number.toString().equals(propertyValue)) { // return number; // } // return null; // } // // @SuppressWarnings("PMD.EmptyCatchBlock") // private static Number convertToNumberFromText(String propertyValue) { // // try { // return getIntegerNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // try { // return getDoubleNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // return null; // } // // private static BigInteger getIntegerNumber(String toParse) { // return new BigInteger(toParse); // } // // private static BigDecimal getDoubleNumber(String toParse) { // return new BigDecimal(toParse); // } // // @Override // public Optional<Number> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // return Optional.ofNullable(convertToNumber(propertyValue)); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NumberToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToNumberResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class NumberJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Number> { public NumberJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java // public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Number convertedValue, // String propertyKey) { // return Optional.of(new NumberJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java // public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { // // public static Number convertToNumber(String propertyValue) { // Number number = convertToNumberFromText(propertyValue); // if (number != null && number.toString().equals(propertyValue)) { // return number; // } // return null; // } // // @SuppressWarnings("PMD.EmptyCatchBlock") // private static Number convertToNumberFromText(String propertyValue) { // // try { // return getIntegerNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // try { // return getDoubleNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // return null; // } // // private static BigInteger getIntegerNumber(String toParse) { // return new BigInteger(toParse); // } // // private static BigDecimal getDoubleNumber(String toParse) { // return new BigDecimal(toParse); // } // // @Override // public Optional<Number> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // return Optional.ofNullable(convertToNumber(propertyValue)); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NumberToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToNumberResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class NumberJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Number> { public NumberJsonTypeResolver() {
super(new TextToNumberResolver(), new NumberToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java // public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Number convertedValue, // String propertyKey) { // return Optional.of(new NumberJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java // public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { // // public static Number convertToNumber(String propertyValue) { // Number number = convertToNumberFromText(propertyValue); // if (number != null && number.toString().equals(propertyValue)) { // return number; // } // return null; // } // // @SuppressWarnings("PMD.EmptyCatchBlock") // private static Number convertToNumberFromText(String propertyValue) { // // try { // return getIntegerNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // try { // return getDoubleNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // return null; // } // // private static BigInteger getIntegerNumber(String toParse) { // return new BigInteger(toParse); // } // // private static BigDecimal getDoubleNumber(String toParse) { // return new BigDecimal(toParse); // } // // @Override // public Optional<Number> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // return Optional.ofNullable(convertToNumber(propertyValue)); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NumberToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToNumberResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class NumberJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Number> { public NumberJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java // public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Number convertedValue, // String propertyKey) { // return Optional.of(new NumberJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java // public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { // // public static Number convertToNumber(String propertyValue) { // Number number = convertToNumberFromText(propertyValue); // if (number != null && number.toString().equals(propertyValue)) { // return number; // } // return null; // } // // @SuppressWarnings("PMD.EmptyCatchBlock") // private static Number convertToNumberFromText(String propertyValue) { // // try { // return getIntegerNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // try { // return getDoubleNumber(propertyValue); // } catch (NumberFormatException exc) { // // NOTHING TO DO // } // return null; // } // // private static BigInteger getIntegerNumber(String toParse) { // return new BigInteger(toParse); // } // // private static BigDecimal getDoubleNumber(String toParse) { // return new BigDecimal(toParse); // } // // @Override // public Optional<Number> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // return Optional.ofNullable(convertToNumber(propertyValue)); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/NumberJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NumberToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToNumberResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class NumberJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Number> { public NumberJsonTypeResolver() {
super(new TextToNumberResolver(), new NumberToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType;
package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child;
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType; package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child;
private PropertyArrayHelper propertyArrayHelper;
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType;
package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child; private PropertyArrayHelper propertyArrayHelper; private Object rawValue;
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType; package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child; private PropertyArrayHelper propertyArrayHelper; private Object rawValue;
private AbstractJsonType jsonValue;
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType;
package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child; private PropertyArrayHelper propertyArrayHelper; private Object rawValue; private AbstractJsonType jsonValue; public boolean isLeaf() { return child == null; } public boolean isRoot() { return parent == null; } public String getCurrentFullPath() {
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType; package pl.jalokim.propertiestojson.path; @Data public class PathMetadata { private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; private static final String WORD_PATTERN = "(.)*"; private final String originalPropertyKey; private PathMetadata parent; private String fieldName; private String originalFieldName; private PathMetadata child; private PropertyArrayHelper propertyArrayHelper; private Object rawValue; private AbstractJsonType jsonValue; public boolean isLeaf() { return child == null; } public boolean isRoot() { return parent == null; } public String getCurrentFullPath() {
return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName;
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType;
public boolean isLeaf() { return child == null; } public boolean isRoot() { return parent == null; } public String getCurrentFullPath() { return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; } public PathMetadata getLeaf() { PathMetadata current = this; while (current.getChild() != null) { current = current.getChild(); } return current; } public void setFieldName(String fieldName) { this.fieldName = fieldName; if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { propertyArrayHelper = new PropertyArrayHelper(fieldName); this.fieldName = propertyArrayHelper.getArrayFieldName(); } } public void setRawValue(Object rawValue) { if (!isLeaf()) {
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType; public boolean isLeaf() { return child == null; } public boolean isRoot() { return parent == null; } public String getCurrentFullPath() { return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; } public PathMetadata getLeaf() { PathMetadata current = this; while (current.getChild() != null) { current = current.getChild(); } return current; } public void setFieldName(String fieldName) { this.fieldName = fieldName; if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { propertyArrayHelper = new PropertyArrayHelper(fieldName); this.fieldName = propertyArrayHelper.getArrayFieldName(); } } public void setRawValue(Object rawValue) { if (!isLeaf()) {
throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // }
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType;
} public void setFieldName(String fieldName) { this.fieldName = fieldName; if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { propertyArrayHelper = new PropertyArrayHelper(fieldName); this.fieldName = propertyArrayHelper.getArrayFieldName(); } } public void setRawValue(Object rawValue) { if (!isLeaf()) { throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); } this.rawValue = rawValue; } public String getOriginalPropertyKey() { return originalPropertyKey; } public PathMetadata getRoot() { PathMetadata current = this; while (current.getParent() != null) { current = current.getParent(); } return current; } public String getCurrentFullPathWithoutIndexes() {
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String NORMAL_DOT = "."; // // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java // @Getter // public class PropertyArrayHelper { // // private List<Integer> dimensionalIndexes; // private String arrayFieldName; // // public PropertyArrayHelper(String field) { // arrayFieldName = getNameFromArray(field); // dimensionalIndexes = getIndexesFromArrayField(field); // } // // public static String getNameFromArray(String fieldName) { // return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); // } // // public static List<Integer> getIndexesFromArrayField(String fieldName) { // String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); // String[] indexesAsTextArray = indexesAsText // .replace(ARRAY_START_SIGN, EMPTY_STRING) // .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER) // .replaceAll("\\s", EMPTY_STRING) // .split(SIMPLE_ARRAY_DELIMITER); // List<Integer> indexes = new ArrayList<>(); // for (String indexAsText : indexesAsTextArray) { // indexes.add(Integer.valueOf(indexAsText)); // } // return indexes; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/exception/NotLeafValueException.java // public class NotLeafValueException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public NotLeafValueException(String message) { // super(message); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.NORMAL_DOT; import lombok.Data; import pl.jalokim.propertiestojson.PropertyArrayHelper; import pl.jalokim.propertiestojson.exception.NotLeafValueException; import pl.jalokim.propertiestojson.object.AbstractJsonType; } public void setFieldName(String fieldName) { this.fieldName = fieldName; if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { propertyArrayHelper = new PropertyArrayHelper(fieldName); this.fieldName = propertyArrayHelper.getArrayFieldName(); } } public void setRawValue(Object rawValue) { if (!isLeaf()) { throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); } this.rawValue = rawValue; } public String getOriginalPropertyKey() { return originalPropertyKey; } public PathMetadata getRoot() { PathMetadata current = this; while (current.getParent() != null) { current = current.getParent(); } return current; } public String getCurrentFullPathWithoutIndexes() {
String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT;
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { @Override
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { @Override
public Optional<Character> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/EmptyStringJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToEmptyStringResolver.java // public class TextToEmptyStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToEmptyStringResolver EMPTY_TEXT_RESOLVER = new TextToEmptyStringResolver(); // private static final String EMPTY_VALUE = ""; // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // String text = EMPTY_VALUE.equals(propertyValue) ? EMPTY_VALUE : null; // return Optional.ofNullable(text); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToEmptyStringResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class EmptyStringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public EmptyStringJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToEmptyStringResolver.java // public class TextToEmptyStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToEmptyStringResolver EMPTY_TEXT_RESOLVER = new TextToEmptyStringResolver(); // private static final String EMPTY_VALUE = ""; // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // String text = EMPTY_VALUE.equals(propertyValue) ? EMPTY_VALUE : null; // return Optional.ofNullable(text); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/EmptyStringJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToEmptyStringResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class EmptyStringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public EmptyStringJsonTypeResolver() {
super(new TextToEmptyStringResolver(), new StringToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/EmptyStringJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToEmptyStringResolver.java // public class TextToEmptyStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToEmptyStringResolver EMPTY_TEXT_RESOLVER = new TextToEmptyStringResolver(); // private static final String EMPTY_VALUE = ""; // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // String text = EMPTY_VALUE.equals(propertyValue) ? EMPTY_VALUE : null; // return Optional.ofNullable(text); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToEmptyStringResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class EmptyStringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public EmptyStringJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToEmptyStringResolver.java // public class TextToEmptyStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToEmptyStringResolver EMPTY_TEXT_RESOLVER = new TextToEmptyStringResolver(); // private static final String EMPTY_VALUE = ""; // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // String text = EMPTY_VALUE.equals(propertyValue) ? EMPTY_VALUE : null; // return Optional.ofNullable(text); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/EmptyStringJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToEmptyStringResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class EmptyStringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public EmptyStringJsonTypeResolver() {
super(new TextToEmptyStringResolver(), new StringToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/JsonNullReferenceTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public final class JsonNullReferenceType extends AbstractJsonType { // // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // public static final String NULL_VALUE = "null"; // // @Override // public String toStringJson() { // return NULL_VALUE; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NullToJsonTypeConverter.java // public class NullToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<JsonNullReferenceType> { // // public static final NullToJsonTypeConverter NULL_TO_JSON_RESOLVER = new NullToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // JsonNullReferenceType convertedValue, // String propertyKey) { // return Optional.of(convertedValue); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java // public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { // // public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); // // @Override // public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue == null || propertyValue.equals(NULL_VALUE)) { // return Optional.of(NULL_OBJECT); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.object.JsonNullReferenceType; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NullToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToJsonNullReferenceResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class JsonNullReferenceTypeResolver extends PrimitiveJsonTypeDelegatorResolver<JsonNullReferenceType> { public JsonNullReferenceTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public final class JsonNullReferenceType extends AbstractJsonType { // // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // public static final String NULL_VALUE = "null"; // // @Override // public String toStringJson() { // return NULL_VALUE; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NullToJsonTypeConverter.java // public class NullToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<JsonNullReferenceType> { // // public static final NullToJsonTypeConverter NULL_TO_JSON_RESOLVER = new NullToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // JsonNullReferenceType convertedValue, // String propertyKey) { // return Optional.of(convertedValue); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java // public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { // // public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); // // @Override // public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue == null || propertyValue.equals(NULL_VALUE)) { // return Optional.of(NULL_OBJECT); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/JsonNullReferenceTypeResolver.java import pl.jalokim.propertiestojson.object.JsonNullReferenceType; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NullToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToJsonNullReferenceResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class JsonNullReferenceTypeResolver extends PrimitiveJsonTypeDelegatorResolver<JsonNullReferenceType> { public JsonNullReferenceTypeResolver() {
super(new TextToJsonNullReferenceResolver(), new NullToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/JsonNullReferenceTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public final class JsonNullReferenceType extends AbstractJsonType { // // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // public static final String NULL_VALUE = "null"; // // @Override // public String toStringJson() { // return NULL_VALUE; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NullToJsonTypeConverter.java // public class NullToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<JsonNullReferenceType> { // // public static final NullToJsonTypeConverter NULL_TO_JSON_RESOLVER = new NullToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // JsonNullReferenceType convertedValue, // String propertyKey) { // return Optional.of(convertedValue); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java // public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { // // public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); // // @Override // public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue == null || propertyValue.equals(NULL_VALUE)) { // return Optional.of(NULL_OBJECT); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.object.JsonNullReferenceType; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NullToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToJsonNullReferenceResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class JsonNullReferenceTypeResolver extends PrimitiveJsonTypeDelegatorResolver<JsonNullReferenceType> { public JsonNullReferenceTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public final class JsonNullReferenceType extends AbstractJsonType { // // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // public static final String NULL_VALUE = "null"; // // @Override // public String toStringJson() { // return NULL_VALUE; // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NullToJsonTypeConverter.java // public class NullToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<JsonNullReferenceType> { // // public static final NullToJsonTypeConverter NULL_TO_JSON_RESOLVER = new NullToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // JsonNullReferenceType convertedValue, // String propertyKey) { // return Optional.of(convertedValue); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java // public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { // // public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); // // @Override // public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue == null || propertyValue.equals(NULL_VALUE)) { // return Optional.of(NULL_OBJECT); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/JsonNullReferenceTypeResolver.java import pl.jalokim.propertiestojson.object.JsonNullReferenceType; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.NullToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToJsonNullReferenceResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class JsonNullReferenceTypeResolver extends PrimitiveJsonTypeDelegatorResolver<JsonNullReferenceType> { public JsonNullReferenceTypeResolver() {
super(new TextToJsonNullReferenceResolver(), new NullToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.object; public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { @Override
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.object; public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { @Override
public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver,
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.object; public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { @Override
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/NumberToJsonTypeConverter.java import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.object; public class NumberToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Number> { @Override
public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver,
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/CharacterJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/CharacterToJsonTypeConverter.java // public class CharacterToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Character> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Character convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue.toString())); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java // public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { // // @Override // public Optional<Character> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue.length() == 1) { // return Optional.of(propertyValue.charAt(0)); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.CharacterToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToCharacterResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class CharacterJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Character> { public CharacterJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/CharacterToJsonTypeConverter.java // public class CharacterToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Character> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Character convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue.toString())); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java // public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { // // @Override // public Optional<Character> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue.length() == 1) { // return Optional.of(propertyValue.charAt(0)); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/CharacterJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.CharacterToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToCharacterResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class CharacterJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Character> { public CharacterJsonTypeResolver() {
super(new TextToCharacterResolver(), new CharacterToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/CharacterJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/CharacterToJsonTypeConverter.java // public class CharacterToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Character> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Character convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue.toString())); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java // public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { // // @Override // public Optional<Character> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue.length() == 1) { // return Optional.of(propertyValue.charAt(0)); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.CharacterToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToCharacterResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class CharacterJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Character> { public CharacterJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/CharacterToJsonTypeConverter.java // public class CharacterToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Character> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Character convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue.toString())); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToCharacterResolver.java // public class TextToCharacterResolver implements TextToConcreteObjectResolver<Character> { // // @Override // public Optional<Character> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (propertyValue.length() == 1) { // return Optional.of(propertyValue.charAt(0)); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/CharacterJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.CharacterToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToCharacterResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class CharacterJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Character> { public CharacterJsonTypeResolver() {
super(new TextToCharacterResolver(), new CharacterToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/BooleanJsonType.java // public class BooleanJsonType extends PrimitiveJsonType<Boolean> { // // public BooleanJsonType(Boolean value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.BooleanJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.object; public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { @Override
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/BooleanJsonType.java // public class BooleanJsonType extends PrimitiveJsonType<Boolean> { // // public BooleanJsonType(Boolean value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.BooleanJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.object; public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { @Override
public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver,
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/BooleanJsonType.java // public class BooleanJsonType extends PrimitiveJsonType<Boolean> { // // public BooleanJsonType(Boolean value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.BooleanJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.object; public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { @Override
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/BooleanJsonType.java // public class BooleanJsonType extends PrimitiveJsonType<Boolean> { // // public BooleanJsonType(Boolean value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java import java.util.Optional; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.BooleanJsonType; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.object; public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { @Override
public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver,
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/HasGenericType.java
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // }
import java.lang.reflect.ParameterizedType; import pl.jalokim.propertiestojson.resolvers.primitives.adapter.InvokedFromAdapter; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.InvokedFromDelegator; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException;
package pl.jalokim.propertiestojson.resolvers.primitives.object; public interface HasGenericType<T> { @SuppressWarnings("unchecked") @InvokedFromAdapter @InvokedFromDelegator default Class<?> resolveTypeOfResolver() { Class<?> currentClass = getClass(); while (currentClass != null) { try { return (Class<T>) ((ParameterizedType) currentClass .getGenericSuperclass()).getActualTypeArguments()[0]; } catch (Exception ccx) { currentClass = currentClass.getSuperclass(); } }
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/HasGenericType.java import java.lang.reflect.ParameterizedType; import pl.jalokim.propertiestojson.resolvers.primitives.adapter.InvokedFromAdapter; import pl.jalokim.propertiestojson.resolvers.primitives.delegator.InvokedFromDelegator; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException; package pl.jalokim.propertiestojson.resolvers.primitives.object; public interface HasGenericType<T> { @SuppressWarnings("unchecked") @InvokedFromAdapter @InvokedFromDelegator default Class<?> resolveTypeOfResolver() { Class<?> currentClass = getClass(); while (currentClass != null) { try { return (Class<T>) ((ParameterizedType) currentClass .getGenericSuperclass()).getActualTypeArguments()[0]; } catch (Exception ccx) { currentClass = currentClass.getSuperclass(); } }
throw new ParsePropertiesException("Cannot find generic type for resolver: " + getClass()
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { public static Number convertToNumber(String propertyValue) { Number number = convertToNumberFromText(propertyValue); if (number != null && number.toString().equals(propertyValue)) { return number; } return null; } @SuppressWarnings("PMD.EmptyCatchBlock") private static Number convertToNumberFromText(String propertyValue) { try { return getIntegerNumber(propertyValue); } catch (NumberFormatException exc) { // NOTHING TO DO } try { return getDoubleNumber(propertyValue); } catch (NumberFormatException exc) { // NOTHING TO DO } return null; } private static BigInteger getIntegerNumber(String toParse) { return new BigInteger(toParse); } private static BigDecimal getDoubleNumber(String toParse) { return new BigDecimal(toParse); } @Override
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToNumberResolver.java import java.math.BigDecimal; import java.math.BigInteger; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToNumberResolver implements TextToConcreteObjectResolver<Number> { public static Number convertToNumber(String propertyValue) { Number number = convertToNumberFromText(propertyValue); if (number != null && number.toString().equals(propertyValue)) { return number; } return null; } @SuppressWarnings("PMD.EmptyCatchBlock") private static Number convertToNumberFromText(String propertyValue) { try { return getIntegerNumber(propertyValue); } catch (NumberFormatException exc) { // NOTHING TO DO } try { return getDoubleNumber(propertyValue); } catch (NumberFormatException exc) { // NOTHING TO DO } return null; } private static BigInteger getIntegerNumber(String toParse) { return new BigInteger(toParse); } private static BigDecimal getDoubleNumber(String toParse) { return new BigDecimal(toParse); } @Override
public Optional<Number> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java // @Deprecated // public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { // // public StringJsonTypeResolver() { // super(new TextToStringResolver(), new StringToJsonTypeConverter()); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.StringJsonTypeResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter;
package pl.jalokim.propertiestojson.util.exception; public class ParsePropertiesException extends RuntimeException { private static final long serialVersionUID = 1L;
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java // @Deprecated // public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { // // public StringJsonTypeResolver() { // super(new TextToStringResolver(), new StringToJsonTypeConverter()); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java import pl.jalokim.propertiestojson.resolvers.primitives.StringJsonTypeResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; package pl.jalokim.propertiestojson.util.exception; public class ParsePropertiesException extends RuntimeException { private static final long serialVersionUID = 1L;
public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName()
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java // @Deprecated // public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { // // public StringJsonTypeResolver() { // super(new TextToStringResolver(), new StringToJsonTypeConverter()); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.StringJsonTypeResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter;
package pl.jalokim.propertiestojson.util.exception; public class ParsePropertiesException extends RuntimeException { private static final long serialVersionUID = 1L; public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() + ". This type resolver always should be last when is in configuration of resolvers";
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java // @Deprecated // public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { // // public StringJsonTypeResolver() { // super(new TextToStringResolver(), new StringToJsonTypeConverter()); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java import pl.jalokim.propertiestojson.resolvers.primitives.StringJsonTypeResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; package pl.jalokim.propertiestojson.util.exception; public class ParsePropertiesException extends RuntimeException { private static final long serialVersionUID = 1L; public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() + ". This type resolver always should be last when is in configuration of resolvers";
public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName()
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+";
import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter;
package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) {
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter; package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) {
return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING);
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+";
import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter;
package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) {
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter; package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) {
return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING);
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+";
import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter;
package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter; package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText
.replace(ARRAY_START_SIGN, EMPTY_STRING)
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+";
import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter;
package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText .replace(ARRAY_START_SIGN, EMPTY_STRING)
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter; package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText .replace(ARRAY_START_SIGN, EMPTY_STRING)
.replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER)
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+";
import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter;
package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText .replace(ARRAY_START_SIGN, EMPTY_STRING)
// Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_END_SIGN = "]"; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String ARRAY_START_SIGN = "["; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String EMPTY_STRING = ""; // // Path: src/main/java/pl/jalokim/propertiestojson/Constants.java // public static final String SIMPLE_ARRAY_DELIMITER = ","; // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // Path: src/main/java/pl/jalokim/propertiestojson/PropertyArrayHelper.java import static pl.jalokim.propertiestojson.Constants.ARRAY_END_SIGN; import static pl.jalokim.propertiestojson.Constants.ARRAY_START_SIGN; import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING; import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER; import static pl.jalokim.propertiestojson.path.PathMetadata.INDEXES_PATTERN; import java.util.ArrayList; import java.util.List; import lombok.Getter; package pl.jalokim.propertiestojson; @Getter public class PropertyArrayHelper { private List<Integer> dimensionalIndexes; private String arrayFieldName; public PropertyArrayHelper(String field) { arrayFieldName = getNameFromArray(field); dimensionalIndexes = getIndexesFromArrayField(field); } public static String getNameFromArray(String fieldName) { return fieldName.replaceFirst(INDEXES_PATTERN + "$", EMPTY_STRING); } public static List<Integer> getIndexesFromArrayField(String fieldName) { String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING); String[] indexesAsTextArray = indexesAsText .replace(ARRAY_START_SIGN, EMPTY_STRING)
.replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER)
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override
public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
if (propertyValue == null || propertyValue.equals(NULL_VALUE)) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { if (propertyValue == null || propertyValue.equals(NULL_VALUE)) {
// Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final JsonNullReferenceType NULL_OBJECT = new JsonNullReferenceType(); // // Path: src/main/java/pl/jalokim/propertiestojson/object/JsonNullReferenceType.java // public static final String NULL_VALUE = "null"; // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToJsonNullReferenceResolver.java import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_OBJECT; import static pl.jalokim.propertiestojson.object.JsonNullReferenceType.NULL_VALUE; import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToJsonNullReferenceResolver implements TextToConcreteObjectResolver<Object> { public static final TextToJsonNullReferenceResolver TEXT_TO_NULL_JSON_RESOLVER = new TextToJsonNullReferenceResolver(); @Override public Optional<Object> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { if (propertyValue == null || propertyValue.equals(NULL_VALUE)) {
return Optional.of(NULL_OBJECT);
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/BooleanJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java // public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Boolean convertedValue, // String propertyKey) { // return Optional.of(new BooleanJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToBooleanResolver.java // public class TextToBooleanResolver implements TextToConcreteObjectResolver<Boolean> { // // private static final String TRUE = "true"; // private static final String FALSE = "false"; // // private static Boolean getBoolean(String value) { // return Boolean.valueOf(value); // } // // @Override // public Optional<Boolean> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (TRUE.equalsIgnoreCase(propertyValue) || FALSE.equalsIgnoreCase(propertyValue)) { // return Optional.of(getBoolean(propertyValue)); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.BooleanToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToBooleanResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class BooleanJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Boolean> { public BooleanJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java // public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Boolean convertedValue, // String propertyKey) { // return Optional.of(new BooleanJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToBooleanResolver.java // public class TextToBooleanResolver implements TextToConcreteObjectResolver<Boolean> { // // private static final String TRUE = "true"; // private static final String FALSE = "false"; // // private static Boolean getBoolean(String value) { // return Boolean.valueOf(value); // } // // @Override // public Optional<Boolean> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (TRUE.equalsIgnoreCase(propertyValue) || FALSE.equalsIgnoreCase(propertyValue)) { // return Optional.of(getBoolean(propertyValue)); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/BooleanJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.BooleanToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToBooleanResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class BooleanJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Boolean> { public BooleanJsonTypeResolver() {
super(new TextToBooleanResolver(), new BooleanToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/BooleanJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java // public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Boolean convertedValue, // String propertyKey) { // return Optional.of(new BooleanJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToBooleanResolver.java // public class TextToBooleanResolver implements TextToConcreteObjectResolver<Boolean> { // // private static final String TRUE = "true"; // private static final String FALSE = "false"; // // private static Boolean getBoolean(String value) { // return Boolean.valueOf(value); // } // // @Override // public Optional<Boolean> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (TRUE.equalsIgnoreCase(propertyValue) || FALSE.equalsIgnoreCase(propertyValue)) { // return Optional.of(getBoolean(propertyValue)); // } // return Optional.empty(); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.BooleanToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToBooleanResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class BooleanJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Boolean> { public BooleanJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/BooleanToJsonTypeConverter.java // public class BooleanToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<Boolean> { // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // Boolean convertedValue, // String propertyKey) { // return Optional.of(new BooleanJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToBooleanResolver.java // public class TextToBooleanResolver implements TextToConcreteObjectResolver<Boolean> { // // private static final String TRUE = "true"; // private static final String FALSE = "false"; // // private static Boolean getBoolean(String value) { // return Boolean.valueOf(value); // } // // @Override // public Optional<Boolean> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) { // if (TRUE.equalsIgnoreCase(propertyValue) || FALSE.equalsIgnoreCase(propertyValue)) { // return Optional.of(getBoolean(propertyValue)); // } // return Optional.empty(); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/BooleanJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.BooleanToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToBooleanResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class BooleanJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<Boolean> { public BooleanJsonTypeResolver() {
super(new TextToBooleanResolver(), new BooleanToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // }
import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver;
package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToStringResolver implements TextToConcreteObjectResolver<String> { public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); @Override
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/PrimitiveJsonTypesResolver.java // public class PrimitiveJsonTypesResolver extends JsonTypeResolver { // // private final List<TextToConcreteObjectResolver<?>> toObjectsResolvers; // private final JsonTypeResolversHierarchyResolver resolversHierarchyResolver; // private final Boolean skipNulls; // private final NullToJsonTypeConverter nullToJsonTypeConverter; // // public PrimitiveJsonTypesResolver(List<TextToConcreteObjectResolver<?>> toObjectsResolvers, // List<ObjectToJsonTypeConverter<?>> toJsonResolvers, // Boolean skipNulls, // NullToJsonTypeConverter nullToJsonTypeConverter) { // this.toObjectsResolvers = ImmutableList.copyOf(toObjectsResolvers); // this.resolversHierarchyResolver = new JsonTypeResolversHierarchyResolver(toJsonResolvers); // this.skipNulls = skipNulls; // this.nullToJsonTypeConverter = nullToJsonTypeConverter; // } // // @Override // public ObjectJsonType traverse(PathMetadata currentPathMetaData) { // addPrimitiveFieldWhenIsValid(currentPathMetaData); // return null; // } // // private void addPrimitiveFieldWhenIsValid(PathMetadata currentPathMetaData) { // JsonObjectFieldsValidator.checkThatFieldCanBeSet(currentObjectJsonType, currentPathMetaData, propertyKey); // addPrimitiveFieldToCurrentJsonObject(currentPathMetaData); // } // // private void addPrimitiveFieldToCurrentJsonObject(PathMetadata currentPathMetaData) { // String field = currentPathMetaData.getFieldName(); // if (currentPathMetaData.isArrayField()) { // addFieldToArray(currentPathMetaData); // } else { // if (currentObjectJsonType.containsField(field) && isArrayJson(currentObjectJsonType.getField(field))) { // AbstractJsonType abstractJsonType = currentPathMetaData.getJsonValue(); // ArrayJsonType currentArrayInObject = currentObjectJsonType.getJsonArray(field); // if (isArrayJson(abstractJsonType)) { // ArrayJsonType newArray = (ArrayJsonType) abstractJsonType; // List<AbstractJsonType> abstractJsonTypes = newArray.convertToListWithoutRealNull(); // for (int i = 0; i < abstractJsonTypes.size(); i++) { // currentArrayInObject.addElement(i, abstractJsonTypes.get(i), currentPathMetaData); // } // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), currentArrayInObject, propertyKey); // } // } else { // currentObjectJsonType.addField(field, currentPathMetaData.getJsonValue(), currentPathMetaData); // } // } // } // // public Object getResolvedObject(String propertyValue, String propertyKey) { // Optional<?> objectOptional = Optional.empty(); // for (TextToConcreteObjectResolver primitiveResolver : toObjectsResolvers) { // if (!objectOptional.isPresent()) { // objectOptional = primitiveResolver.returnConvertedValueForClearedText(this, propertyValue, propertyKey); // } // } // return objectOptional.orElse(null); // } // // public AbstractJsonType resolvePrimitiveTypeAndReturn(Object propertyValue, String propertyKey) { // AbstractJsonType result; // if (propertyValue == null) { // result = nullToJsonTypeConverter.convertToJsonTypeOrEmpty(this, NULL_OBJECT, propertyKey).get(); // } else { // result = resolversHierarchyResolver.returnConcreteJsonTypeObject(this, propertyValue, propertyKey); // } // // if (Boolean.TRUE.equals(skipNulls) && result instanceof JsonNullReferenceType) { // result = SkipJsonField.SKIP_JSON_FIELD; // } // // return result; // } // // protected void addFieldToArray(PathMetadata currentPathMetaData) { // if (arrayWithGivenFieldNameExist(currentPathMetaData.getFieldName())) { // fetchArrayAndAddElement(currentPathMetaData); // } else { // createArrayAndAddElement(currentPathMetaData); // } // } // // private boolean arrayWithGivenFieldNameExist(String field) { // return currentObjectJsonType.containsField(field); // } // // private void createArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonTypeObject = new ArrayJsonType(); // addElementToArray(currentPathMetaData, arrayJsonTypeObject); // currentObjectJsonType.addField(currentPathMetaData.getFieldName(), arrayJsonTypeObject, currentPathMetaData); // } // // private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) { // ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData); // addElementToArray(currentPathMetaData, arrayJsonType); // } // // private void addElementToArray(PathMetadata currentPathMetaData, ArrayJsonType arrayJsonTypeObject) { // arrayJsonTypeObject.addElement(currentPathMetaData.getPropertyArrayHelper(), currentPathMetaData.getJsonValue(), currentPathMetaData); // } // // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java import java.util.Optional; import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; package pl.jalokim.propertiestojson.resolvers.primitives.string; public class TextToStringResolver implements TextToConcreteObjectResolver<String> { public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); @Override
public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver,
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/util/JsonCheckerUtil.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/utils/JsonObjectHelper.java // public final class JsonObjectHelper { // // private static final PrimitiveJsonTypesResolver PRIMITIVE_JSON_TYPES_RESOLVER; // private static final JsonParser JSON_PARSER = new JsonParser(); // private static final Gson GSON = new Gson(); // // static { // List<ObjectToJsonTypeConverter<?>> toJsonResolvers = new ArrayList<>(); // toJsonResolvers.add(new NumberToJsonTypeConverter()); // toJsonResolvers.add(new BooleanToJsonTypeConverter()); // toJsonResolvers.add(STRING_TO_JSON_RESOLVER); // // List<TextToConcreteObjectResolver<?>> toObjectsResolvers = new ArrayList<>(); // toObjectsResolvers.add(new TextToNumberResolver()); // toObjectsResolvers.add(new TextToBooleanResolver()); // toObjectsResolvers.add(TO_STRING_RESOLVER); // PRIMITIVE_JSON_TYPES_RESOLVER = new PrimitiveJsonTypesResolver(toObjectsResolvers, toJsonResolvers, false, NULL_TO_JSON_RESOLVER); // } // // private JsonObjectHelper() { // } // // public static String toJson(Object object) { // return GSON.toJson(object); // } // // public static JsonElement toJsonElement(String json) { // return JSON_PARSER.parse(json); // } // // public static ObjectJsonType createObjectJsonType(JsonElement parsedJson, String propertyKey) { // ObjectJsonType objectJsonType = new ObjectJsonType(); // JsonObject asJsonObject = parsedJson.getAsJsonObject(); // for (Map.Entry<String, JsonElement> entry : asJsonObject.entrySet()) { // JsonElement someField = entry.getValue(); // AbstractJsonType valueOfNextField = convertToAbstractJsonType(someField, propertyKey); // objectJsonType.addField(entry.getKey(), valueOfNextField, null); // } // return objectJsonType; // } // // public static AbstractJsonType convertToAbstractJsonType(JsonElement someField, String propertyKey) { // AbstractJsonType valueOfNextField = null; // if (someField.isJsonNull()) { // valueOfNextField = NULL_OBJECT; // } // if (someField.isJsonObject()) { // valueOfNextField = createObjectJsonType(someField, propertyKey); // } // if (someField.isJsonArray()) { // valueOfNextField = createArrayJsonType(someField, propertyKey); // } // if (someField.isJsonPrimitive()) { // JsonPrimitive jsonPrimitive = someField.getAsJsonPrimitive(); // if (jsonPrimitive.isString()) { // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(jsonPrimitive.getAsString(), propertyKey); // } else if (jsonPrimitive.isNumber()) { // String numberAsText = jsonPrimitive.getAsNumber().toString(); // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(convertToNumber(numberAsText), propertyKey); // } else if (jsonPrimitive.isBoolean()) { // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(jsonPrimitive.getAsBoolean(), propertyKey); // } // } // return valueOfNextField; // } // // public static ArrayJsonType createArrayJsonType(JsonElement parsedJson, String propertyKey) { // ArrayJsonType arrayJsonType = new ArrayJsonType(); // JsonArray asJsonArray = parsedJson.getAsJsonArray(); // int index = 0; // for (JsonElement element : asJsonArray) { // arrayJsonType.addElement(index, convertToAbstractJsonType(element, propertyKey), null); // index++; // } // return arrayJsonType; // } // // public static boolean isValidJsonObjectOrArray(String propertyValue) { // if (hasJsonObjectSignature(propertyValue) || hasJsonArraySignature(propertyValue)) { // JsonParser jp = new JsonParser(); // try { // jp.parse(propertyValue); // return true; // } catch (Exception ex) { // return false; // } // } // return false; // } // // public static boolean hasJsonArraySignature(String propertyValue) { // return hasJsonSignature(propertyValue.trim(), ARRAY_START_SIGN, ARRAY_END_SIGN); // } // // public static boolean hasJsonObjectSignature(String propertyValue) { // return hasJsonSignature(propertyValue.trim(), JSON_OBJECT_START, JSON_OBJECT_END); // } // // private static boolean hasJsonSignature(String propertyValue, String startSign, String endSign) { // return firsLetter(propertyValue).contains(startSign) && lastLetter(propertyValue).contains(endSign); // } // // private static String firsLetter(String text) { // return text.substring(0, 1); // } // // private static String lastLetter(String text) { // return text.substring(text.length() - 1); // } // }
import com.google.gson.JsonObject; import pl.jalokim.propertiestojson.resolvers.primitives.utils.JsonObjectHelper;
package pl.jalokim.propertiestojson.util; public class JsonCheckerUtil { public static boolean leafOfPathIsNotPresent(String jsonPath, String jsonAsText) {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/utils/JsonObjectHelper.java // public final class JsonObjectHelper { // // private static final PrimitiveJsonTypesResolver PRIMITIVE_JSON_TYPES_RESOLVER; // private static final JsonParser JSON_PARSER = new JsonParser(); // private static final Gson GSON = new Gson(); // // static { // List<ObjectToJsonTypeConverter<?>> toJsonResolvers = new ArrayList<>(); // toJsonResolvers.add(new NumberToJsonTypeConverter()); // toJsonResolvers.add(new BooleanToJsonTypeConverter()); // toJsonResolvers.add(STRING_TO_JSON_RESOLVER); // // List<TextToConcreteObjectResolver<?>> toObjectsResolvers = new ArrayList<>(); // toObjectsResolvers.add(new TextToNumberResolver()); // toObjectsResolvers.add(new TextToBooleanResolver()); // toObjectsResolvers.add(TO_STRING_RESOLVER); // PRIMITIVE_JSON_TYPES_RESOLVER = new PrimitiveJsonTypesResolver(toObjectsResolvers, toJsonResolvers, false, NULL_TO_JSON_RESOLVER); // } // // private JsonObjectHelper() { // } // // public static String toJson(Object object) { // return GSON.toJson(object); // } // // public static JsonElement toJsonElement(String json) { // return JSON_PARSER.parse(json); // } // // public static ObjectJsonType createObjectJsonType(JsonElement parsedJson, String propertyKey) { // ObjectJsonType objectJsonType = new ObjectJsonType(); // JsonObject asJsonObject = parsedJson.getAsJsonObject(); // for (Map.Entry<String, JsonElement> entry : asJsonObject.entrySet()) { // JsonElement someField = entry.getValue(); // AbstractJsonType valueOfNextField = convertToAbstractJsonType(someField, propertyKey); // objectJsonType.addField(entry.getKey(), valueOfNextField, null); // } // return objectJsonType; // } // // public static AbstractJsonType convertToAbstractJsonType(JsonElement someField, String propertyKey) { // AbstractJsonType valueOfNextField = null; // if (someField.isJsonNull()) { // valueOfNextField = NULL_OBJECT; // } // if (someField.isJsonObject()) { // valueOfNextField = createObjectJsonType(someField, propertyKey); // } // if (someField.isJsonArray()) { // valueOfNextField = createArrayJsonType(someField, propertyKey); // } // if (someField.isJsonPrimitive()) { // JsonPrimitive jsonPrimitive = someField.getAsJsonPrimitive(); // if (jsonPrimitive.isString()) { // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(jsonPrimitive.getAsString(), propertyKey); // } else if (jsonPrimitive.isNumber()) { // String numberAsText = jsonPrimitive.getAsNumber().toString(); // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(convertToNumber(numberAsText), propertyKey); // } else if (jsonPrimitive.isBoolean()) { // valueOfNextField = PRIMITIVE_JSON_TYPES_RESOLVER.resolvePrimitiveTypeAndReturn(jsonPrimitive.getAsBoolean(), propertyKey); // } // } // return valueOfNextField; // } // // public static ArrayJsonType createArrayJsonType(JsonElement parsedJson, String propertyKey) { // ArrayJsonType arrayJsonType = new ArrayJsonType(); // JsonArray asJsonArray = parsedJson.getAsJsonArray(); // int index = 0; // for (JsonElement element : asJsonArray) { // arrayJsonType.addElement(index, convertToAbstractJsonType(element, propertyKey), null); // index++; // } // return arrayJsonType; // } // // public static boolean isValidJsonObjectOrArray(String propertyValue) { // if (hasJsonObjectSignature(propertyValue) || hasJsonArraySignature(propertyValue)) { // JsonParser jp = new JsonParser(); // try { // jp.parse(propertyValue); // return true; // } catch (Exception ex) { // return false; // } // } // return false; // } // // public static boolean hasJsonArraySignature(String propertyValue) { // return hasJsonSignature(propertyValue.trim(), ARRAY_START_SIGN, ARRAY_END_SIGN); // } // // public static boolean hasJsonObjectSignature(String propertyValue) { // return hasJsonSignature(propertyValue.trim(), JSON_OBJECT_START, JSON_OBJECT_END); // } // // private static boolean hasJsonSignature(String propertyValue, String startSign, String endSign) { // return firsLetter(propertyValue).contains(startSign) && lastLetter(propertyValue).contains(endSign); // } // // private static String firsLetter(String text) { // return text.substring(0, 1); // } // // private static String lastLetter(String text) { // return text.substring(text.length() - 1); // } // } // Path: src/test/java/pl/jalokim/propertiestojson/util/JsonCheckerUtil.java import com.google.gson.JsonObject; import pl.jalokim.propertiestojson.resolvers.primitives.utils.JsonObjectHelper; package pl.jalokim.propertiestojson.util; public class JsonCheckerUtil { public static boolean leafOfPathIsNotPresent(String jsonPath, String jsonAsText) {
JsonObject jsonObject = JsonObjectHelper.toJsonElement(jsonAsText).getAsJsonObject();
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java // public class TextToStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // return Optional.ofNullable(propertyValue); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToStringResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public StringJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java // public class TextToStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // return Optional.ofNullable(propertyValue); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToStringResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public StringJsonTypeResolver() {
super(new TextToStringResolver(), new StringToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java // public class TextToStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // return Optional.ofNullable(propertyValue); // } // }
import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToStringResolver;
package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public StringJsonTypeResolver() {
// Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/delegator/PrimitiveJsonTypeDelegatorResolver.java // @SuppressWarnings("unchecked") // @SuppressFBWarnings("UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR") // public class PrimitiveJsonTypeDelegatorResolver<T> extends PrimitiveJsonTypeResolver<T> { // // private final TextToConcreteObjectResolver toObjectResolver; // private final AbstractObjectToJsonTypeConverter toJsonResolver; // // @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") // public PrimitiveJsonTypeDelegatorResolver(TextToConcreteObjectResolver toObjectResolver, // AbstractObjectToJsonTypeConverter toJsonResolver) { // this.toObjectResolver = toObjectResolver; // this.toJsonResolver = toJsonResolver; // setValueForField(this, "typeWhichCanBeResolved", resolveTypeOfResolver()); // } // // @Override // public Class<?> resolveTypeOfResolver() { // if (toJsonResolver != null) { // return toJsonResolver.resolveTypeOfResolver(); // } // return null; // } // // @Override // public AbstractJsonType returnConcreteJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // T convertedValue, // String propertyKey) { // Optional<AbstractJsonType> optional = toJsonResolver.convertToJsonTypeOrEmpty(primitiveJsonTypesResolver, // convertedValue, // propertyKey); // return optional.get(); // } // // @Override // protected Optional<T> returnConcreteValueWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // Optional<Object> optionalObject = toObjectResolver.returnObjectWhenCanBeResolved(primitiveJsonTypesResolver, // propertyValue, propertyKey); // return optionalObject.map(o -> (T) o); // } // // @Override // public List<Class<?>> getClassesWhichCanResolve() { // return toJsonResolver.getClassesWhichCanResolve(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/object/StringToJsonTypeConverter.java // public class StringToJsonTypeConverter extends AbstractObjectToJsonTypeConverter<String> { // // public static final StringToJsonTypeConverter STRING_TO_JSON_RESOLVER = new StringToJsonTypeConverter(); // // @Override // public Optional<AbstractJsonType> convertToJsonTypeOrEmpty(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String convertedValue, // String propertyKey) { // return Optional.of(new StringJsonType(convertedValue)); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToStringResolver.java // public class TextToStringResolver implements TextToConcreteObjectResolver<String> { // // public static final TextToStringResolver TO_STRING_RESOLVER = new TextToStringResolver(); // // @Override // public Optional<String> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, // String propertyValue, // String propertyKey) { // return Optional.ofNullable(propertyValue); // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/StringJsonTypeResolver.java import pl.jalokim.propertiestojson.resolvers.primitives.delegator.PrimitiveJsonTypeDelegatorResolver; import pl.jalokim.propertiestojson.resolvers.primitives.object.StringToJsonTypeConverter; import pl.jalokim.propertiestojson.resolvers.primitives.string.TextToStringResolver; package pl.jalokim.propertiestojson.resolvers.primitives; @Deprecated public class StringJsonTypeResolver extends PrimitiveJsonTypeDelegatorResolver<String> { public StringJsonTypeResolver() {
super(new TextToStringResolver(), new StringToJsonTypeConverter());
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType;
package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // Path: src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType; package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when
AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get();
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType;
package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull();
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // Path: src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType; package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull();
NumberJsonType numberJsonType = (NumberJsonType) jsonObject;
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType;
package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull(); NumberJsonType numberJsonType = (NumberJsonType) jsonObject; assertThat(numberJsonType.toString()).isEqualTo("1564876800"); } @Test public void convertLocalDateToJsonObject() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(false); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull();
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/NumberJsonType.java // public class NumberJsonType extends PrimitiveJsonType<Number> { // // public NumberJsonType(Number value) { // super(value); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // Path: src/test/java/pl/jalokim/propertiestojson/resolvers/primitives/custom/LocalDateToJsonTypeConverterTest.java import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import org.junit.Test; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.object.NumberJsonType; import pl.jalokim.propertiestojson.object.ObjectJsonType; package pl.jalokim.propertiestojson.resolvers.primitives.custom; public class LocalDateToJsonTypeConverterTest { @Test public void convertLocalDateToUtcTimestamp() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(true); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull(); NumberJsonType numberJsonType = (NumberJsonType) jsonObject; assertThat(numberJsonType.toString()).isEqualTo("1564876800"); } @Test public void convertLocalDateToJsonObject() { // given LocalDate localDate = LocalDate.of(2019, 8, 4); LocalDateToJsonTypeConverter resolver = new LocalDateToJsonTypeConverter(false); // when AbstractJsonType jsonObject = resolver.convertToJsonTypeOrEmpty(null, localDate, "some.field").get(); // then assertThat(jsonObject).isNotNull();
ObjectJsonType numberJsonType = (ObjectJsonType) jsonObject;
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/resolvers/hierarchy/HierarchyClassResolverTest.java
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // }
import static java.util.Arrays.asList; import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; import static pl.jalokim.utils.string.StringUtils.concatElementsAsLines; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException;
package pl.jalokim.propertiestojson.resolvers.hierarchy; public class HierarchyClassResolverTest { public static final String ERR_MSG_FORMAT = "Found %s resolvers for instance type: %s%nfound resolvers:%n%s"; @Test public void willFoundTheSameTypeOfResolver() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver(asList(Object.class, Number.class, Comparable.class, BigDecimal.class)); BigDecimal bigDecimal = BigDecimal.ONE; // when Class<?> aClass = hierarchyClassResolver.searchResolverClass(bigDecimal); // then assertThat(aClass).isEqualTo(BigDecimal.class); } @Test public void foundCollectionInResolverTypeForArrayList() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver(asList(Collection.class, Double.class)); List<String> arrayList = Arrays.asList("test1", "test2"); // when Class<?> aClass = hierarchyClassResolver.searchResolverClass(arrayList); // then assertThat(aClass).isEqualTo(Collection.class); } @Test public void foundToMuchResolversToMuchInterfaces() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver( asList(HasMind.class, HasHair.class, HasLegs.class, Object.class, HasBrain.class, HasAwareness.class)); Human human = new Human(); // when try { hierarchyClassResolver.searchResolverClass(human); fail();
// Path: src/main/java/pl/jalokim/propertiestojson/util/exception/ParsePropertiesException.java // public class ParsePropertiesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final String STRING_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringJsonTypeResolver.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String STRING_TO_JSON_RESOLVER_AS_NOT_LAST = "Added some type resolver after " + StringToJsonTypeConverter.class.getCanonicalName() // + ". This type resolver always should be last when is in configuration of resolvers"; // // public static final String PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE = "Unsupported property key type: %s for key: %s, Property key needs to be a string type"; // public static final String CANNOT_FIND_TYPE_RESOLVER_MSG = "Cannot find valid JSON type resolver for class: '%s'. %n" // + "Please consider add sufficient resolver to your resolvers."; // // public static final String CANNOT_FIND_JSON_TYPE_OBJ = "Cannot find valid JSON type resolver for class: '%s'. %n" // + " for property: %s, and object value: %s %n" // + "Please consider add sufficient resolver to your resolvers."; // // public ParsePropertiesException(String message) { // super(message); // } // } // Path: src/test/java/pl/jalokim/propertiestojson/resolvers/hierarchy/HierarchyClassResolverTest.java import static java.util.Arrays.asList; import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; import static pl.jalokim.utils.string.StringUtils.concatElementsAsLines; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import pl.jalokim.propertiestojson.util.exception.ParsePropertiesException; package pl.jalokim.propertiestojson.resolvers.hierarchy; public class HierarchyClassResolverTest { public static final String ERR_MSG_FORMAT = "Found %s resolvers for instance type: %s%nfound resolvers:%n%s"; @Test public void willFoundTheSameTypeOfResolver() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver(asList(Object.class, Number.class, Comparable.class, BigDecimal.class)); BigDecimal bigDecimal = BigDecimal.ONE; // when Class<?> aClass = hierarchyClassResolver.searchResolverClass(bigDecimal); // then assertThat(aClass).isEqualTo(BigDecimal.class); } @Test public void foundCollectionInResolverTypeForArrayList() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver(asList(Collection.class, Double.class)); List<String> arrayList = Arrays.asList("test1", "test2"); // when Class<?> aClass = hierarchyClassResolver.searchResolverClass(arrayList); // then assertThat(aClass).isEqualTo(Collection.class); } @Test public void foundToMuchResolversToMuchInterfaces() { // given HierarchyClassResolver hierarchyClassResolver = new HierarchyClassResolver( asList(HasMind.class, HasHair.class, HasLegs.class, Object.class, HasBrain.class, HasAwareness.class)); Human human = new Human(); // when try { hierarchyClassResolver.searchResolverClass(human); fail();
} catch (ParsePropertiesException ex) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // }
import static java.lang.String.format; import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.path.PathMetadata;
package pl.jalokim.propertiestojson.util.exception; public class MergeObjectException extends RuntimeException { private static final long serialVersionUID = 1L;
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java import static java.lang.String.format; import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.path.PathMetadata; package pl.jalokim.propertiestojson.util.exception; public class MergeObjectException extends RuntimeException { private static final long serialVersionUID = 1L;
public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // }
import static java.lang.String.format; import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.path.PathMetadata;
package pl.jalokim.propertiestojson.util.exception; public class MergeObjectException extends RuntimeException { private static final long serialVersionUID = 1L;
// Path: src/main/java/pl/jalokim/propertiestojson/object/AbstractJsonType.java // public abstract class AbstractJsonType { // // /** // * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly. // * // * @return string for part of json. // */ // public abstract String toStringJson(); // // @Override // public final String toString() { // return toStringJson(); // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // Path: src/main/java/pl/jalokim/propertiestojson/util/exception/MergeObjectException.java import static java.lang.String.format; import com.google.common.annotations.VisibleForTesting; import pl.jalokim.propertiestojson.object.AbstractJsonType; import pl.jalokim.propertiestojson.path.PathMetadata; package pl.jalokim.propertiestojson.util.exception; public class MergeObjectException extends RuntimeException { private static final long serialVersionUID = 1L;
public MergeObjectException(AbstractJsonType oldJsonElement, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) {
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/transfer/DataForResolve.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // }
import java.util.Map; import pl.jalokim.propertiestojson.object.ObjectJsonType; import pl.jalokim.propertiestojson.path.PathMetadata;
package pl.jalokim.propertiestojson.resolvers.transfer; public class DataForResolve { private final Map<String, Object> properties; private final String propertyKey;
// Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/transfer/DataForResolve.java import java.util.Map; import pl.jalokim.propertiestojson.object.ObjectJsonType; import pl.jalokim.propertiestojson.path.PathMetadata; package pl.jalokim.propertiestojson.resolvers.transfer; public class DataForResolve { private final Map<String, Object> properties; private final String propertyKey;
private final ObjectJsonType currentObjectJsonType;
mikolajmitura/java-properties-to-json
src/main/java/pl/jalokim/propertiestojson/resolvers/transfer/DataForResolve.java
// Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // }
import java.util.Map; import pl.jalokim.propertiestojson.object.ObjectJsonType; import pl.jalokim.propertiestojson.path.PathMetadata;
package pl.jalokim.propertiestojson.resolvers.transfer; public class DataForResolve { private final Map<String, Object> properties; private final String propertyKey; private final ObjectJsonType currentObjectJsonType;
// Path: src/main/java/pl/jalokim/propertiestojson/object/ObjectJsonType.java // public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> { // // @SuppressWarnings("PMD.UseConcurrentHashMap") // private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>(); // // public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) { // if (object instanceof SkipJsonField) { // return; // } // // AbstractJsonType oldFieldValue = fields.get(field); // if (oldFieldValue == null) { // fields.put(field, object); // } else { // if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) { // mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData); // } else { // throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), // oldFieldValue, // currentPathMetaData.getOriginalPropertyKey()); // } // } // } // // public boolean containsField(String field) { // return fields.containsKey(field); // } // // public AbstractJsonType getField(String field) { // return fields.get(field); // } // // public ArrayJsonType getJsonArray(String field) { // return (ArrayJsonType) fields.get(field); // } // // @Override // public String toStringJson() { // StringBuilder result = new StringBuilder().append(JSON_OBJECT_START); // int index = 0; // int lastIndex = getLastIndex(fields.keySet()); // for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) { // AbstractJsonType object = entry.getValue(); // String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN; // result.append(StringToJsonStringWrapper.wrap(entry.getKey())) // .append(':') // .append(object.toStringJson()) // .append(lastSign); // index++; // } // result.append(JSON_OBJECT_END); // return result.toString(); // } // // @Override // public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) { // for (String fieldName : mergeWith.fields.keySet()) { // addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata); // } // } // } // // Path: src/main/java/pl/jalokim/propertiestojson/path/PathMetadata.java // @Data // public class PathMetadata { // // private static final String NUMBER_PATTERN = "([1-9]\\d*)|0"; // public static final String INDEXES_PATTERN = "\\s*(\\[\\s*((" + NUMBER_PATTERN + ")|\\*)\\s*]\\s*)+"; // // private static final String WORD_PATTERN = "(.)*"; // // private final String originalPropertyKey; // private PathMetadata parent; // private String fieldName; // private String originalFieldName; // private PathMetadata child; // private PropertyArrayHelper propertyArrayHelper; // private Object rawValue; // private AbstractJsonType jsonValue; // // public boolean isLeaf() { // return child == null; // } // // public boolean isRoot() { // return parent == null; // } // // public String getCurrentFullPath() { // return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName; // } // // public PathMetadata getLeaf() { // PathMetadata current = this; // while (current.getChild() != null) { // current = current.getChild(); // } // return current; // } // // public void setFieldName(String fieldName) { // this.fieldName = fieldName; // if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) { // propertyArrayHelper = new PropertyArrayHelper(fieldName); // this.fieldName = propertyArrayHelper.getArrayFieldName(); // } // } // // public void setRawValue(Object rawValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.rawValue = rawValue; // } // // public String getOriginalPropertyKey() { // return originalPropertyKey; // } // // public PathMetadata getRoot() { // PathMetadata current = this; // while (current.getParent() != null) { // current = current.getParent(); // } // return current; // } // // public String getCurrentFullPathWithoutIndexes() { // String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT; // return parentFullPath + getFieldName(); // } // // public AbstractJsonType getJsonValue() { // return jsonValue; // } // // public void setJsonValue(AbstractJsonType jsonValue) { // if (!isLeaf()) { // throw new NotLeafValueException("Cannot set value for not leaf: " + getCurrentFullPath()); // } // this.jsonValue = jsonValue; // } // // @Override // public String toString() { // return "field='" + fieldName + '\'' // + ", rawValue=" + rawValue // + ", fullPath='" + getCurrentFullPath() + '}'; // } // // public boolean isArrayField() { // return propertyArrayHelper != null; // } // } // Path: src/main/java/pl/jalokim/propertiestojson/resolvers/transfer/DataForResolve.java import java.util.Map; import pl.jalokim.propertiestojson.object.ObjectJsonType; import pl.jalokim.propertiestojson.path.PathMetadata; package pl.jalokim.propertiestojson.resolvers.transfer; public class DataForResolve { private final Map<String, Object> properties; private final String propertyKey; private final ObjectJsonType currentObjectJsonType;
private final PathMetadata currentPathMetaData;
mikolajmitura/java-properties-to-json
src/test/java/pl/jalokim/propertiestojson/util/AbstractPropertiesToJsonConverterTest.java
// Path: src/test/java/pl/jalokim/propertiestojson/domain/MainObject.java // @Getter // @Setter // public class MainObject { // // private Man man; // private Insurance insurance; // private String field1; // private String field2; // }
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.assertj.core.api.Assertions; import pl.jalokim.propertiestojson.domain.MainObject;
return properties; } protected Properties initProperlyProperties() { Properties properties = new Properties(); properties.put("man.name", NAME); properties.put("man.surname", SURNAME); properties.put("man.address.city", CITY); properties.put("man.address.street", STREET); properties.put("insurance.type", INSRANCE_TYPE); properties.put("insurance.cost", COST_INT_VALUE); properties.put("field1", FIELD1_VALUE); properties.put("field2", FIELD2_VALUE); properties.put("man.emails", Arrays.asList(EMAIL_1, EMAIL_2, EMAIL_3, EMAIL_3)); properties.put("man.groups[0].name", GROUP_1); properties.put("man.groups[0].type", COMMERCIAL); properties.put("man.groups[2].name", GROUP_3); properties.put("man.groups[2].type", COMMERCIAL); properties.put("man.groups[1].name", GROUP_2); properties.put("man.groups[1].type", FREE); properties.put("man.hoobies[0]", CARS); properties.put("man.hoobies[3]", COMPUTERS); properties.put("man.hoobies[2]", WOMEN); properties.put("man.hoobies[1]", SCIENCE); properties.put("man.married", false); properties.put("man.insurance.cost", EXPECTED_MAN_COST); properties.put("man.insurance.valid", true); return properties; }
// Path: src/test/java/pl/jalokim/propertiestojson/domain/MainObject.java // @Getter // @Setter // public class MainObject { // // private Man man; // private Insurance insurance; // private String field1; // private String field2; // } // Path: src/test/java/pl/jalokim/propertiestojson/util/AbstractPropertiesToJsonConverterTest.java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.assertj.core.api.Assertions; import pl.jalokim.propertiestojson.domain.MainObject; return properties; } protected Properties initProperlyProperties() { Properties properties = new Properties(); properties.put("man.name", NAME); properties.put("man.surname", SURNAME); properties.put("man.address.city", CITY); properties.put("man.address.street", STREET); properties.put("insurance.type", INSRANCE_TYPE); properties.put("insurance.cost", COST_INT_VALUE); properties.put("field1", FIELD1_VALUE); properties.put("field2", FIELD2_VALUE); properties.put("man.emails", Arrays.asList(EMAIL_1, EMAIL_2, EMAIL_3, EMAIL_3)); properties.put("man.groups[0].name", GROUP_1); properties.put("man.groups[0].type", COMMERCIAL); properties.put("man.groups[2].name", GROUP_3); properties.put("man.groups[2].type", COMMERCIAL); properties.put("man.groups[1].name", GROUP_2); properties.put("man.groups[1].type", FREE); properties.put("man.hoobies[0]", CARS); properties.put("man.hoobies[3]", COMPUTERS); properties.put("man.hoobies[2]", WOMEN); properties.put("man.hoobies[1]", SCIENCE); properties.put("man.married", false); properties.put("man.insurance.cost", EXPECTED_MAN_COST); properties.put("man.insurance.valid", true); return properties; }
protected void assertGroupByIdAndExpectedValues(MainObject mainObject, int index, String name, String type) {
crawler-commons/http-fetcher
src/main/java/crawlercommons/fetcher/http/UserAgent.java
// Path: src/main/java/crawlercommons/util/HttpFetcherVersion.java // public class HttpFetcherVersion { // // public static String getVersion() { // String path = "/version.prop"; // InputStream stream = HttpFetcherVersion.class.getResourceAsStream(path); // if (stream == null) { // return "Unknown Version"; // } // // Properties props = new Properties(); // try { // props.load(stream); // stream.close(); // return (String) props.get("version"); // } catch (IOException e) { // return "Unknown Version"; // } // } // }
import java.io.Serializable; import java.util.Locale; import crawlercommons.util.HttpFetcherVersion;
/** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher.http; /** * User Agent enables us to describe characteristics of any http-fetcher * agent. There are a number of constructor options to describe the following: * <ol> * <li><tt>_agentName</tt>: Primary agent name.</li> * <li><tt>_emailAddress</tt>: The agent owners email address.</li> * <li><tt>_webAddress</tt>: A web site/address representing the agent owner.</li> * <li><tt>_browserVersion</tt>: Broswer version used for compatibility.</li> * <li><tt>_crawlerVersion</tt>: Version of the user agents personal crawler. If * this is not set, it defaults to the http-fetcher maven artifact version.</li> * </ol> * */ @SuppressWarnings("serial") public class UserAgent implements Serializable { public static final String DEFAULT_BROWSER_VERSION = "Mozilla/5.0";
// Path: src/main/java/crawlercommons/util/HttpFetcherVersion.java // public class HttpFetcherVersion { // // public static String getVersion() { // String path = "/version.prop"; // InputStream stream = HttpFetcherVersion.class.getResourceAsStream(path); // if (stream == null) { // return "Unknown Version"; // } // // Properties props = new Properties(); // try { // props.load(stream); // stream.close(); // return (String) props.get("version"); // } catch (IOException e) { // return "Unknown Version"; // } // } // } // Path: src/main/java/crawlercommons/fetcher/http/UserAgent.java import java.io.Serializable; import java.util.Locale; import crawlercommons.util.HttpFetcherVersion; /** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher.http; /** * User Agent enables us to describe characteristics of any http-fetcher * agent. There are a number of constructor options to describe the following: * <ol> * <li><tt>_agentName</tt>: Primary agent name.</li> * <li><tt>_emailAddress</tt>: The agent owners email address.</li> * <li><tt>_webAddress</tt>: A web site/address representing the agent owner.</li> * <li><tt>_browserVersion</tt>: Broswer version used for compatibility.</li> * <li><tt>_crawlerVersion</tt>: Version of the user agents personal crawler. If * this is not set, it defaults to the http-fetcher maven artifact version.</li> * </ol> * */ @SuppressWarnings("serial") public class UserAgent implements Serializable { public static final String DEFAULT_BROWSER_VERSION = "Mozilla/5.0";
public static final String DEFAULT_CRAWLER_VERSION = HttpFetcherVersion.getVersion();
crawler-commons/http-fetcher
src/main/java/crawlercommons/fetcher/FetchedResult.java
// Path: src/main/java/crawlercommons/util/Headers.java // @SuppressWarnings("serial") // public class Headers implements Serializable { // // public static final String CONTENT_ENCODING = "Content-Encoding"; // public static final String CONTENT_LANGUAGE = "Content-Language"; // public static final String CONTENT_LENGTH = "Content-Length"; // public static final String CONTENT_LOCATION = "Content-Location"; // public static final String CONTENT_DISPOSITION = "Content-Disposition"; // public static final String CONTENT_MD5 = "Content-MD5"; // public static final String CONTENT_TYPE = "Content-Type"; // public static final String LAST_MODIFIED = "Last-Modified"; // public static final String LOCATION = "Location"; // // private final static List<String> EMPTY_VALUES = Collections.unmodifiableList(new ArrayList<String>()); // // /** // * A map of all headers. // */ // private final Map<String, List<String>> headers; // // public Headers() { // this.headers = new HashMap<>(); // } // // public Headers(Map<String, List<String>> headers) { // this.headers = new HashMap<>(); // } // // /** // * Returns true if named value is multivalued. // * // * @param name name of header // * @return true if named value is multivalued, false if single value or null // */ // public boolean isMultiValued(final String name) { // List<String> values = headers.get(name); // return values != null && values.size() > 1; // } // // /** // * Returns an array of header names. // * // * @return header names // */ // public List<String> names() { // return new ArrayList<String>(headers.keySet()); // } // // /** // * Get the value associated to a header name. If many values are associated // * to the specified name, then the first one is returned. // * // * @param name // * of the header. // * @return the value associated to the specified header name. // */ // public String get(final String name) { // List<String> values = headers.get(name); // return values == null ? null : values.get(0); // } // // /** // * Get the values associated to a header name. // * // * @param name // * of the header. // * @return the values associated to a header name. // */ // public List<String> getValues(final String name) { // return _getValues(name); // } // // private List<String> _getValues(final String name) { // List<String> values = headers.get(name); // return values == null ? EMPTY_VALUES : values; // } // // /** // * Add a header name/value mapping. Add the specified value to the list of // * values associated to the specified header name. // * // * @param name // * the header name. // * @param value // * the header value. // */ // public void add(final String name, final String value) { // List<String> values = headers.get(name); // if (values == null) { // set(name, value); // } else { // values.add(value); // } // } // // /** // * Set header name/value. Associate the specified value to the specified // * header name. If some previous values were associated to this name, // * they are removed. If the given value is <code>null</code>, then the // * header entry is removed. // * // * @param name the header name. // * @param value the header value, or <code>null</code> // */ // public void set(String name, String value) { // if (value != null) { // List<String> values = new ArrayList<>(1); // values.add(value); // headers.put(name, values); // } else { // headers.remove(name); // } // } // // /** // * Returns the number of header names in this Header. // * // * @return number of header names // */ // public int size() { // return headers.size(); // } // // /** // * Returns the HTTP headers as a plain Java map object. The map keys are // * the header names and map values are the header content. // * // * @return headers data as plain Java map. // */ // public Map<String, List<String>> getHeaders() { // return headers; // } // // public String toString() { // StringBuilder buf = new StringBuilder(); // List<String> names = names(); // for (int i = 0; i < names.size(); i++) { // List<String> values = _getValues(names.get(i)); // for (int j = 0; j < values.size(); j++) { // buf.append(names.get(i)) // .append("=") // .append(values.get(j)) // .append(" "); // } // } // return buf.toString(); // } // // }
import java.nio.charset.Charset; import java.security.InvalidParameterException; import crawlercommons.util.Headers;
/** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher; /** */ public class FetchedResult { private final String _baseUrl; private final String _fetchedUrl; private final long _fetchTime; private final byte[] _content; private final String _contentType; private final int _responseRate;
// Path: src/main/java/crawlercommons/util/Headers.java // @SuppressWarnings("serial") // public class Headers implements Serializable { // // public static final String CONTENT_ENCODING = "Content-Encoding"; // public static final String CONTENT_LANGUAGE = "Content-Language"; // public static final String CONTENT_LENGTH = "Content-Length"; // public static final String CONTENT_LOCATION = "Content-Location"; // public static final String CONTENT_DISPOSITION = "Content-Disposition"; // public static final String CONTENT_MD5 = "Content-MD5"; // public static final String CONTENT_TYPE = "Content-Type"; // public static final String LAST_MODIFIED = "Last-Modified"; // public static final String LOCATION = "Location"; // // private final static List<String> EMPTY_VALUES = Collections.unmodifiableList(new ArrayList<String>()); // // /** // * A map of all headers. // */ // private final Map<String, List<String>> headers; // // public Headers() { // this.headers = new HashMap<>(); // } // // public Headers(Map<String, List<String>> headers) { // this.headers = new HashMap<>(); // } // // /** // * Returns true if named value is multivalued. // * // * @param name name of header // * @return true if named value is multivalued, false if single value or null // */ // public boolean isMultiValued(final String name) { // List<String> values = headers.get(name); // return values != null && values.size() > 1; // } // // /** // * Returns an array of header names. // * // * @return header names // */ // public List<String> names() { // return new ArrayList<String>(headers.keySet()); // } // // /** // * Get the value associated to a header name. If many values are associated // * to the specified name, then the first one is returned. // * // * @param name // * of the header. // * @return the value associated to the specified header name. // */ // public String get(final String name) { // List<String> values = headers.get(name); // return values == null ? null : values.get(0); // } // // /** // * Get the values associated to a header name. // * // * @param name // * of the header. // * @return the values associated to a header name. // */ // public List<String> getValues(final String name) { // return _getValues(name); // } // // private List<String> _getValues(final String name) { // List<String> values = headers.get(name); // return values == null ? EMPTY_VALUES : values; // } // // /** // * Add a header name/value mapping. Add the specified value to the list of // * values associated to the specified header name. // * // * @param name // * the header name. // * @param value // * the header value. // */ // public void add(final String name, final String value) { // List<String> values = headers.get(name); // if (values == null) { // set(name, value); // } else { // values.add(value); // } // } // // /** // * Set header name/value. Associate the specified value to the specified // * header name. If some previous values were associated to this name, // * they are removed. If the given value is <code>null</code>, then the // * header entry is removed. // * // * @param name the header name. // * @param value the header value, or <code>null</code> // */ // public void set(String name, String value) { // if (value != null) { // List<String> values = new ArrayList<>(1); // values.add(value); // headers.put(name, values); // } else { // headers.remove(name); // } // } // // /** // * Returns the number of header names in this Header. // * // * @return number of header names // */ // public int size() { // return headers.size(); // } // // /** // * Returns the HTTP headers as a plain Java map object. The map keys are // * the header names and map values are the header content. // * // * @return headers data as plain Java map. // */ // public Map<String, List<String>> getHeaders() { // return headers; // } // // public String toString() { // StringBuilder buf = new StringBuilder(); // List<String> names = names(); // for (int i = 0; i < names.size(); i++) { // List<String> values = _getValues(names.get(i)); // for (int j = 0; j < values.size(); j++) { // buf.append(names.get(i)) // .append("=") // .append(values.get(j)) // .append(" "); // } // } // return buf.toString(); // } // // } // Path: src/main/java/crawlercommons/fetcher/FetchedResult.java import java.nio.charset.Charset; import java.security.InvalidParameterException; import crawlercommons.util.Headers; /** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher; /** */ public class FetchedResult { private final String _baseUrl; private final String _fetchedUrl; private final long _fetchTime; private final byte[] _content; private final String _contentType; private final int _responseRate;
private final Headers _headers;
crawler-commons/http-fetcher
src/test/java/crawlercommons/fetcher/FetchedResultTest.java
// Path: src/main/java/crawlercommons/util/Headers.java // @SuppressWarnings("serial") // public class Headers implements Serializable { // // public static final String CONTENT_ENCODING = "Content-Encoding"; // public static final String CONTENT_LANGUAGE = "Content-Language"; // public static final String CONTENT_LENGTH = "Content-Length"; // public static final String CONTENT_LOCATION = "Content-Location"; // public static final String CONTENT_DISPOSITION = "Content-Disposition"; // public static final String CONTENT_MD5 = "Content-MD5"; // public static final String CONTENT_TYPE = "Content-Type"; // public static final String LAST_MODIFIED = "Last-Modified"; // public static final String LOCATION = "Location"; // // private final static List<String> EMPTY_VALUES = Collections.unmodifiableList(new ArrayList<String>()); // // /** // * A map of all headers. // */ // private final Map<String, List<String>> headers; // // public Headers() { // this.headers = new HashMap<>(); // } // // public Headers(Map<String, List<String>> headers) { // this.headers = new HashMap<>(); // } // // /** // * Returns true if named value is multivalued. // * // * @param name name of header // * @return true if named value is multivalued, false if single value or null // */ // public boolean isMultiValued(final String name) { // List<String> values = headers.get(name); // return values != null && values.size() > 1; // } // // /** // * Returns an array of header names. // * // * @return header names // */ // public List<String> names() { // return new ArrayList<String>(headers.keySet()); // } // // /** // * Get the value associated to a header name. If many values are associated // * to the specified name, then the first one is returned. // * // * @param name // * of the header. // * @return the value associated to the specified header name. // */ // public String get(final String name) { // List<String> values = headers.get(name); // return values == null ? null : values.get(0); // } // // /** // * Get the values associated to a header name. // * // * @param name // * of the header. // * @return the values associated to a header name. // */ // public List<String> getValues(final String name) { // return _getValues(name); // } // // private List<String> _getValues(final String name) { // List<String> values = headers.get(name); // return values == null ? EMPTY_VALUES : values; // } // // /** // * Add a header name/value mapping. Add the specified value to the list of // * values associated to the specified header name. // * // * @param name // * the header name. // * @param value // * the header value. // */ // public void add(final String name, final String value) { // List<String> values = headers.get(name); // if (values == null) { // set(name, value); // } else { // values.add(value); // } // } // // /** // * Set header name/value. Associate the specified value to the specified // * header name. If some previous values were associated to this name, // * they are removed. If the given value is <code>null</code>, then the // * header entry is removed. // * // * @param name the header name. // * @param value the header value, or <code>null</code> // */ // public void set(String name, String value) { // if (value != null) { // List<String> values = new ArrayList<>(1); // values.add(value); // headers.put(name, values); // } else { // headers.remove(name); // } // } // // /** // * Returns the number of header names in this Header. // * // * @return number of header names // */ // public int size() { // return headers.size(); // } // // /** // * Returns the HTTP headers as a plain Java map object. The map keys are // * the header names and map values are the header content. // * // * @return headers data as plain Java map. // */ // public Map<String, List<String>> getHeaders() { // return headers; // } // // public String toString() { // StringBuilder buf = new StringBuilder(); // List<String> names = names(); // for (int i = 0; i < names.size(); i++) { // List<String> values = _getValues(names.get(i)); // for (int j = 0; j < values.size(); j++) { // buf.append(names.get(i)) // .append("=") // .append(values.get(j)) // .append(" "); // } // } // return buf.toString(); // } // // }
import java.io.UnsupportedEncodingException; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import crawlercommons.util.Headers;
/** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher; /** * @author lmcgibbn * */ public class FetchedResultTest { private static final Logger LOG = LoggerFactory.getLogger(FetchedResultTest.class); /** * Test method for {@link crawlercommons.fetcher.FetchedResult#report()}. * This does not actually test anything but simply allows us to see what a * generated report would look like. * * @throws UnsupportedEncodingException */ @Test public void testPrintReport() throws UnsupportedEncodingException {
// Path: src/main/java/crawlercommons/util/Headers.java // @SuppressWarnings("serial") // public class Headers implements Serializable { // // public static final String CONTENT_ENCODING = "Content-Encoding"; // public static final String CONTENT_LANGUAGE = "Content-Language"; // public static final String CONTENT_LENGTH = "Content-Length"; // public static final String CONTENT_LOCATION = "Content-Location"; // public static final String CONTENT_DISPOSITION = "Content-Disposition"; // public static final String CONTENT_MD5 = "Content-MD5"; // public static final String CONTENT_TYPE = "Content-Type"; // public static final String LAST_MODIFIED = "Last-Modified"; // public static final String LOCATION = "Location"; // // private final static List<String> EMPTY_VALUES = Collections.unmodifiableList(new ArrayList<String>()); // // /** // * A map of all headers. // */ // private final Map<String, List<String>> headers; // // public Headers() { // this.headers = new HashMap<>(); // } // // public Headers(Map<String, List<String>> headers) { // this.headers = new HashMap<>(); // } // // /** // * Returns true if named value is multivalued. // * // * @param name name of header // * @return true if named value is multivalued, false if single value or null // */ // public boolean isMultiValued(final String name) { // List<String> values = headers.get(name); // return values != null && values.size() > 1; // } // // /** // * Returns an array of header names. // * // * @return header names // */ // public List<String> names() { // return new ArrayList<String>(headers.keySet()); // } // // /** // * Get the value associated to a header name. If many values are associated // * to the specified name, then the first one is returned. // * // * @param name // * of the header. // * @return the value associated to the specified header name. // */ // public String get(final String name) { // List<String> values = headers.get(name); // return values == null ? null : values.get(0); // } // // /** // * Get the values associated to a header name. // * // * @param name // * of the header. // * @return the values associated to a header name. // */ // public List<String> getValues(final String name) { // return _getValues(name); // } // // private List<String> _getValues(final String name) { // List<String> values = headers.get(name); // return values == null ? EMPTY_VALUES : values; // } // // /** // * Add a header name/value mapping. Add the specified value to the list of // * values associated to the specified header name. // * // * @param name // * the header name. // * @param value // * the header value. // */ // public void add(final String name, final String value) { // List<String> values = headers.get(name); // if (values == null) { // set(name, value); // } else { // values.add(value); // } // } // // /** // * Set header name/value. Associate the specified value to the specified // * header name. If some previous values were associated to this name, // * they are removed. If the given value is <code>null</code>, then the // * header entry is removed. // * // * @param name the header name. // * @param value the header value, or <code>null</code> // */ // public void set(String name, String value) { // if (value != null) { // List<String> values = new ArrayList<>(1); // values.add(value); // headers.put(name, values); // } else { // headers.remove(name); // } // } // // /** // * Returns the number of header names in this Header. // * // * @return number of header names // */ // public int size() { // return headers.size(); // } // // /** // * Returns the HTTP headers as a plain Java map object. The map keys are // * the header names and map values are the header content. // * // * @return headers data as plain Java map. // */ // public Map<String, List<String>> getHeaders() { // return headers; // } // // public String toString() { // StringBuilder buf = new StringBuilder(); // List<String> names = names(); // for (int i = 0; i < names.size(); i++) { // List<String> values = _getValues(names.get(i)); // for (int j = 0; j < values.size(); j++) { // buf.append(names.get(i)) // .append("=") // .append(values.get(j)) // .append(" "); // } // } // return buf.toString(); // } // // } // Path: src/test/java/crawlercommons/fetcher/FetchedResultTest.java import java.io.UnsupportedEncodingException; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import crawlercommons.util.Headers; /** * Copyright 2016 Crawler-Commons * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package crawlercommons.fetcher; /** * @author lmcgibbn * */ public class FetchedResultTest { private static final Logger LOG = LoggerFactory.getLogger(FetchedResultTest.class); /** * Test method for {@link crawlercommons.fetcher.FetchedResult#report()}. * This does not actually test anything but simply allows us to see what a * generated report would look like. * * @throws UnsupportedEncodingException */ @Test public void testPrintReport() throws UnsupportedEncodingException {
Headers headerMetadata = new Headers();
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/LunatriusCore.java
// Path: src/main/java/com/github/lunatrius/core/proxy/CommonProxy.java // public abstract class CommonProxy { // public void preInit(final FMLPreInitializationEvent event) { // Reference.logger = event.getModLog(); // // FMLInterModComms.sendMessage(Reference.MODID, "checkUpdate", Reference.FORGE); // } // // public void init(final FMLInitializationEvent event) { // } // // public void postInit(final FMLPostInitializationEvent event) { // if (VersionChecker.isAllowedToCheck("Global") && ConfigurationHandler.VersionCheck.checkForUpdates) { // VersionChecker.startVersionCheck(); // } // } // // public void processIMC(final FMLInterModComms.IMCEvent event) { // for (final FMLInterModComms.IMCMessage message : event.getMessages()) { // if ("checkUpdate".equals(message.key) && message.isStringMessage()) { // processMessage(message.getSender(), message.getStringValue()); // } // } // } // // private void processMessage(final String sender, final String forgeVersion) { // final ModContainer container = Loader.instance().getIndexedModList().get(sender); // if (container != null) { // VersionChecker.registerMod(container, forgeVersion); // } // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.proxy.CommonProxy; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import java.util.Map;
package com.github.lunatrius.core; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class LunatriusCore { @SidedProxy(serverSide = Reference.PROXY_SERVER, clientSide = Reference.PROXY_CLIENT)
// Path: src/main/java/com/github/lunatrius/core/proxy/CommonProxy.java // public abstract class CommonProxy { // public void preInit(final FMLPreInitializationEvent event) { // Reference.logger = event.getModLog(); // // FMLInterModComms.sendMessage(Reference.MODID, "checkUpdate", Reference.FORGE); // } // // public void init(final FMLInitializationEvent event) { // } // // public void postInit(final FMLPostInitializationEvent event) { // if (VersionChecker.isAllowedToCheck("Global") && ConfigurationHandler.VersionCheck.checkForUpdates) { // VersionChecker.startVersionCheck(); // } // } // // public void processIMC(final FMLInterModComms.IMCEvent event) { // for (final FMLInterModComms.IMCMessage message : event.getMessages()) { // if ("checkUpdate".equals(message.key) && message.isStringMessage()) { // processMessage(message.getSender(), message.getStringValue()); // } // } // } // // private void processMessage(final String sender, final String forgeVersion) { // final ModContainer container = Loader.instance().getIndexedModList().get(sender); // if (container != null) { // VersionChecker.registerMod(container, forgeVersion); // } // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/LunatriusCore.java import com.github.lunatrius.core.proxy.CommonProxy; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import java.util.Map; package com.github.lunatrius.core; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class LunatriusCore { @SidedProxy(serverSide = Reference.PROXY_SERVER, clientSide = Reference.PROXY_CLIENT)
public static CommonProxy proxy;
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java
// Path: src/main/java/com/github/lunatrius/core/reference/Names.java // @SuppressWarnings("HardCodedStringLiteral") // public final class Names { // public static final class Config { // public static final class Category { // public static final String VERSION_CHECK = "versioncheck"; // public static final String TWEAKS = "tweaks"; // } // // public static final String CHECK_FOR_UPDATES = "checkForUpdates"; // public static final String CHECK_FOR_UPDATES_DESC = "Should the mod check for updates?"; // // public static final String LANG_PREFIX = Reference.MODID + ".config"; // } // // public static final class ModId { // public static final String DYNIOUS_VERSION_CHECKER = "VersionChecker"; // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.reference.Names; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.RequiresMcRestart; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package com.github.lunatrius.core.handler; public class ConfigurationHandler { public static Configuration configuration;
// Path: src/main/java/com/github/lunatrius/core/reference/Names.java // @SuppressWarnings("HardCodedStringLiteral") // public final class Names { // public static final class Config { // public static final class Category { // public static final String VERSION_CHECK = "versioncheck"; // public static final String TWEAKS = "tweaks"; // } // // public static final String CHECK_FOR_UPDATES = "checkForUpdates"; // public static final String CHECK_FOR_UPDATES_DESC = "Should the mod check for updates?"; // // public static final String LANG_PREFIX = Reference.MODID + ".config"; // } // // public static final class ModId { // public static final String DYNIOUS_VERSION_CHECKER = "VersionChecker"; // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java import com.github.lunatrius.core.reference.Names; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.RequiresMcRestart; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; package com.github.lunatrius.core.handler; public class ConfigurationHandler { public static Configuration configuration;
@Config(modid = Reference.MODID, category = Names.Config.Category.VERSION_CHECK)
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java
// Path: src/main/java/com/github/lunatrius/core/reference/Names.java // @SuppressWarnings("HardCodedStringLiteral") // public final class Names { // public static final class Config { // public static final class Category { // public static final String VERSION_CHECK = "versioncheck"; // public static final String TWEAKS = "tweaks"; // } // // public static final String CHECK_FOR_UPDATES = "checkForUpdates"; // public static final String CHECK_FOR_UPDATES_DESC = "Should the mod check for updates?"; // // public static final String LANG_PREFIX = Reference.MODID + ".config"; // } // // public static final class ModId { // public static final String DYNIOUS_VERSION_CHECKER = "VersionChecker"; // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.reference.Names; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.RequiresMcRestart; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package com.github.lunatrius.core.handler; public class ConfigurationHandler { public static Configuration configuration;
// Path: src/main/java/com/github/lunatrius/core/reference/Names.java // @SuppressWarnings("HardCodedStringLiteral") // public final class Names { // public static final class Config { // public static final class Category { // public static final String VERSION_CHECK = "versioncheck"; // public static final String TWEAKS = "tweaks"; // } // // public static final String CHECK_FOR_UPDATES = "checkForUpdates"; // public static final String CHECK_FOR_UPDATES_DESC = "Should the mod check for updates?"; // // public static final String LANG_PREFIX = Reference.MODID + ".config"; // } // // public static final class ModId { // public static final String DYNIOUS_VERSION_CHECKER = "VersionChecker"; // } // } // // Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java import com.github.lunatrius.core.reference.Names; import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.config.Config; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.RequiresMcRestart; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; package com.github.lunatrius.core.handler; public class ConfigurationHandler { public static Configuration configuration;
@Config(modid = Reference.MODID, category = Names.Config.Category.VERSION_CHECK)
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/util/FileUtils.java
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.reference.Reference; import java.io.File; import java.io.IOException;
package com.github.lunatrius.core.util; public class FileUtils { // http://stackoverflow.com/a/3758880/1166946 public static String humanReadableByteCount(final long bytes) { final int unit = 1024; if (bytes < unit) { return bytes + " B"; } final int exp = (int) (Math.log(bytes) / Math.log(unit)); final String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%3.0f %sB", bytes / Math.pow(unit, exp), pre); } public static boolean contains(final File root, final String filename) { return contains(root, new File(root, filename)); } // http://stackoverflow.com/q/18227634/1166946 public static boolean contains(final File root, final File file) { try { return file.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator); } catch (final IOException e) {
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/util/FileUtils.java import com.github.lunatrius.core.reference.Reference; import java.io.File; import java.io.IOException; package com.github.lunatrius.core.util; public class FileUtils { // http://stackoverflow.com/a/3758880/1166946 public static String humanReadableByteCount(final long bytes) { final int unit = 1024; if (bytes < unit) { return bytes + " B"; } final int exp = (int) (Math.log(bytes) / Math.log(unit)); final String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%3.0f %sB", bytes / Math.pow(unit, exp), pre); } public static boolean contains(final File root, final String filename) { return contains(root, new File(root, filename)); } // http://stackoverflow.com/q/18227634/1166946 public static boolean contains(final File root, final File file) { try { return file.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator); } catch (final IOException e) {
Reference.logger.error("", e);
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/version/VersionChecker.java
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.reference.Reference; import com.google.common.base.Joiner; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.versioning.ComparableVersion; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
package com.github.lunatrius.core.version; public class VersionChecker { public static final String VER_CHECK_API_URL = "http://mc.lunatri.us/json?v=%d&mc=%s&limit=5"; public static final int VER_CHECK_API_VER = 2; public static final String UPDATE_URL = "https://mods.io/mods?author=Lunatrius"; private static final List<ModContainer> REGISTERED_MODS = new ArrayList<ModContainer>(); private static final Joiner NEWLINE_JOINER = Joiner.on('\n'); public static void registerMod(final ModContainer container, final String forgeVersion) { REGISTERED_MODS.add(container); final ModMetadata metadata = container.getMetadata(); if (metadata.description != null) { metadata.description += "\n---\nCompiled against Forge " + forgeVersion; } } public static void startVersionCheck() { new Thread("LunatriusCore Version Check") { @Override public void run() { try {
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/version/VersionChecker.java import com.github.lunatrius.core.reference.Reference; import com.google.common.base.Joiner; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.versioning.ComparableVersion; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; package com.github.lunatrius.core.version; public class VersionChecker { public static final String VER_CHECK_API_URL = "http://mc.lunatri.us/json?v=%d&mc=%s&limit=5"; public static final int VER_CHECK_API_VER = 2; public static final String UPDATE_URL = "https://mods.io/mods?author=Lunatrius"; private static final List<ModContainer> REGISTERED_MODS = new ArrayList<ModContainer>(); private static final Joiner NEWLINE_JOINER = Joiner.on('\n'); public static void registerMod(final ModContainer container, final String forgeVersion) { REGISTERED_MODS.add(container); final ModMetadata metadata = container.getMetadata(); if (metadata.description != null) { metadata.description += "\n---\nCompiled against Forge " + forgeVersion; } } public static void startVersionCheck() { new Thread("LunatriusCore Version Check") { @Override public void run() { try {
if ("null".equals(Reference.MINECRAFT)) {
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/proxy/ClientProxy.java
// Path: src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java // public class ConfigurationHandler { // public static Configuration configuration; // // @Config(modid = Reference.MODID, category = Names.Config.Category.VERSION_CHECK) // public static class VersionCheck { // @RequiresMcRestart // @Comment(Names.Config.CHECK_FOR_UPDATES_DESC) // public static boolean checkForUpdates = true; // } // // @SubscribeEvent // public void onConfigurationChangedEvent(final ConfigChangedEvent.OnConfigChangedEvent event) { // if (event.getModID().equalsIgnoreCase(Reference.MODID)) { // ConfigManager.sync(Reference.MODID, Config.Type.INSTANCE); // } // } // }
import com.github.lunatrius.core.handler.ConfigurationHandler; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLInitializationEvent;
package com.github.lunatrius.core.proxy; public class ClientProxy extends CommonProxy { @Override public void init(final FMLInitializationEvent event) { super.init(event);
// Path: src/main/java/com/github/lunatrius/core/handler/ConfigurationHandler.java // public class ConfigurationHandler { // public static Configuration configuration; // // @Config(modid = Reference.MODID, category = Names.Config.Category.VERSION_CHECK) // public static class VersionCheck { // @RequiresMcRestart // @Comment(Names.Config.CHECK_FOR_UPDATES_DESC) // public static boolean checkForUpdates = true; // } // // @SubscribeEvent // public void onConfigurationChangedEvent(final ConfigChangedEvent.OnConfigChangedEvent event) { // if (event.getModID().equalsIgnoreCase(Reference.MODID)) { // ConfigManager.sync(Reference.MODID, Config.Type.INSTANCE); // } // } // } // Path: src/main/java/com/github/lunatrius/core/proxy/ClientProxy.java import com.github.lunatrius.core.handler.ConfigurationHandler; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.event.FMLInitializationEvent; package com.github.lunatrius.core.proxy; public class ClientProxy extends CommonProxy { @Override public void init(final FMLInitializationEvent event) { super.init(event);
MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
Lunatrius/LunatriusCore
src/main/java/com/github/lunatrius/core/version/ForgeVersionCheck.java
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // }
import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.versioning.ComparableVersion; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Map;
package com.github.lunatrius.core.version; /** * This class/helper is a workaround for Forge's one mod per version file standard. */ public class ForgeVersionCheck { public static ForgeVersion.Status getStatus(final ComparableVersion versionRemote, final ComparableVersion versionLocal) { final int diff = versionRemote.compareTo(versionLocal); if (diff == 0) { return ForgeVersion.Status.UP_TO_DATE; } if (diff > 0) { return ForgeVersion.Status.OUTDATED; } return ForgeVersion.Status.AHEAD; } public static void notify(final ModContainer container, final ForgeVersion.Status status, final ComparableVersion target, final Map<ComparableVersion, String> changes, final String url) { try { final Map<ModContainer, ForgeVersion.CheckResult> versionMap = getVersionMap(); final ForgeVersion.CheckResult checkResult = getCheckResult(status, target, changes, url); if (versionMap != null && checkResult != null) { versionMap.put(container, checkResult); } } catch (final Throwable t) {
// Path: src/main/java/com/github/lunatrius/core/reference/Reference.java // public class Reference { // public static final String MODID = "lunatriuscore"; // public static final String NAME = "LunatriusCore"; // public static final String VERSION = "${version}"; // public static final String FORGE = "${forgeversion}"; // public static final String MINECRAFT = "${mcversion}"; // public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy"; // public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy"; // // public static Logger logger = LogManager.getLogger(Reference.MODID); // } // Path: src/main/java/com/github/lunatrius/core/version/ForgeVersionCheck.java import com.github.lunatrius.core.reference.Reference; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.versioning.ComparableVersion; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Map; package com.github.lunatrius.core.version; /** * This class/helper is a workaround for Forge's one mod per version file standard. */ public class ForgeVersionCheck { public static ForgeVersion.Status getStatus(final ComparableVersion versionRemote, final ComparableVersion versionLocal) { final int diff = versionRemote.compareTo(versionLocal); if (diff == 0) { return ForgeVersion.Status.UP_TO_DATE; } if (diff > 0) { return ForgeVersion.Status.OUTDATED; } return ForgeVersion.Status.AHEAD; } public static void notify(final ModContainer container, final ForgeVersion.Status status, final ComparableVersion target, final Map<ComparableVersion, String> changes, final String url) { try { final Map<ModContainer, ForgeVersion.CheckResult> versionMap = getVersionMap(); final ForgeVersion.CheckResult checkResult = getCheckResult(status, target, changes, url); if (versionMap != null && checkResult != null) { versionMap.put(container, checkResult); } } catch (final Throwable t) {
Reference.logger.error("Failed to notify Forge!", t);
RPTools/dicelib
src/test/java/net/rptools/common/expression/function/RollTest.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import java.math.BigDecimal; import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.Expression; import net.rptools.parser.MapVariableResolver; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.function.EvaluationException; import net.rptools.parser.function.ParameterException;
/* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class RollTest extends TestCase { public void testEvaluateRoll() throws ParserException, EvaluationException, ParameterException { Parser p = new Parser(); p.addFunction(new Roll()); try {
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/test/java/net/rptools/common/expression/function/RollTest.java import java.math.BigDecimal; import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.Expression; import net.rptools.parser.MapVariableResolver; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.function.EvaluationException; import net.rptools.parser.function.ParameterException; /* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class RollTest extends TestCase { public void testEvaluateRoll() throws ParserException, EvaluationException, ParameterException { Parser p = new Parser(); p.addFunction(new Roll()); try {
RunData.setCurrent(new RunData(null));
RPTools/dicelib
src/main/java/net/rptools/common/expression/function/HeroKillingRoll.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import java.math.BigDecimal; import java.util.List; import net.rptools.common.expression.RunData; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.VariableResolver; import net.rptools.parser.function.AbstractNumberFunction;
/* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; /* * Hero System Dice * * Used to get both the stun & body of an attack roll. * */ public class HeroKillingRoll extends AbstractNumberFunction { public HeroKillingRoll() { super(2, 3, false, "herokilling", "herokilling2", "killing", "heromultiplier", "multiplier"); } // Use variable names with illegal character to minimize chances of variable overlap private static String lastKillingBodyVar = "#Hero-LastKillingBodyVar"; @Override public Object childEvaluate( Parser parser, VariableResolver vr, String functionName, List<Object> parameters) throws ParserException { int n = 0; double times = ((BigDecimal) parameters.get(n++)).doubleValue(); int sides = ((BigDecimal) parameters.get(n++)).intValue(); double half = times - Math.floor(times); int extra = 0; if (parameters.size() > 2) extra = ((BigDecimal) parameters.get(n++)).intValue();
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/main/java/net/rptools/common/expression/function/HeroKillingRoll.java import java.math.BigDecimal; import java.util.List; import net.rptools.common.expression.RunData; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.VariableResolver; import net.rptools.parser.function.AbstractNumberFunction; /* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; /* * Hero System Dice * * Used to get both the stun & body of an attack roll. * */ public class HeroKillingRoll extends AbstractNumberFunction { public HeroKillingRoll() { super(2, 3, false, "herokilling", "herokilling2", "killing", "heromultiplier", "multiplier"); } // Use variable names with illegal character to minimize chances of variable overlap private static String lastKillingBodyVar = "#Hero-LastKillingBodyVar"; @Override public Object childEvaluate( Parser parser, VariableResolver vr, String functionName, List<Object> parameters) throws ParserException { int n = 0; double times = ((BigDecimal) parameters.get(n++)).doubleValue(); int sides = ((BigDecimal) parameters.get(n++)).intValue(); double half = times - Math.floor(times); int extra = 0; if (parameters.size() > 2) extra = ((BigDecimal) parameters.get(n++)).intValue();
RunData runData = RunData.getCurrent();
RPTools/dicelib
src/main/java/net/rptools/common/expression/function/DiceHelper.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import java.util.Arrays; import java.util.Comparator; import net.rptools.common.expression.RunData; import net.rptools.parser.function.*;
/* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DiceHelper { public static int rollDice(int times, int sides) { int result = 0;
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/main/java/net/rptools/common/expression/function/DiceHelper.java import java.util.Arrays; import java.util.Comparator; import net.rptools.common.expression.RunData; import net.rptools.parser.function.*; /* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DiceHelper { public static int rollDice(int times, int sides) { int result = 0;
RunData runData = RunData.getCurrent();
RPTools/dicelib
src/test/java/net/rptools/common/expression/function/DropRollTest.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import java.math.BigDecimal; import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.Expression; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.function.EvaluationException; import net.rptools.parser.function.ParameterException;
/* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DropRollTest extends TestCase { public void testEvaluateRoll() throws ParserException, EvaluationException, ParameterException { Parser p = new Parser(); p.addFunction(new DropRoll()); try {
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/test/java/net/rptools/common/expression/function/DropRollTest.java import java.math.BigDecimal; import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.Expression; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.function.EvaluationException; import net.rptools.parser.function.ParameterException; /* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DropRollTest extends TestCase { public void testEvaluateRoll() throws ParserException, EvaluationException, ParameterException { Parser p = new Parser(); p.addFunction(new DropRoll()); try {
RunData.setCurrent(new RunData(null));
RPTools/dicelib
src/main/java/net/rptools/common/expression/function/HeroRoll.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import java.math.BigDecimal; import java.util.List; import net.rptools.common.expression.RunData; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.VariableResolver; import net.rptools.parser.function.AbstractNumberFunction;
Parser parser, VariableResolver vr, String functionName, List<Object> parameters) throws ParserException { int n = 0; double times = ((BigDecimal) parameters.get(n++)).doubleValue(); int sides = ((BigDecimal) parameters.get(n++)).intValue(); if (functionName.equalsIgnoreCase("herobody")) { double lastTimes = 0; if (vr.containsVariable(lastTimesVar)) lastTimes = ((BigDecimal) vr.getVariable(lastTimesVar)).doubleValue(); int lastSides = 0; if (vr.containsVariable(lastSidesVar)) lastSides = ((BigDecimal) vr.getVariable(lastSidesVar)).intValue(); int lastBody = 0; if (vr.containsVariable(lastBodyVar)) lastBody = ((BigDecimal) vr.getVariable(lastBodyVar)).intValue(); if (times == lastTimes && sides == lastSides) return new BigDecimal(lastBody); return new BigDecimal(-1); // Should this be -1? Perhaps it should return null. } else if ("hero".equalsIgnoreCase(functionName) || "herostun".equalsIgnoreCase(functionName)) { // assume stun double lastTimes = times; int lastSides = sides; int lastBody = 0;
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/main/java/net/rptools/common/expression/function/HeroRoll.java import java.math.BigDecimal; import java.util.List; import net.rptools.common.expression.RunData; import net.rptools.parser.Parser; import net.rptools.parser.ParserException; import net.rptools.parser.VariableResolver; import net.rptools.parser.function.AbstractNumberFunction; Parser parser, VariableResolver vr, String functionName, List<Object> parameters) throws ParserException { int n = 0; double times = ((BigDecimal) parameters.get(n++)).doubleValue(); int sides = ((BigDecimal) parameters.get(n++)).intValue(); if (functionName.equalsIgnoreCase("herobody")) { double lastTimes = 0; if (vr.containsVariable(lastTimesVar)) lastTimes = ((BigDecimal) vr.getVariable(lastTimesVar)).doubleValue(); int lastSides = 0; if (vr.containsVariable(lastSidesVar)) lastSides = ((BigDecimal) vr.getVariable(lastSidesVar)).intValue(); int lastBody = 0; if (vr.containsVariable(lastBodyVar)) lastBody = ((BigDecimal) vr.getVariable(lastBodyVar)).intValue(); if (times == lastTimes && sides == lastSides) return new BigDecimal(lastBody); return new BigDecimal(-1); // Should this be -1? Perhaps it should return null. } else if ("hero".equalsIgnoreCase(functionName) || "herostun".equalsIgnoreCase(functionName)) { // assume stun double lastTimes = times; int lastSides = sides; int lastBody = 0;
RunData runData = RunData.getCurrent();
RPTools/dicelib
src/test/java/net/rptools/common/expression/function/DiceHelperTest.java
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // }
import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.function.EvaluationException;
/* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DiceHelperTest extends TestCase { public void testRollDice() throws Exception {
// Path: src/main/java/net/rptools/common/expression/RunData.java // public class RunData { // private static ThreadLocal<RunData> current = new ThreadLocal<RunData>(); // public static Random RANDOM = new SecureRandom(); // // private final Result result; // // private long randomValue; // private long randomMax; // private long randomMin; // // /** Should not be modified directly. Use {@link #recordRolled(Integer)} */ // private final List<Integer> rolled = new LinkedList<>(); // // private final RunData parent; // // public RunData(Result result) { // this(result, null); // } // // /** // * Constructor for a new RunData with a parent. // * // * @param result the result object // * @param parent the parent RunData, to whom all rolls will be reported (if parent is not null) // */ // RunData(Result result, RunData parent) { // this.result = result; // this.parent = parent; // } // // /** Returns a random integer between 1 and <code>maxValue</code> */ // public int randomInt(int maxValue) { // return randomInt(1, maxValue); // } // // /** Returns a list of random integers between 1 and <code>maxValue</code> */ // public int[] randomInts(int num, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) { // ret[i] = randomInt(maxValue); // } // return ret; // } // // /** Returns a random integer between <code>minValue</code> and <code>maxValue</code> */ // public int randomInt(int minValue, int maxValue) { // randomMin += minValue; // randomMax += maxValue; // // int result = RANDOM.nextInt(maxValue - minValue + 1) + minValue; // // recordRolled(result); // // randomValue += result; // // return result; // } // // /** // * Returns a list of random integers between <code>minValue</code> and <code>maxValue</code> // * // * @return // */ // public int[] randomInts(int num, int minValue, int maxValue) { // int[] ret = new int[num]; // for (int i = 0; i < num; i++) ret[i] = randomInt(minValue, maxValue); // return ret; // } // // public Result getResult() { // return result; // } // // public static boolean hasCurrent() { // return current.get() != null; // } // // public static RunData getCurrent() { // RunData data = current.get(); // if (data == null) { // throw new NullPointerException("data cannot be null"); // } // return data; // } // // public static void setCurrent(RunData data) { // current.set(data); // } // // // If a seed is set we need to switch from SecureRandom to // // random. // public static void setSeed(long seed) { // RANDOM = new Random(seed); // } // // /** // * Records the rolls, passing through to the parent RunData (if any) // * // * @param roll the new roll to record // */ // void recordRolled(Integer roll) { // if (parent != null) parent.recordRolled(roll); // rolled.add(roll); // } // // /** // * Gets the list of rolled integers, including rolls generated by any child instances // * // * @return the list of rolls, in order // */ // public List<Integer> getRolled() { // return Collections.unmodifiableList(rolled); // } // // /** // * Create a new RunData instance for a child execution. Rolls produced by the child instance // * should propagate up to the list of rolls maintained by this (parent) instance. // * // * @param childResult the Result object for the new RunData // * @return a new RunData with this RunData as its parent // */ // public RunData createChildRunData(Result childResult) { // return new RunData(childResult, this); // } // } // Path: src/test/java/net/rptools/common/expression/function/DiceHelperTest.java import junit.framework.TestCase; import net.rptools.common.expression.RunData; import net.rptools.parser.function.EvaluationException; /* * This software Copyright by the RPTools.net development team, and * licensed under the Affero GPL Version 3 or, at your option, any later * version. * * MapTool Source Code is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU Affero General Public * License * along with this source Code. If not, please visit * <http://www.gnu.org/licenses/> and specifically the Affero license * text at <http://www.gnu.org/licenses/agpl.html>. */ package net.rptools.common.expression.function; public class DiceHelperTest extends TestCase { public void testRollDice() throws Exception {
RunData.setCurrent(new RunData(null));
GideonLeGrange/mikrotik-java
src/main/java/examples/SimpleCommandWithResults.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 2: A command that returns results. Print all interfaces * * @author gideon */ public class SimpleCommandWithResults extends Example { public static void main(String... args) throws Exception { SimpleCommandWithResults ex = new SimpleCommandWithResults(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/SimpleCommandWithResults.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 2: A command that returns results. Print all interfaces * * @author gideon */ public class SimpleCommandWithResults extends Example { public static void main(String... args) throws Exception { SimpleCommandWithResults ex = new SimpleCommandWithResults(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/CharacterSets.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example to show that different character sets may work some times. * * @author gideon */ public class CharacterSets extends Example { private static final String JAPANESE = "事報ハヤ久送とゅ歳用ト候新放すルドう二5春園ユヲロ然納レ部悲と被状クヘ芸一ーあぽだ野健い産隊ず"; private static final String CRYLLIC = "Лорем ипсум долор сит амет, легере елояуентиам хис ид. Елигенди нолуиссе вих ут. Нихил"; private static final String ARABIC = "تجهيز والمانيا تم قام. وحتّى المتاخمة ما وقد. أسر أمدها تكبّد عل. فقد بسبب ترتيب استدعى أم, مما مع غرّة، لأداء. الشتاء، عسكرياً"; public static void main(String... args) throws Exception { CharacterSets ex = new CharacterSets(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/CharacterSets.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example to show that different character sets may work some times. * * @author gideon */ public class CharacterSets extends Example { private static final String JAPANESE = "事報ハヤ久送とゅ歳用ト候新放すルドう二5春園ユヲロ然納レ部悲と被状クヘ芸一ーあぽだ野健い産隊ず"; private static final String CRYLLIC = "Лорем ипсум долор сит амет, легере елояуентиам хис ид. Елигенди нолуиссе вих ут. Нихил"; private static final String ARABIC = "تجهيز والمانيا تم قام. وحتّى المتاخمة ما وقد. أسر أمدها تكبّد عل. فقد بسبب ترتيب استدعى أم, مما مع غرّة، لأداء. الشتاء، عسكرياً"; public static void main(String... args) throws Exception { CharacterSets ex = new CharacterSets(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/CommandWithWhere.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 3: Queries. Print all interfaces of a certain type. * * @author gideon */ public class CommandWithWhere extends Example { public static void main(String... args) throws Exception { CommandWithWhere ex = new CommandWithWhere(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/CommandWithWhere.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 3: Queries. Print all interfaces of a certain type. * * @author gideon */ public class CommandWithWhere extends Example { public static void main(String... args) throws Exception { CommandWithWhere ex = new CommandWithWhere(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/SimpleCommand.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 1: A very simple command: Reboot the remote router * @author gideon */ public class SimpleCommand extends Example { public static void main(String...args) throws Exception { SimpleCommand ex = new SimpleCommand(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/SimpleCommand.java import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 1: A very simple command: Reboot the remote router * @author gideon */ public class SimpleCommand extends Example { public static void main(String...args) throws Exception { SimpleCommand ex = new SimpleCommand(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/AddAndModify.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 6: Create and modify object * * @author gideon */ public class AddAndModify extends Example { public static void main(String... args) throws Exception { AddAndModify ex = new AddAndModify(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/AddAndModify.java import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 6: Create and modify object * * @author gideon */ public class AddAndModify extends Example { public static void main(String... args) throws Exception { AddAndModify ex = new AddAndModify(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException, InterruptedException {
GideonLeGrange/mikrotik-java
src/main/java/examples/Example.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // }
import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection;
package examples; /** * * @author gideon */ abstract class Example { protected void connect() throws Exception {
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // Path: src/main/java/examples/Example.java import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection; package examples; /** * * @author gideon */ abstract class Example { protected void connect() throws Exception {
con = ApiConnection.connect(SocketFactory.getDefault(), Config.HOST, ApiConnection.DEFAULT_PORT, 2000);
GideonLeGrange/mikrotik-java
src/main/java/me/legrange/mikrotik/impl/Util.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnectionException.java // public class ApiConnectionException extends MikrotikApiException { // // /** // * Create a new exception. // * // * @param msg The message // */ // public ApiConnectionException(String msg) { // super(msg); // } // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public ApiConnectionException(String msg, Throwable err) { // super(msg, err); // } // // // // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import me.legrange.mikrotik.ApiConnectionException;
package me.legrange.mikrotik.impl; /** * Utility library that handles the low level encoding required by the Mikrotik * API. * * @author GideonLeGrange. Possibly some code by janisk left. */ final class Util { /** * write a command to the output stream */ static void write(Command cmd, OutputStream out) throws UnsupportedEncodingException, IOException { encode(cmd.getCommand(), out); for (Parameter param : cmd.getParameters()) { encode(String.format("=%s=%s", param.getName(), param.hasValue() ? param.getValue() : ""), out); } String tag = cmd.getTag(); if ((tag != null) && !tag.equals("")) { encode(String.format(".tag=%s", tag), out); } List<String> props = cmd.getProperties(); if (!props.isEmpty()) { StringBuilder buf = new StringBuilder("=.proplist="); for (int i = 0; i < props.size(); ++i) { if (i > 0) { buf.append(","); } buf.append(props.get(i)); } encode(buf.toString(), out); } for (String query : cmd.getQueries()) { encode(query, out); } out.write(0); } /** * decode bytes from an input stream of Mikrotik protocol sentences into * text */
// Path: src/main/java/me/legrange/mikrotik/ApiConnectionException.java // public class ApiConnectionException extends MikrotikApiException { // // /** // * Create a new exception. // * // * @param msg The message // */ // public ApiConnectionException(String msg) { // super(msg); // } // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public ApiConnectionException(String msg, Throwable err) { // super(msg, err); // } // // // // } // Path: src/main/java/me/legrange/mikrotik/impl/Util.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import me.legrange.mikrotik.ApiConnectionException; package me.legrange.mikrotik.impl; /** * Utility library that handles the low level encoding required by the Mikrotik * API. * * @author GideonLeGrange. Possibly some code by janisk left. */ final class Util { /** * write a command to the output stream */ static void write(Command cmd, OutputStream out) throws UnsupportedEncodingException, IOException { encode(cmd.getCommand(), out); for (Parameter param : cmd.getParameters()) { encode(String.format("=%s=%s", param.getName(), param.hasValue() ? param.getValue() : ""), out); } String tag = cmd.getTag(); if ((tag != null) && !tag.equals("")) { encode(String.format(".tag=%s", tag), out); } List<String> props = cmd.getProperties(); if (!props.isEmpty()) { StringBuilder buf = new StringBuilder("=.proplist="); for (int i = 0; i < props.size(); ++i) { if (i > 0) { buf.append(","); } buf.append(props.get(i)); } encode(buf.toString(), out); } for (String query : cmd.getQueries()) { encode(query, out); } out.write(0); } /** * decode bytes from an input stream of Mikrotik protocol sentences into * text */
static String decode(InputStream in) throws ApiDataException, ApiConnectionException {
GideonLeGrange/mikrotik-java
src/main/java/examples/ConnectTLSCertificate.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import javax.net.ssl.SSLSocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
/* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open a TLS connection * * @author gideon */ public class ConnectTLSCertificate { public static void main(String... args) throws Exception { ConnectTLSCertificate ex = new ConnectTLSCertificate(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/ConnectTLSCertificate.java import java.util.List; import java.util.Map; import javax.net.ssl.SSLSocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; /* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open a TLS connection * * @author gideon */ public class ConnectTLSCertificate { public static void main(String... args) throws Exception { ConnectTLSCertificate ex = new ConnectTLSCertificate(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/ConnectTLSCertificate.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import javax.net.ssl.SSLSocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
/* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open a TLS connection * * @author gideon */ public class ConnectTLSCertificate { public static void main(String... args) throws Exception { ConnectTLSCertificate ex = new ConnectTLSCertificate(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException { List<Map<String, String>> results = con.execute("/interface/print"); for (Map<String, String> result : results) { System.out.println(result); } } protected void connect() throws Exception {
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/ConnectTLSCertificate.java import java.util.List; import java.util.Map; import javax.net.ssl.SSLSocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; /* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open a TLS connection * * @author gideon */ public class ConnectTLSCertificate { public static void main(String... args) throws Exception { ConnectTLSCertificate ex = new ConnectTLSCertificate(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException { List<Map<String, String>> results = con.execute("/interface/print"); for (Map<String, String> result : results) { System.out.println(result); } } protected void connect() throws Exception {
con = ApiConnection.connect(SSLSocketFactory.getDefault(), Config.HOST, ApiConnection.DEFAULT_TLS_PORT, ApiConnection.DEFAULT_CONNECTION_TIMEOUT);
GideonLeGrange/mikrotik-java
src/main/java/examples/ConnectTLSAnonymous.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
/* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open an Anonymous TLS connection * * @author gideon */ public class ConnectTLSAnonymous { public static void main(String... args) throws Exception { ConnectTLSAnonymous ex = new ConnectTLSAnonymous(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/ConnectTLSAnonymous.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; /* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open an Anonymous TLS connection * * @author gideon */ public class ConnectTLSAnonymous { public static void main(String... args) throws Exception { ConnectTLSAnonymous ex = new ConnectTLSAnonymous(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/ConnectTLSAnonymous.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
/* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open an Anonymous TLS connection * * @author gideon */ public class ConnectTLSAnonymous { public static void main(String... args) throws Exception { ConnectTLSAnonymous ex = new ConnectTLSAnonymous(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException { List<Map<String, String>> results = con.execute("/interface/print"); for (Map<String, String> result : results) { System.out.println(result); } } protected void connect() throws Exception {
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/ConnectTLSAnonymous.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; /* * Copyright 2015 gideon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples; /** * Example: Open an Anonymous TLS connection * * @author gideon */ public class ConnectTLSAnonymous { public static void main(String... args) throws Exception { ConnectTLSAnonymous ex = new ConnectTLSAnonymous(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException { List<Map<String, String>> results = con.execute("/interface/print"); for (Map<String, String> result : results) { System.out.println(result); } } protected void connect() throws Exception {
con = ApiConnection.connect(AnonymousSocketFactory.getDefault(), Config.HOST, ApiConnection.DEFAULT_TLS_PORT, ApiConnection.DEFAULT_CONNECTION_TIMEOUT);
GideonLeGrange/mikrotik-java
src/main/java/examples/DownloadConfig.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 7: Dump your complete config * * @author gideon */ public class DownloadConfig extends Example { public static void main(String... args) throws Exception { DownloadConfig ex = new DownloadConfig(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/DownloadConfig.java import java.util.List; import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 7: Dump your complete config * * @author gideon */ public class DownloadConfig extends Example { public static void main(String... args) throws Exception { DownloadConfig ex = new DownloadConfig(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException, InterruptedException {
GideonLeGrange/mikrotik-java
src/main/java/me/legrange/mikrotik/impl/Parser.java
// Path: src/main/java/me/legrange/mikrotik/impl/Scanner.java // enum Token { // // SLASH("/"), COMMA(","), EOL(), WS, TEXT, // LESS("<"), MORE(">"), EQUALS("="), NOT_EQUALS("!="), PIPE("!"), // LEFT_BRACKET("("), RIGHT_BRACKET(")"), // WHERE, NOT, AND, OR, RETURN; // // @Override // public String toString() { // return (symb == null) ? name() : symb; // } // // private Token(String symb) { // this.symb = symb; // } // // private Token() { // symb = null; // } // // private final String symb; // }
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import me.legrange.mikrotik.impl.Scanner.Token;
package me.legrange.mikrotik.impl; /** * Parse the pseudo-command line into command objects. * * @author GideonLeGrange */ class Parser { /** * parse the given bit of text into a Command object */ static Command parse(String text) throws ParseException { Parser parser = new Parser(text); return parser.parse(); } /** * run parse on the internal data and return the command object */ private Command parse() throws ParseException { command();
// Path: src/main/java/me/legrange/mikrotik/impl/Scanner.java // enum Token { // // SLASH("/"), COMMA(","), EOL(), WS, TEXT, // LESS("<"), MORE(">"), EQUALS("="), NOT_EQUALS("!="), PIPE("!"), // LEFT_BRACKET("("), RIGHT_BRACKET(")"), // WHERE, NOT, AND, OR, RETURN; // // @Override // public String toString() { // return (symb == null) ? name() : symb; // } // // private Token(String symb) { // this.symb = symb; // } // // private Token() { // symb = null; // } // // private final String symb; // } // Path: src/main/java/me/legrange/mikrotik/impl/Parser.java import java.util.Arrays; import java.util.LinkedList; import java.util.List; import me.legrange.mikrotik.impl.Scanner.Token; package me.legrange.mikrotik.impl; /** * Parse the pseudo-command line into command objects. * * @author GideonLeGrange */ class Parser { /** * parse the given bit of text into a Command object */ static Command parse(String text) throws ParseException { Parser parser = new Parser(text); return parser.parse(); } /** * run parse on the internal data and return the command object */ private Command parse() throws ParseException { command();
while (!is(Token.WHERE, Token.RETURN, Token.EOL)) {
GideonLeGrange/mikrotik-java
src/main/java/examples/TryWithResources.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 9: Try with resources * * @author gideon */ public class TryWithResources { public static void main(String... args) throws Exception { TryWithResources ex = new TryWithResources(); ex.test(); }
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/TryWithResources.java import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 9: Try with resources * * @author gideon */ public class TryWithResources { public static void main(String... args) throws Exception { TryWithResources ex = new TryWithResources(); ex.test(); }
private void test() throws MikrotikApiException, InterruptedException {
GideonLeGrange/mikrotik-java
src/main/java/examples/TryWithResources.java
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 9: Try with resources * * @author gideon */ public class TryWithResources { public static void main(String... args) throws Exception { TryWithResources ex = new TryWithResources(); ex.test(); } private void test() throws MikrotikApiException, InterruptedException {
// Path: src/main/java/me/legrange/mikrotik/ApiConnection.java // public abstract class ApiConnection implements AutoCloseable { // // /** // * default TCP port used by Mikrotik API // */ // public static final int DEFAULT_PORT = 8728; // /** // * default TCP TLS port used by Mikrotik API // */ // public static final int DEFAULT_TLS_PORT = 8729; // /** // * default connection timeout to use when opening the connection // */ // public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; // /** // * default command timeout used for synchronous commands // */ // public static final int DEFAULT_COMMAND_TIMEOUT = 60000; // // // /** // * Create a new API connection to the give device on the supplied port using // * the supplied socket factory to create the socket. // * // * @param fact SocketFactory to use for TCP socket creation. // * @param host The host to which to connect. // * @param port The TCP port to use. // * @param timeout The connection timeout to use when opening the connection. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // * @since 3.0 // */ // public static ApiConnection connect(SocketFactory fact, String host, int port, int timeout) throws MikrotikApiException { // return ApiConnectionImpl.connect(fact, host, port, timeout); // } // // /** // * Create a new API connection to the give device on the default API port. // * // * @param host The host to which to connect. // * @return The ApiConnection // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem connecting // */ // public static ApiConnection connect(String host) throws MikrotikApiException { // return connect(SocketFactory.getDefault(), host, DEFAULT_PORT, DEFAULT_COMMAND_TIMEOUT); // } // // /** // * Check the state of connection. // * // * @return if connection is established to router it returns true. // */ // public abstract boolean isConnected(); // // /** // * Log in to the remote router. // * // * @param username - username of the user on the router // * @param password - password for the user // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error on login. // */ // public abstract void login(String username, String password) throws MikrotikApiException; // // /** // * execute a command and return a list of results. // * // * @param cmd Command to execute // * @return The list of results // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract List<Map<String, String>> execute(String cmd) throws MikrotikApiException; // // /** // * execute a command and attach a result listener to receive it's results. // * // * @param cmd Command to execute // * @param lis ResultListener that will receive the results // * @return A command object that can be used to cancel the command. // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if the API encounters an error executing a command. // */ // public abstract String execute(String cmd, ResultListener lis) throws MikrotikApiException; // // /** // * cancel a command // * // * @param tag The tag of the command to cancel // * @throws me.legrange.mikrotik.MikrotikApiException Thrown if there is a // * problem cancelling the command // */ // public abstract void cancel(String tag) throws MikrotikApiException; // // /** // * set the command timeout. The command timeout is used to time out API // * commands after a specific time. // * // * Note: This is not the same as the timeout value passed in the connect() // * methods. This timeout is specific to synchronous // * commands, that timeout is applied to opening the API socket. // * // * @param timeout The time out in milliseconds. // * @throws MikrotikApiException Thrown if the timeout specified is invalid. // * @since 2.1 // */ // public abstract void setTimeout(int timeout) throws MikrotikApiException; // // /** // * Disconnect from the remote API // * // * @throws me.legrange.mikrotik.ApiConnectionException Thrown if there is a // * problem closing the connection. // * @since 2.2 // */ // @Override // public abstract void close() throws ApiConnectionException; // // } // // Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/TryWithResources.java import javax.net.SocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 9: Try with resources * * @author gideon */ public class TryWithResources { public static void main(String... args) throws Exception { TryWithResources ex = new TryWithResources(); ex.test(); } private void test() throws MikrotikApiException, InterruptedException {
try (ApiConnection con = ApiConnection.connect(SocketFactory.getDefault(), Config.HOST, ApiConnection.DEFAULT_PORT, 2000)) {
GideonLeGrange/mikrotik-java
src/main/java/examples/AsyncWithErrorHandling.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // }
import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener;
package examples; /** * Example 5: Asynchronous results, with error and completion. Run a command and receive results, errors and completion notification for it asynchronously with a ResponseListener * * @author gideon */ public class AsyncWithErrorHandling extends Example { public static void main(String... args) throws Exception { AsyncWithErrorHandling ex = new AsyncWithErrorHandling(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // } // Path: src/main/java/examples/AsyncWithErrorHandling.java import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener; package examples; /** * Example 5: Asynchronous results, with error and completion. Run a command and receive results, errors and completion notification for it asynchronously with a ResponseListener * * @author gideon */ public class AsyncWithErrorHandling extends Example { public static void main(String... args) throws Exception { AsyncWithErrorHandling ex = new AsyncWithErrorHandling(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException, InterruptedException {
GideonLeGrange/mikrotik-java
src/main/java/examples/AsyncWithErrorHandling.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // }
import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener;
package examples; /** * Example 5: Asynchronous results, with error and completion. Run a command and receive results, errors and completion notification for it asynchronously with a ResponseListener * * @author gideon */ public class AsyncWithErrorHandling extends Example { public static void main(String... args) throws Exception { AsyncWithErrorHandling ex = new AsyncWithErrorHandling(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException, InterruptedException { boolean completed = false;
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // } // Path: src/main/java/examples/AsyncWithErrorHandling.java import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener; package examples; /** * Example 5: Asynchronous results, with error and completion. Run a command and receive results, errors and completion notification for it asynchronously with a ResponseListener * * @author gideon */ public class AsyncWithErrorHandling extends Example { public static void main(String... args) throws Exception { AsyncWithErrorHandling ex = new AsyncWithErrorHandling(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException, InterruptedException { boolean completed = false;
String id = con.execute("/interface/wireless/monitor .id=wlan1", new ResultListener() {
GideonLeGrange/mikrotik-java
src/main/java/examples/AsyncCommand.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // }
import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener;
package examples; /** * Example 4: Asynchronous results. Run a command and receive results for it asynchronously with a ResultListener * * @author gideon */ public class AsyncCommand extends Example { public static void main(String... args) throws Exception { AsyncCommand ex = new AsyncCommand(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // } // Path: src/main/java/examples/AsyncCommand.java import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener; package examples; /** * Example 4: Asynchronous results. Run a command and receive results for it asynchronously with a ResultListener * * @author gideon */ public class AsyncCommand extends Example { public static void main(String... args) throws Exception { AsyncCommand ex = new AsyncCommand(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException, InterruptedException {
GideonLeGrange/mikrotik-java
src/main/java/examples/AsyncCommand.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // }
import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener;
package examples; /** * Example 4: Asynchronous results. Run a command and receive results for it asynchronously with a ResultListener * * @author gideon */ public class AsyncCommand extends Example { public static void main(String... args) throws Exception { AsyncCommand ex = new AsyncCommand(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException, InterruptedException {
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: src/main/java/me/legrange/mikrotik/ResultListener.java // public interface ResultListener { // // /** receive data from router // * @param result The data received */ // void receive(Map<String, String> result); // // /** called if the command associated with this listener experiences an error // * @param ex Exception encountered */ // void error(MikrotikApiException ex); // // /** called when the command associated with this listener is done */ // void completed(); // // } // Path: src/main/java/examples/AsyncCommand.java import java.util.Map; import me.legrange.mikrotik.MikrotikApiException; import me.legrange.mikrotik.ResultListener; package examples; /** * Example 4: Asynchronous results. Run a command and receive results for it asynchronously with a ResultListener * * @author gideon */ public class AsyncCommand extends Example { public static void main(String... args) throws Exception { AsyncCommand ex = new AsyncCommand(); ex.connect(); ex.test(); ex.disconnect(); } private void test() throws MikrotikApiException, InterruptedException {
String id = con.execute("/interface/wireless/monitor .id=wlan1 .proplist=signal-strength", new ResultListener() {
GideonLeGrange/mikrotik-java
src/main/java/examples/ScriptCommand.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import me.legrange.mikrotik.MikrotikApiException;
package examples; /** * Example 1: A very simple command: Reboot the remote router * @author gideon */ public class ScriptCommand extends Example { public static void main(String...args) throws Exception { ScriptCommand ex = new ScriptCommand(); ex.connect(); ex.test(); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/ScriptCommand.java import me.legrange.mikrotik.MikrotikApiException; package examples; /** * Example 1: A very simple command: Reboot the remote router * @author gideon */ public class ScriptCommand extends Example { public static void main(String...args) throws Exception { ScriptCommand ex = new ScriptCommand(); ex.connect(); ex.test(); ex.disconnect(); }
private void test() throws MikrotikApiException {
GideonLeGrange/mikrotik-java
src/main/java/examples/NestedExpressions.java
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // }
import me.legrange.mikrotik.MikrotikApiException; import java.util.List; import java.util.Map;
package examples; /** * Example 2: A command that returns results. Print all interfaces * * @author gideon */ public class NestedExpressions extends Example { public static void main(String... args) throws Exception { NestedExpressions ex = new NestedExpressions(); ex.connect(); ex.test("/ip/firewall/nat/print where (src-address=\"192.168.15.52\" or src-address=\"192.168.15.53\")"); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=192.168.15.52) and action=log "); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=192.168.15.53 or src-address=192.168.15.52) and action=log "); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=\"192.168.15.53\" or src-address=\"192.168.15.52\") and action=log "); ex.disconnect(); }
// Path: src/main/java/me/legrange/mikrotik/MikrotikApiException.java // public class MikrotikApiException extends Exception { // // // /** // * Create a new exception // * @param msg The message // */ // public MikrotikApiException(String msg) { // super(msg); // } // // // /** // * Create a new exception // * @param msg The message // * @param err The underlying cause // */ // public MikrotikApiException(String msg, Throwable err) { // super(msg, err); // } // } // Path: src/main/java/examples/NestedExpressions.java import me.legrange.mikrotik.MikrotikApiException; import java.util.List; import java.util.Map; package examples; /** * Example 2: A command that returns results. Print all interfaces * * @author gideon */ public class NestedExpressions extends Example { public static void main(String... args) throws Exception { NestedExpressions ex = new NestedExpressions(); ex.connect(); ex.test("/ip/firewall/nat/print where (src-address=\"192.168.15.52\" or src-address=\"192.168.15.53\")"); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=192.168.15.52) and action=log "); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=192.168.15.53 or src-address=192.168.15.52) and action=log "); ex.test("/ip/firewall/nat/print where chain=api_test and (src-address=\"192.168.15.53\" or src-address=\"192.168.15.52\") and action=log "); ex.disconnect(); }
private void test(String cmd) throws MikrotikApiException {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id;
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // } // Path: src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id;
private final Leader leader;
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader;
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // } // Path: src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader;
private Star star;
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); }
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // } // Path: src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); }
public void turn(Stars stars, List<Command> commands) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); }
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // } // Path: src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); }
public void turn(Stars stars, List<Command> commands) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); } public void turn(Stars stars, List<Command> commands) { for(Command command : commands) {
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/command/FleetDispatchCommand.java // public class FleetDispatchCommand extends Command { // // private final int fleetId; // private final String destinationStar; // // public FleetDispatchCommand(int fleetId, String destinationStar) { // this.fleetId = fleetId; // this.destinationStar = destinationStar; // } // // public int getFleetId() { // return fleetId; // } // // public String getDestinationStar() { // return destinationStar; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/Leader.java // public class Leader { // // private final String name; // private final String nation; // private final String homeStar; // // public Leader(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Leader) { // Leader other = (Leader) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Star.java // public class Star { // // public static class Prototype { // // private String name; // private Vector2D location; // // public Prototype(String name, int x, int y) { // this.name = name; // this.location = new Vector2D(x, y); // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // } // // private final String name; // private Vector2D location; // // private Optional<Colony> colony; // // public Star(String name, Vector2D location, Optional<Colony> colony) { // this.name = name; // this.location = location; // // this.colony = colony; // } // // public String getName() { // return name; // } // // public Vector2D getLocation() { // return location; // } // // public Optional<Colony> getColony() { // return colony; // } // } // // Path: src/main/java/com/scheible/risingempire/game/core/star/Stars.java // public class Stars extends ArrayList<Star> { // // public Star getByName(String star) { // for(Star currentStar : this) { // if(currentStar.getName().equals(star)) { // return currentStar; // } // } // // throw new IllegalStateException("The star '" + star + "' is unknown!"); // } // } // Path: src/main/java/com/scheible/risingempire/game/core/fleet/Fleet.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.command.FleetDispatchCommand; import com.scheible.risingempire.game.core.Leader; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.core.star.Stars; import java.util.List; import java.util.Optional; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; package com.scheible.risingempire.game.core.fleet; /** * * @author sj */ public class Fleet { private final double SPEED = 30.0f; private final int id; private final Leader leader; private Star star; private Optional<Star> destinationStar; private Optional<Vector2D> location; public Fleet(int id, Leader leader, Star star) { this.id = id; this.leader = leader; this.star = star; destinationStar = Optional.empty(); location = Optional.empty(); } public void turn(Stars stars, List<Command> commands) { for(Command command : commands) {
if(command instanceof FleetDispatchCommand) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // }
import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map;
package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn;
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // } // Path: src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map; package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn;
private final View view;
janScheible/rising-empire
src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // }
import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map;
package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn; private final View view; public TurnFinishedMessage(Player player, Map<String, String> colorMapping, int turn, View view) { this.player = player; this.colorMapping = colorMapping; this.turn = turn; this.view = view; // NOTE We have to exchange all event instance with ones that contain the EventType info. int eventIndex = -1;
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // } // Path: src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map; package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn; private final View view; public TurnFinishedMessage(Player player, Map<String, String> colorMapping, int turn, View view) { this.player = player; this.colorMapping = colorMapping; this.turn = turn; this.view = view; // NOTE We have to exchange all event instance with ones that contain the EventType info. int eventIndex = -1;
for(Event event : view.getEvents()) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // }
import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map;
package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn; private final View view; public TurnFinishedMessage(Player player, Map<String, String> colorMapping, int turn, View view) { this.player = player; this.colorMapping = colorMapping; this.turn = turn; this.view = view; // NOTE We have to exchange all event instance with ones that contain the EventType info. int eventIndex = -1; for(Event event : view.getEvents()) { eventIndex++;
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/Event.java // public abstract class Event { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/event/RandomMessageEvent.java // public class RandomMessageEvent extends Event { // // private final String message; // // public RandomMessageEvent(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // } // Path: src/main/java/com/scheible/risingempire/web/game/message/server/TurnFinishedMessage.java import com.scheible.risingempire.game.common.Player; import com.scheible.risingempire.game.common.event.Event; import com.scheible.risingempire.game.common.event.RandomMessageEvent; import com.scheible.risingempire.game.common.view.View; import java.util.Map; package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnFinishedMessage { private final Player player; private final Map<String, String> colorMapping; // <nationName, #??????> private final int turn; private final View view; public TurnFinishedMessage(Player player, Map<String, String> colorMapping, int turn, View view) { this.player = player; this.colorMapping = colorMapping; this.turn = turn; this.view = view; // NOTE We have to exchange all event instance with ones that contain the EventType info. int eventIndex = -1; for(Event event : view.getEvents()) { eventIndex++;
if(event instanceof RandomMessageEvent) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/web/game/message/server/TurnInfoMessage.java
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // }
import com.scheible.risingempire.game.common.Player; import java.util.HashMap; import java.util.Map;
package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnInfoMessage { private final Map<String, Boolean> status = new HashMap<>(); // <nationName, boolean>
// Path: src/main/java/com/scheible/risingempire/game/common/Player.java // public class Player { // // public static class Prototype { // // private final String name; // private final String nation; // private final String homeStar; // // public Prototype(String name, String nation, String homeStar) { // this.name = name; // this.nation = nation; // this.homeStar = homeStar; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // public String getHomeStar() { // return homeStar; // } // } // // private final String name; // private final String nation; // // public Player(String name, String nation) { // this.name = name; // this.nation = nation; // } // // public String getName() { // return name; // } // // public String getNation() { // return nation; // } // // @Override // public int hashCode() { // return Objects.hash(name, nation); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } else if (obj instanceof Player) { // Player other = (Player) obj; // return Objects.equals(name, other.name) && Objects.equals(nation, other.nation); // } else { // return false; // } // } // } // Path: src/main/java/com/scheible/risingempire/web/game/message/server/TurnInfoMessage.java import com.scheible.risingempire.game.common.Player; import java.util.HashMap; import java.util.Map; package com.scheible.risingempire.web.game.message.server; /** * * @author sj */ public class TurnInfoMessage { private final Map<String, Boolean> status = new HashMap<>(); // <nationName, boolean>
public TurnInfoMessage(Map<Player, Boolean> status) {
janScheible/rising-empire
src/main/java/com/scheible/risingempire/web/config/web/WebSecurityConfig.java
// Path: src/main/java/com/scheible/risingempire/web/security/ConnectedPlayer.java // public final class ConnectedPlayer implements UserDetails { // // public final static PasswordEncoder PASSWORD_ENCODER = NoOpPasswordEncoder.getInstance(); // public final static String DEFAULT_PASSWORD = "yyy"; // // private final String username; // // /* package */ ConnectedPlayer(String username) { // this.username = username; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return AuthorityUtils.createAuthorityList("ROLE_USER"); // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // // @Override // public String getPassword() { // return DEFAULT_PASSWORD; // } // }
import com.scheible.risingempire.web.security.ConnectedPlayer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor; import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.web.servlet.support.RequestDataValueProcessor;
package com.scheible.risingempire.web.config.web; /** * * @author sj */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().antMatchers("/css/**", "/js/**", "/typescript/**", "/images/**", "/**/favicon.ico").permitAll().and() .authorizeRequests().regexMatchers("/players").permitAll().and() .authorizeRequests().regexMatchers("/addAi").permitAll().and() .authorizeRequests().regexMatchers("/csrf").permitAll().and() .authorizeRequests().regexMatchers("/shutdown").permitAll().and() // NOTE Not production ready! ;-) .authorizeRequests().antMatchers("/h2-console/**").permitAll().and() // NOTE Not production ready as well! ;-) .authorizeRequests().anyRequest().fullyAuthenticated().and() .formLogin().loginProcessingUrl("/login").loginPage("/join.html").failureUrl("/join.html?error").defaultSuccessUrl("/game.html", true).permitAll().and() .logout().permitAll(); http .csrf() .requireCsrfProtectionMatcher(new AndRequestMatcher(CsrfFilter.DEFAULT_CSRF_MATCHER, new RegexRequestMatcher("^(?!/h2-console/)", null))); http.headers().frameOptions().sameOrigin(); // // NOTE Also needed for h2-console. } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception {
// Path: src/main/java/com/scheible/risingempire/web/security/ConnectedPlayer.java // public final class ConnectedPlayer implements UserDetails { // // public final static PasswordEncoder PASSWORD_ENCODER = NoOpPasswordEncoder.getInstance(); // public final static String DEFAULT_PASSWORD = "yyy"; // // private final String username; // // /* package */ ConnectedPlayer(String username) { // this.username = username; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return AuthorityUtils.createAuthorityList("ROLE_USER"); // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // // @Override // public String getPassword() { // return DEFAULT_PASSWORD; // } // } // Path: src/main/java/com/scheible/risingempire/web/config/web/WebSecurityConfig.java import com.scheible.risingempire.web.security.ConnectedPlayer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor; import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.web.servlet.support.RequestDataValueProcessor; package com.scheible.risingempire.web.config.web; /** * * @author sj */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().antMatchers("/css/**", "/js/**", "/typescript/**", "/images/**", "/**/favicon.ico").permitAll().and() .authorizeRequests().regexMatchers("/players").permitAll().and() .authorizeRequests().regexMatchers("/addAi").permitAll().and() .authorizeRequests().regexMatchers("/csrf").permitAll().and() .authorizeRequests().regexMatchers("/shutdown").permitAll().and() // NOTE Not production ready! ;-) .authorizeRequests().antMatchers("/h2-console/**").permitAll().and() // NOTE Not production ready as well! ;-) .authorizeRequests().anyRequest().fullyAuthenticated().and() .formLogin().loginProcessingUrl("/login").loginPage("/join.html").failureUrl("/join.html?error").defaultSuccessUrl("/game.html", true).permitAll().and() .logout().permitAll(); http .csrf() .requireCsrfProtectionMatcher(new AndRequestMatcher(CsrfFilter.DEFAULT_CSRF_MATCHER, new RegexRequestMatcher("^(?!/h2-console/)", null))); http.headers().frameOptions().sameOrigin(); // // NOTE Also needed for h2-console. } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(ConnectedPlayer.PASSWORD_ENCODER);
janScheible/rising-empire
src/main/java/com/scheible/risingempire/game/common/Game.java
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // }
import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.view.View; import java.util.List; import java.util.Map;
package com.scheible.risingempire.game.common; /** * * @author sj */ public interface Game { void register(Player player); void addAi(Player player); List<Player> getPlayers(); boolean isAi(Player player);
// Path: src/main/java/com/scheible/risingempire/game/common/command/Command.java // public abstract class Command { // // } // // Path: src/main/java/com/scheible/risingempire/game/common/view/View.java // public class View { // // private final List<Player> players; // private final List<Star> stars; // private final List<Fleet> fleets; // // private final List<Event> events; // // public View(String nation, List<Player> players, List<Star> stars, List<Fleet> fleets, List<Event> events) { // this.players = players; // this.stars = stars; // this.fleets = fleets; // // this.events = events; // } // // public List<Player> getPlayers() { // return players; // } // // public List<Star> getStars() { // return stars; // } // // public List<Fleet> getFleets() { // return fleets; // } // // public List<Event> getEvents() { // return events; // } // } // Path: src/main/java/com/scheible/risingempire/game/common/Game.java import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.common.view.View; import java.util.List; import java.util.Map; package com.scheible.risingempire.game.common; /** * * @author sj */ public interface Game { void register(Player player); void addAi(Player player); List<Player> getPlayers(); boolean isAi(Player player);
boolean process(Player player, List<Command> commands);