Skip to content

Commit

Permalink
add support yaml file
Browse files Browse the repository at this point in the history
  • Loading branch information
ext-zshi committed Aug 8, 2023
1 parent 5105ebc commit 5da2453
Show file tree
Hide file tree
Showing 3 changed files with 154 additions and 11 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@
<artifactId>maven-plugin-annotations</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.1</version>
</dependency>
</dependencies>

<profiles>
Expand Down
93 changes: 82 additions & 11 deletions src/main/java/org/codehaus/mojo/properties/ReadPropertiesMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,6 @@
* under the License.
*/

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
Expand All @@ -37,6 +27,12 @@
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
* The read-project-properties goal reads property files and URLs and stores the properties as project properties. It
Expand Down Expand Up @@ -169,7 +165,10 @@ private void loadUrls() throws MojoExecutionException {

private void load(Resource resource) throws MojoExecutionException {
if (resource.canBeOpened()) {
loadProperties(resource);
if (resource.isYaml())
loadYaml(resource);
else
loadProperties(resource);
} else {
missing(resource);
}
Expand Down Expand Up @@ -201,6 +200,64 @@ private void loadProperties(Resource resource) throws MojoExecutionException {
}
}

private void loadYaml(Resource resource) throws MojoExecutionException {
try {
getLog().debug("Loading properties from " + resource);

try (InputStream stream = resource.getInputStream()) {
String effectivePrefix = "";
if (keyPrefix != null) {
effectivePrefix = keyPrefix;
}

Properties projectProperties = project.getProperties();
Map yamlMap = flattenYamlMap(effectivePrefix, new Yaml().load(stream));

if(override){
projectProperties.putAll(yamlMap);
}else{
for (Object o : yamlMap.entrySet()) {
Map.Entry entry = (Map.Entry) o;
if(!projectProperties.containsKey(entry.getKey())){
projectProperties.put(entry.getKey(), entry.getValue());
}
}
}
}
} catch (IOException e) {
throw new MojoExecutionException("Error reading Yaml from " + resource, e);
}
}

private Map<String, Object> flattenYamlMap(String key, Map map) {
if (!key.endsWith(".") && !"".equals(key.trim())) {
key = key.trim() + ".";
}
Map<String, Object> result = new HashMap<String, Object>();
for (Object o : map.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object value = entry.getValue();
if (value instanceof Map) {
result.putAll( flattenYamlMap(String.format("%s%s", key, entry.getKey()),
(Map) value));
} else if (value instanceof Collection) {
Object[] values = ((Collection) value).toArray();
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof Map) {
result.putAll( flattenYamlMap(
String.format("%s%s[%d]", key, entry.getKey(), i), (Map) values[i]));
} else {
result.put(String.format("%s%s[%d]", key, entry.getKey(), i), String.valueOf(values[i]));
}

}
} else {
result.put(key + "" + entry.getKey(), String.valueOf(value));
}
}
return result;
}

private void missing(Resource resource) throws MojoExecutionException {
if (quiet) {
getLog().info("Quiet processing - ignoring properties cannot be loaded from " + resource);
Expand Down Expand Up @@ -308,6 +365,8 @@ private abstract static class Resource {

protected abstract InputStream openStream() throws IOException;

public abstract boolean isYaml();

public InputStream getInputStream() throws IOException {
if (stream == null) {
stream = openStream();
Expand All @@ -327,6 +386,12 @@ public boolean canBeOpened() {
return file.exists();
}

public boolean isYaml() {
return this.file.getName().matches("(?i).*\\.yaml$")
|| this.file.getName().matches("(?i).*\\.yml$");

}

protected InputStream openStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
Expand Down Expand Up @@ -379,6 +444,12 @@ public boolean canBeOpened() {
return true;
}

public boolean isYaml() {
return this.url.toString().matches("(?i).*\\.yaml$")
|| this.url.toString().matches("(?i).*\\.yml$");

}

protected InputStream openStream() throws IOException {
return new BufferedInputStream(url.openStream());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
Expand Down Expand Up @@ -264,6 +265,36 @@ public void testDefaultValueForUnresolvedPropertyWithDisabledFlag()
assertEquals("${unknown: }", value13);
}

@Test
public void readYamlWithKeyprefix() throws Exception {
String keyPrefix = "testkey-prefix.";

try (FileReader fs1 = new FileReader(geYamlFileForTesting(keyPrefix));
FileReader fs2 = new FileReader(geYamlFileForTesting(""))) {
// Object testYamlWithoutPrefix = new Yaml().load(fs2);

// do the work
readPropertiesMojo.setKeyPrefix(keyPrefix);
readPropertiesMojo.setFiles(new File[] { geYamlFileForTesting("") });
readPropertiesMojo.execute();

// load properties directly and add prefix for comparison later
// Properties testPropertiesPrefix = new Properties();
// testPropertiesPrefix.load(fs1);

// check results
Properties projectProperties = projectStub.getProperties();
assertNotNull(projectProperties);
// it should not be empty
assertNotEquals(0, projectProperties.size());

assertEquals("31", projectProperties.get(keyPrefix + "age"));
assertEquals("123456789", projectProperties.get(keyPrefix + "contactDetails[0].number"));
assertEquals("12312341235", projectProperties.get(keyPrefix + "phones[1]"));
assertEquals("Xyz, DEF Street", projectProperties.get(keyPrefix + "homeAddress.line"));
}
}

private File getPropertyFileForTesting() throws IOException {
return getPropertyFileForTesting(null);
}
Expand All @@ -286,4 +317,39 @@ private File getPropertyFileForTesting(String keyPrefix) throws IOException {
}
return f;
}

private File geYamlFileForTesting(String keyPrefix) throws IOException {
File f = File.createTempFile("yaml-test", ".yaml");
f.deleteOnExit();
FileWriter writer = new FileWriter(f);
String prefix = keyPrefix;
if (prefix == null) {
prefix = "";
}
try {
Yaml yaml = new Yaml();
Object data = yaml.load(
"firstName: \"John\"\n" +
"lastName: \"Doe\"\n" +
"age: 31\n" +
"phones:\n" +
" - 12312341234\n" +
" - 12312341235\n" +
"contactDetails:\n" +
" - type: \"mobile\"\n" +
" number: 123456789\n" +
" - type: \"landline\"\n" +
" number: 456786868\n" +
"homeAddress:\n" +
" line: \"Xyz, DEF Street\"\n" +
" city: \"City Y\"\n"

);
yaml.dump(data, writer);
writer.flush();
} finally {
writer.close();
}
return f;
}
}

0 comments on commit 5da2453

Please sign in to comment.