Skip to content

Commit

Permalink
Merge pull request #228 from hazendaz/master
Browse files Browse the repository at this point in the history
[enhance] Properly initialize all new formatters and use them consist…
  • Loading branch information
hazendaz committed Oct 22, 2017
2 parents 7dacfd5 + dca9104 commit 76c550b
Show file tree
Hide file tree
Showing 14 changed files with 144 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,12 @@ public class FormatterMojo extends AbstractMojo implements ConfigurationSource {
@Parameter(defaultValue = "src/config/jsoup/formatter/xml.properties", property = "configxmlfile", required = true)
private String configXmlFile;

/**
* File or classpath location of a properties file to use in json formatting.
*/
@Parameter(defaultValue = "src/config/gson/formatter/json.properties", property = "configjsonfile", required = true)
private String configJsonFile;

/**
* File or classpath location of a properties file to use in css formatting.
*/
Expand Down Expand Up @@ -633,19 +639,22 @@ private void createCodeFormatter() throws MojoExecutionException {
this.jsFormatter.init(jsFormattingOptions, this);
}
if (configHtmlFile != null) {
this.htmlFormatter.setFilename(configHtmlFile);
this.htmlFormatter.init(getOptionsFromPropertiesFile(configHtmlFile), this);
}
if (configXmlFile != null) {
this.xmlFormatter.setFilename(configXmlFile);
this.xmlFormatter.init(getOptionsFromPropertiesFile(configXmlFile), this);
}
if (configJsonFile != null) {
this.jsonFormatter.init(getOptionsFromPropertiesFile(configJsonFile), this);
}
if (configCssFile != null) {
this.cssFormatter.setFilename(configCssFile);
this.cssFormatter.init(getOptionsFromPropertiesFile(configCssFile), this);
}
// stop the process if not config files where found
if (javaFormattingOptions == null && jsFormattingOptions == null && configHtmlFile == null
&& configXmlFile == null && configCssFile == null) {
throw new MojoExecutionException(
"You must provide a Java, Javascript, HTML, XML or CSS configuration file.");
"You must provide a Java, Javascript, HTML, XML, JSON, or CSS configuration file.");
}
}

Expand Down Expand Up @@ -695,6 +704,34 @@ private Map<String, String> getOptionsFromConfigFile(String newConfigFile) throw
}
}

