Skip to content

Commit

Permalink
Merge pull request #595 from xenoamess-fork/support_multiple-object_j…
Browse files Browse the repository at this point in the history
…son_file

support multiple-object json file
  • Loading branch information
hazendaz authored Feb 27, 2022
2 parents a98bbd2 + f3ae830 commit 7dda0a2
Show file tree
Hide file tree
Showing 9 changed files with 204 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,11 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<!-- TODO: Allow pull from snapshots while on jsoup snapshot, remove once finalized -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public abstract class AbstractCacheableFormatter {
protected Charset encoding;

/**
* Inits the.
* Inits the AbstractCacheableFormatter.
*
* @param options
* the options
Expand Down Expand Up @@ -130,6 +130,9 @@ private static String fixLineEnding(String code, final LineEnding ending) {
/**
* Do format.
*
* notice that when calling this function, {@code ending} here MUST equals lineending in config when
* {@link #init(Map, ConfigurationSource)} init.
*
* @param code
* the code
* @param ending
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/net/revelc/code/formatter/json/JsonFormatter.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@
package net.revelc.code.formatter.json;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.core.util.Separators;
Expand All @@ -36,6 +39,8 @@ public class JsonFormatter extends AbstractCacheableFormatter implements Formatt
/** The formatter. */
private ObjectMapper formatter;

private boolean multipleJsonObjectFileAllowed;

@Override
public void init(final Map<String, String> options, final ConfigurationSource cfg) {
super.initCfg(cfg);
Expand All @@ -44,6 +49,8 @@ public void init(final Map<String, String> options, final ConfigurationSource cf
final var lineEnding = options.getOrDefault("lineending", System.lineSeparator());
final var spaceBeforeSeparator = Boolean.parseBoolean(options.getOrDefault("spaceBeforeSeparator", "true"));
final var useAlphabeticalOrder = Boolean.parseBoolean(options.getOrDefault("alphabeticalOrder", "false"));
this.multipleJsonObjectFileAllowed = Boolean
.parseBoolean(options.getOrDefault("multipleJsonObjectFileAllowed", "true"));
this.formatter = new ObjectMapper();

// Setup a pretty printer with an indenter (indenter has 4 spaces in this case)
Expand Down Expand Up @@ -74,6 +81,14 @@ public DefaultPrettyPrinter withSeparators(final Separators separators) {

@Override
protected String doFormat(final String code, final LineEnding ending) throws IOException {
if (this.multipleJsonObjectFileAllowed) {
return doFormatWithMultipleJsonFileAllowed(code, ending);
}
return doFormatWithMultipleJsonFileForbidden(code, ending);
}

private String doFormatWithMultipleJsonFileForbidden(final String code, final LineEnding ending)
throws IOException {
// note: line ending set in init for this usecase
final var json = this.formatter.readValue(code, Object.class);
var formattedCode = this.formatter.writer().writeValueAsString(json);
Expand All @@ -84,6 +99,24 @@ protected String doFormat(final String code, final LineEnding ending) throws IOE
return formattedCode;
}

private String doFormatWithMultipleJsonFileAllowed(final String code, final LineEnding ending) throws IOException {
try (StringWriter stringWriter = new StringWriter()) {
JsonParser jsonParser = this.formatter.createParser(code);
// note: line ending set in init for this usecase
final Iterator<Object> jsonObjectIterator = this.formatter.readValues(jsonParser, Object.class);
while (jsonObjectIterator.hasNext()) {
String jsonString = this.formatter.writer().writeValueAsString(jsonObjectIterator.next());
stringWriter.write(jsonString);
stringWriter.write(ending.getChars());
}
String formattedCode = stringWriter.toString();
if (code.equals(formattedCode)) {
return null;
}
return formattedCode;
}
}

@Override
public boolean isInitialized() {
return this.formatter != null;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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
*
* https://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 net.revelc.code.formatter.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

import org.codehaus.plexus.util.IOUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import net.revelc.code.formatter.AbstractFormatterTest;
import net.revelc.code.formatter.LineEnding;

public class MultipleJsonFormatterTest extends AbstractFormatterTest {

private static String BEFORE_STRING;

private static String AFTER_STRING;

@BeforeAll
public static void init() throws IOException {
try (InputStream inputStream = NormalJsonFormatterTest.class
.getResourceAsStream("/multiple-json/before.json")) {
BEFORE_STRING = IOUtil.toString(Objects.requireNonNull(inputStream), "UTF-8");
}
try (InputStream inputStream = NormalJsonFormatterTest.class.getResourceAsStream("/multiple-json/after.json")) {
AFTER_STRING = IOUtil.toString(Objects.requireNonNull(inputStream), "UTF-8");
}
}

public static Stream<Arguments> testParamsProvider() {
return Stream.of(Arguments.of(LineEnding.CRLF, "true"), Arguments.of(LineEnding.LF, "true"),
Arguments.of(LineEnding.CR, "true"));
}

@ParameterizedTest
@MethodSource("testParamsProvider")
void test(LineEnding currentTestedLineEnding, String multipleJsonObjectFileAllowed) throws IOException {
final JsonFormatter jsonFormatter = new JsonFormatter();
Assertions.assertFalse(jsonFormatter.isInitialized());
jsonFormatter.init(
Map.of("lineending", currentTestedLineEnding.getChars(), "multipleJsonObjectFileAllowed",
multipleJsonObjectFileAllowed),
new TestConfigurationSource(AbstractFormatterTest.TEST_OUTPUT_PRIMARY_DIR));
Assertions.assertTrue(jsonFormatter.isInitialized());
String result = jsonFormatter.doFormat(BEFORE_STRING, currentTestedLineEnding);
Assertions.assertEquals(AFTER_STRING.replaceAll(LineEnding.CRLF.getChars(), LineEnding.LF.getChars())
.replaceAll(LineEnding.LF.getChars(), currentTestedLineEnding.getChars()), result);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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
*
* https://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 net.revelc.code.formatter.json;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

import org.codehaus.plexus.util.IOUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import net.revelc.code.formatter.AbstractFormatterTest;
import net.revelc.code.formatter.LineEnding;

public class NormalJsonFormatterTest extends AbstractFormatterTest {

private static String BEFORE_STRING;

private static String AFTER_STRING;

@BeforeAll
public static void init() throws IOException {
try (InputStream inputStream = NormalJsonFormatterTest.class.getResourceAsStream("/normal-json/before.json")) {
BEFORE_STRING = IOUtil.toString(Objects.requireNonNull(inputStream), "UTF-8");
}
try (InputStream inputStream = NormalJsonFormatterTest.class.getResourceAsStream("/normal-json/after.json")) {
AFTER_STRING = IOUtil.toString(Objects.requireNonNull(inputStream), "UTF-8");
}
}

public static Stream<Arguments> testParamsProvider() {
return Stream.of(Arguments.of(LineEnding.CRLF, "true"), Arguments.of(LineEnding.LF, "true"),
Arguments.of(LineEnding.CR, "true"), Arguments.of(LineEnding.CRLF, "false"),
Arguments.of(LineEnding.LF, "false"), Arguments.of(LineEnding.CR, "false"));
}

@ParameterizedTest
@MethodSource("testParamsProvider")
void test(LineEnding currentTestedLineEnding, String multipleJsonObjectFileAllowed) throws IOException {
final JsonFormatter jsonFormatter = new JsonFormatter();
Assertions.assertFalse(jsonFormatter.isInitialized());
jsonFormatter.init(
Map.of("lineending", currentTestedLineEnding.getChars(), "multipleJsonObjectFileAllowed",
multipleJsonObjectFileAllowed),
new TestConfigurationSource(AbstractFormatterTest.TEST_OUTPUT_PRIMARY_DIR));
Assertions.assertTrue(jsonFormatter.isInitialized());
String result = jsonFormatter.doFormat(BEFORE_STRING, currentTestedLineEnding);
Assertions.assertEquals(AFTER_STRING.replaceAll(LineEnding.CRLF.getChars(), LineEnding.LF.getChars())
.replaceAll(LineEnding.LF.getChars(), currentTestedLineEnding.getChars()), result);
}

}
15 changes: 15 additions & 0 deletions src/test/resources/multiple-json/after.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name" : "Bob",
"age" : 28,
"prefer" : 1
}
{
"name" : "Tom",
"age" : 36,
"prefer" : 0
}
{
"name" : "V",
"age" : 45,
"prefer" : 1
}
3 changes: 3 additions & 0 deletions src/test/resources/multiple-json/before.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{"name" : "Bob", "age" : 28, "prefer":1}
{"name" : "Tom", "age" : 36, "prefer":0}
{"name" : "V", "age" : 45, "prefer":1}
5 changes: 5 additions & 0 deletions src/test/resources/normal-json/after.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name" : "Bob",
"age" : 28,
"prefer" : 1
}
1 change: 1 addition & 0 deletions src/test/resources/normal-json/before.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name" : "Bob", "age" : 28, "prefer":1}

0 comments on commit 7dda0a2

Please sign in to comment.