Skip to content

Commit

Permalink
Code quality improvements. Updates to the new release.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mariana Azevedo committed Mar 8, 2019
1 parent 9fc005c commit f7e5c87
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 26 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,6 @@ You must import .jar into the classpath of your project. If your project is a ma
<dependency>
<groupId>io.github.mariazevedo88</groupId>
<artifactId>json-formatter-validator</artifactId>
<version>1.1.6</version>
<version>1.1.7</version>
</dependency>
```
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
<connection>scm:git:git://github.com/mariazevedo88/json-formatter-validator.git</connection>
<developerConnection>scm:git:git@github.com:mariazevedo88/json-formatter-validator.git</developerConnection>
<url>https://github.com/mariazevedo88/json-formatter-validator</url>
<tag>json-formatter-validator-1.1.6</tag>
<tag>json-formatter-validator-1.1.7</tag>
</scm>

<distributionManagement>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.github.mariazevedo88.jsonformattervalidator.enumeration;

public enum DelimitersEnum {

COLON(":"),
COMMA(","),
DOUBLE_COMMA(",,"),
EMPTY_STRING(""),
RIGHT_DOUBLE_QUOTE_WITH_ESCAPE("\""),
RIGHT_KEY("}"),
RIGHT_KEY_WITH_ESCAPE("\"}"),
SEMICOLON(";"),
QUOTES("''");

private String value;

private DelimitersEnum(String value){
this.value = value;
}

public String getValue() {
return value;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.MalformedJsonException;

import io.github.mariazevedo88.jsonformattervalidator.enumeration.DelimitersEnum;

/**
* Class that verify a json and format in cases of invalid json
* Class that verify a JSON and format in cases of invalid JSON
*
* @author Mariana Azevedo
* @since 10/02/2019
Expand All @@ -33,7 +35,7 @@ public class CustomJSONFormatter {
private JsonObject validJson;

/**
* Method that verify in a object is a valid or invalid json.
* Method that verify in a object is a valid or invalid JSON.
*
* @author Mariana Azevedo
* @since 10/02/2019
Expand All @@ -60,7 +62,7 @@ private boolean isValidJson(Object json){
}

/**
* Method that parses a json object.
* Method that parses a JSON object.
*
* @author Mariana Azevedo
* @since 10/02/2019
Expand All @@ -84,7 +86,7 @@ private void parseJSONObject(Object json) {
}

/**
* Method to convert a invalid json, add double quotes where is needed. Based on the answers of this question:
* Method to convert a invalid JSON, add double quotes where is needed. Based on the answers of this question:
* https://stackoverflow.com/questions/54584696/how-add-quotes-in-a-json-string-using-java-when-the-value-is-a-date
*
* (?<=: ?): there’s a colon an optionally a blank before the value (lookbehind)
Expand Down Expand Up @@ -122,7 +124,7 @@ private static String getInvalidJsonToFormat(String invalidJson) {
* @return
*/
private static String fixFieldsWithSimpleQuotes(String invalidJson) {
return invalidJson.replaceAll("''", "");
return invalidJson.replaceAll(DelimitersEnum.QUOTES.getValue(), DelimitersEnum.EMPTY_STRING.getValue());
}

/**
Expand All @@ -149,7 +151,8 @@ private static String fixEmptyFields(String invalidJson) {
* @return
*/
private static String replaceControlDelimiters(StringBuilder builderModified) {
return builderModified.toString().replaceAll(";", ",");
return builderModified.toString().replaceAll(DelimitersEnum.SEMICOLON.getValue(),
DelimitersEnum.COMMA.getValue());
}

/**
Expand All @@ -163,7 +166,7 @@ private static String replaceControlDelimiters(StringBuilder builderModified) {
*/
private static StringBuilder fixFieldsWithCommasWronglyModified(StringBuilder builderModified){

String [] invalidJsonValues = builderModified.toString().split(",");
String [] invalidJsonValues = builderModified.toString().split(DelimitersEnum.COMMA.getValue());
boolean hasInvalidValues = true;

while(hasInvalidValues) {
Expand All @@ -173,14 +176,14 @@ private static StringBuilder fixFieldsWithCommasWronglyModified(StringBuilder bu
throw new JsonParseException("Error: JSON with more invalid characters than commas and quotes on keys and values.");
}

invalidJsonValues = builderModified.toString().split(",");
invalidJsonValues = builderModified.toString().split(DelimitersEnum.COMMA.getValue());

if(!isStringHasInvalidJsonValues(invalidJsonValues)) {
hasInvalidValues = false;
}
}

if(!builderModified.toString().contains(",")){
if(!builderModified.toString().contains(DelimitersEnum.COMMA.getValue())){
throw new JsonSyntaxException("Error: JSON doesn't have fields separated by commas.");
}

Expand All @@ -197,7 +200,7 @@ private static StringBuilder fixFieldsWithCommasWronglyModified(StringBuilder bu
*/
private static boolean isStringHasInvalidJsonValues(String [] invalidJsonValues) {
Set<String> collection = Arrays.stream(invalidJsonValues).collect(Collectors.toSet());
return collection.stream().anyMatch(str -> !str.contains(":"));
return collection.stream().anyMatch(str -> !str.contains(DelimitersEnum.COLON.getValue()));
}

/**
Expand All @@ -212,11 +215,11 @@ private static boolean isStringHasInvalidJsonValues(String [] invalidJsonValues)
private static StringBuilder cleanInvalidJsonValues(String[] invalidJsonValues, StringBuilder builder) {

StringBuilder builderModified = new StringBuilder(builder);
String previousField = "";
String previousField = DelimitersEnum.EMPTY_STRING.getValue();

List<String> collection = Arrays.stream(invalidJsonValues).collect(Collectors.toList());
for(String str : collection) {
if(str.contains(":")) {
if(str.contains(DelimitersEnum.COLON.getValue())) {
previousField = str;
}else{
if(!str.isEmpty()) {
Expand Down Expand Up @@ -246,26 +249,26 @@ private static void cleanWrongQuotesOnFields(StringBuilder builderModified, Stri
int lastIndexOf = previousField.length();

try {
if(sbReplace.lastIndexOf("\"") == lastIndexOf-1) {
if(sbReplace.lastIndexOf(DelimitersEnum.RIGHT_DOUBLE_QUOTE_WITH_ESCAPE.getValue()) == lastIndexOf-1) {
sbReplace = sbReplace.deleteCharAt(lastIndexOf-1);
sbReplace.insert(lastIndexOf-1, ";");
sbReplace.insert(lastIndexOf-1, DelimitersEnum.SEMICOLON.getValue());
}
}catch(StringIndexOutOfBoundsException exception){
throw new StringIndexOutOfBoundsException("String is an empty object or has an invalid structure (key without value or vice-versa): " + str);
}

if(str.contains("}")){
if(str.contains(DelimitersEnum.RIGHT_KEY.getValue())){
//If the field that has commas in the middle, but is at the end of the object,
//treat so that the quotes are in the right place
int lastIndexOfStr = str.length();
String strModified = new StringBuilder(str).deleteCharAt(lastIndexOfStr-1).toString();
sbReplace.append(strModified).append("\"}");
sbReplace.append(strModified).append(DelimitersEnum.RIGHT_KEY_WITH_ESCAPE.getValue());
}else{
sbReplace.append(str).append("\"");
sbReplace.append(str).append(DelimitersEnum.RIGHT_DOUBLE_QUOTE_WITH_ESCAPE.getValue());
}

Pattern pattern = Pattern.compile(str, Pattern.LITERAL);
replaceStringBasedOnAPattern(builderModified, pattern, "");
replaceStringBasedOnAPattern(builderModified, pattern, DelimitersEnum.EMPTY_STRING.getValue());

try {
pattern = Pattern.compile(previousField);
Expand All @@ -274,8 +277,8 @@ private static void cleanWrongQuotesOnFields(StringBuilder builderModified, Stri
splitPatternToNearowTheSearch(builderModified, previousField, sbReplace);
}

pattern = Pattern.compile(",,");
replaceStringBasedOnAPattern(builderModified, pattern, ",");
pattern = Pattern.compile(DelimitersEnum.DOUBLE_COMMA.getValue());
replaceStringBasedOnAPattern(builderModified, pattern, DelimitersEnum.COMMA.getValue());
}

/**
Expand All @@ -291,8 +294,8 @@ private static void cleanWrongQuotesOnFields(StringBuilder builderModified, Stri
private static void splitPatternToNearowTheSearch(StringBuilder builderModified, String previousField,
StringBuilder sbReplace) {

String[] patternSplit = previousField.split(":");
String[] sbReplaceToSplit = sbReplace.toString().split(":");
String[] patternSplit = previousField.split(DelimitersEnum.COLON.getValue());
String[] sbReplaceToSplit = sbReplace.toString().split(DelimitersEnum.COLON.getValue());

Pattern pattern = Pattern.compile(patternSplit[patternSplit.length-1]);
replaceStringBasedOnAPattern(builderModified, pattern, sbReplaceToSplit[sbReplaceToSplit.length-1]);
Expand All @@ -318,7 +321,7 @@ private static void replaceStringBasedOnAPattern(StringBuilder builderModified,
}

/**
* Method that checks json validity and format if needed.
* Method that checks JSON validity and format if needed.
*
* @author Mariana Azevedo
* @since 17/02/2019
Expand Down Expand Up @@ -356,7 +359,7 @@ public JsonObject checkValidityAndFormatObject(Object json) throws IOException {
}

/**
* Method that return a valid json
* Method that return a valid JSON
*
* @author Mariana Azevedo
* @since 10/02/2019
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.github.mariazevedo88.jsonformattervalidator.test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

Expand All @@ -19,6 +20,7 @@
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.TestMethodOrder;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
Expand Down Expand Up @@ -202,6 +204,37 @@ public void getInvalidJSONFromJsonFile() throws IOException {
});
}

@Test
@DisplayName("Get a JSON Array From Empty Object as a String")
@Order(18)
public void getJSONArrayFromEmptyObjectAsString() throws IOException {
assertThrows(StringIndexOutOfBoundsException.class,()->{
formatter.checkValidityAndFormatObject("[]");
});
}

@Test
@DisplayName("Verify if the String as a JSON Array is a JSON Object")
@Order(19)
public void verifyIfJSONArrayIsJSONObject() throws IOException {
String jsonWithDotBeforeComma = "{paymentMethods:[{sequential:1,id:CREDIT_CARD,value:169.89,installments:2}]}";
JsonObject json = formatter.checkValidityAndFormatObject(jsonWithDotBeforeComma);

JsonElement jsonElement = json.get("paymentMethods");
assertFalse(jsonElement.isJsonObject());
}

@Test
@DisplayName("Verify if JSON Object has a valid value")
@Order(20)
public void verifyIfJSONObjectHasValidValue() throws IOException {
String jsonWithDotBeforeComma = "{id:1234567890, productCode:02-671806364}";
JsonObject json = formatter.checkValidityAndFormatObject(jsonWithDotBeforeComma);

JsonElement jsonElement = json.get("id");
assertTrue(jsonElement.isJsonPrimitive()); //JsonPrimitive = primitive types and Java types
}

@AfterAll
public void tearDown() {
formatter = null;
Expand Down

0 comments on commit f7e5c87

Please sign in to comment.