/**
* Read properties file and return the properties as {@link Map}.
*
* @return the options from properties file or null if not properties file found
* @throws MojoExecutionException the mojo execution exception
*/
private Map<String, String> getOptionsFromPropertiesFile(String newPropertiesFile) throws MojoExecutionException {

this.getLog().debug("Using search path at: " + this.basedir.getAbsolutePath());
this.resourceManager.addSearchPath(FileResourceLoader.ID, this.basedir.getAbsolutePath());

Properties properties = new Properties();
try {
properties.load(this.resourceManager.getResourceAsInputStream(newPropertiesFile));
} catch (ResourceNotFoundException e) {
getLog().debug("Property file [" + newPropertiesFile + "] cannot be found", e);
return new HashMap<>();
} catch (IOException e) {
throw new MojoExecutionException("Cannot read config file [" + newPropertiesFile + "]", e);
}

final Map<String, String> map = new HashMap<>();
for (final String name : properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
return map;
}

class ResultCollector {

int successCount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,64 +18,49 @@

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Document.OutputSettings;
import org.jsoup.nodes.Document.OutputSettings.Syntax;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.parser.Parser;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;

/**
* @author yoshiman
*
*/
public abstract class JsoupBasedFormatter extends AbstractCacheableFormatter implements Formatter {

private String filename;
private OutputSettings formatter;

@Override
public void init(Map<String, String> options, ConfigurationSource cfg) {
if (cfg != null) {
super.initCfg(cfg);
}
super.initCfg(cfg);

formatter = new OutputSettings();
formatter.charset(Charset.forName(options.getOrDefault("charset", StandardCharsets.UTF_8.name())));
formatter.escapeMode(EscapeMode.valueOf(options.getOrDefault("escapeMode", EscapeMode.xhtml.name())));
formatter.indentAmount(Integer.parseInt(options.getOrDefault("indentAmount", "4")));
formatter.outline(Boolean.parseBoolean(options.getOrDefault("outlineMode", Boolean.TRUE.toString())));
formatter.prettyPrint(Boolean.parseBoolean(options.getOrDefault("pretty", Boolean.TRUE.toString())));
formatter.syntax(Syntax.valueOf(options.getOrDefault("syntax", Syntax.html.name())));
}

public String doFormat(String code, Syntax syntax) {
public String doFormat(String code, LineEnding ending) {
Document document;
switch (syntax) {
switch (formatter.syntax()) {
case html:
document = Jsoup.parse(code, "", Parser.htmlParser());
break;
case xml:
document = Jsoup.parse(code, "", Parser.xmlParser());
break;
default:
throw new IllegalArgumentException(syntax + " is not allowed as syntax");
}
try {
Properties properties = new Properties();
properties.load(Files.newInputStream(Paths.get(filename)));
Charset charset = Charset.forName(properties.getProperty("charset", StandardCharsets.UTF_8.name()));
EscapeMode escapeMode = EscapeMode.valueOf(properties.getProperty("escapeMode", EscapeMode.xhtml.name()));
int indentAmount = Integer.parseInt(properties.getProperty("indentAmount", "1"));
boolean outlineMode = Boolean.parseBoolean(properties.getProperty("outlineMode", Boolean.toString(true)));
boolean pretty = Boolean.parseBoolean(properties.getProperty("pretty", Boolean.toString(true)));
document.outputSettings() //
.charset(charset) //
.escapeMode(escapeMode) //
.indentAmount(indentAmount) //
.outline(outlineMode) //
.prettyPrint(pretty) //
.syntax(syntax);

} catch (IOException e) {
this.log.error(e);
throw new IllegalArgumentException(formatter.syntax() + " is not allowed as syntax");
}
document.outputSettings(formatter);

String formattedCode = document.outerHtml();
if (code.equals(formattedCode)) {
Expand All @@ -86,15 +71,7 @@ public String doFormat(String code, Syntax syntax) {

@Override
public boolean isInitialized() {
return filename != null;
}

public String getFilename() {
return filename;
}

public void setFilename(String filename) {
this.filename = filename;
return formatter != null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,40 +28,23 @@

import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;

/**
* @author yoshiman
*
*/
public class CssFormatter extends AbstractCacheableFormatter implements Formatter {
private String filename;
private CSSFormat format;

@Override
public boolean isInitialized() {
return filename != null && format != null;
}
private CSSFormat formatter;

@Override
public void init(Map<String, String> options, ConfigurationSource cfg) {
if (cfg != null) {
super.initCfg(cfg);
}
Properties properties = new Properties();
try {
properties.load(Files.newInputStream(Paths.get(filename)));
} catch (IOException e) {
this.log.error("error while reading properties file", e);
}
int indent = Integer.parseInt(properties.getProperty("indent", "2"));
boolean rgbAsHex = Boolean.parseBoolean(properties.getProperty("rgbAsHex", Boolean.toString(true)));
format = new CSSFormat();
format.setPropertiesInSeparateLines(indent);
format.setRgbAsHex(rgbAsHex);
super.initCfg(cfg);

int indent = Integer.parseInt(options.getOrDefault("indent", "4"));
boolean rgbAsHex = Boolean.parseBoolean(options.getOrDefault("rgbAsHex", Boolean.TRUE.toString()));
formatter = new CSSFormat().setPropertiesInSeparateLines(indent).setRgbAsHex(rgbAsHex);
}

@Override
Expand All @@ -70,20 +53,17 @@ protected String doFormat(String code, LineEnding ending) throws IOException {
InputSource source = new InputSource(new StringReader(code));
CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
CSSStyleSheetImpl sheet = (CSSStyleSheetImpl) parser.parseStyleSheet(source, null, null);
String formattedCode = sheet.getCssText(format);
String formattedCode = sheet.getCssText(formatter);

if (code.equals(formattedCode)) {
return null;
}
return formattedCode;
}

public String getFilename() {
return filename;
}

public void setFilename(String filename) {
this.filename = filename;
@Override
public boolean isInitialized() {
return formatter != null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
import net.revelc.code.formatter.Formatter;
import net.revelc.code.formatter.JsoupBasedFormatter;
import net.revelc.code.formatter.LineEnding;
import org.jsoup.nodes.Document.OutputSettings.Syntax;

import java.io.UnsupportedEncodingException;

/**
* @author yoshiman
Expand All @@ -30,8 +27,8 @@
public class HTMLFormatter extends JsoupBasedFormatter implements Formatter {

@Override
public String doFormat(String code, LineEnding ending) throws UnsupportedEncodingException {
return super.doFormat(code, Syntax.html);
public String doFormat(String code, LineEnding ending) {
return super.doFormat(code, ending);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,30 +32,37 @@
*
*/
public class JsonFormatter extends AbstractCacheableFormatter implements Formatter {
private Gson gson;
private JsonParser jsonParser;

@Override
public boolean isInitialized() {
return gson != null && jsonParser != null;
}
private Gson formatter;

private JsonParser jsonParser;

@Override
public void init(Map<String, String> options, ConfigurationSource cfg) {
if (cfg != null) {
super.initCfg(cfg);
super.initCfg(cfg);

boolean printPrinting = Boolean.parseBoolean(options.getOrDefault("prettyPrinting", Boolean.TRUE.toString()));

if (printPrinting) {
formatter = new GsonBuilder().setPrettyPrinting().create();
} else {
formatter = new GsonBuilder().create();
}
gson = new GsonBuilder().setPrettyPrinting().create();
jsonParser = new JsonParser();
}

@Override
protected String doFormat(String code, LineEnding ending) throws IOException {
String formattedCode = gson.toJson(jsonParser.parse(code));
String formattedCode = formatter.toJson(jsonParser.parse(code));
if (code.equals(formattedCode)) {
return null;
}
return formattedCode;
}

@Override
public boolean isInitialized() {
return formatter != null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
import net.revelc.code.formatter.Formatter;
import net.revelc.code.formatter.JsoupBasedFormatter;
import net.revelc.code.formatter.LineEnding;
import org.jsoup.nodes.Document.OutputSettings.Syntax;

import java.io.UnsupportedEncodingException;

/**
* @author yoshiman
Expand All @@ -30,8 +27,8 @@
public class XMLFormatter extends JsoupBasedFormatter implements Formatter {

@Override
public String doFormat(String code, LineEnding ending) throws UnsupportedEncodingException {
return super.doFormat(code, Syntax.xml);
public String doFormat(String code, LineEnding ending) {
return super.doFormat(code, ending);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.junit.Test;

import java.io.File;
import java.util.HashMap;

/**
* @author yoshiman
Expand All @@ -29,10 +30,14 @@ public class CssFormatterTest extends AbstractFormatterTest {

@Test
public void testDoFormatFile() throws Exception {
CssFormatter cssFormatter = new CssFormatter();
cssFormatter.setFilename("src/test/resources/css.properties");
doTestFormat(cssFormatter, "someFile.css",
"2e3a00647508e528051f607b29e7e2dc5dc7ba12c1b75b746f490676f51ca27c1c0f26c233b94804d7656434d65138249530bf0969cff4a7e9c2baef0f3c9294");
// FIXME Handle linux vs windows since this formatter does not accept line endings
if (System.lineSeparator().equals("\n")) {
doTestFormat(new CssFormatter(), "someFile.css",
"590c14fa99d8296d7e1c6d4124de96e8fc436ee3f44704445a966befd37488e336b14e60fdb7d26181f6fc0c05848c1cc32701b34f98846f3122d4d057de9605");
} else {
doTestFormat(new CssFormatter(), "someFile.css",
"c3bdea2e2755c1e773459024ca5114282da1ebf0c46d975d90d2567f39ac16c7c6f227745a80f4912d55049a177699ffe619df444ebb3cffeb8574e41babaf0b");
}
}

@Test
Expand All @@ -41,8 +46,7 @@ public void testIsIntialized() throws Exception {
Assert.assertFalse(cssFormatter.isInitialized());
final File targetDir = new File("target/testoutput");
targetDir.mkdirs();
cssFormatter.setFilename("src/test/resources/css.properties");
cssFormatter.init(null, null);
cssFormatter.init(new HashMap<String, String>(), new AbstractFormatterTest.TestConfigurationSource(targetDir));

Assert.assertTrue(cssFormatter.isInitialized());
}
Expand Down
Loading

0 comments on commit 76c550b

Please sign in to comment.