1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.codehaus.mojo.properties;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.io.OutputStream;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Properties;
25
26 import org.apache.commons.io.FileUtils;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.maven.plugin.AbstractMojo;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.project.MavenProject;
31 import org.codehaus.plexus.util.StringUtils;
32
33
34
35
36
37 public abstract class AbstractWritePropertiesMojo extends AbstractMojo {
38
39
40
41
42
43
44 MavenProject project;
45
46
47
48
49
50
51
52 File outputFile;
53
54
55
56
57
58
59
60
61 OutputStyle outputStyle;
62
63
64
65
66
67
68 String prefix;
69
70 protected void writeProperties(File file, Properties properties, OutputStyle outputStyle, String prefix) throws MojoExecutionException {
71 Properties prefixed = getPrefixedProperties(properties, prefix);
72 Properties formatted = getFormattedProperties(prefixed, outputStyle);
73 Properties sorted = getSortedProperties(formatted);
74 OutputStream out = null;
75 try {
76 out = FileUtils.openOutputStream(file);
77 sorted.store(out, "Created by the properties-maven-plugin");
78 } catch (IOException e) {
79 throw new MojoExecutionException("Error creating properties file", e);
80 } finally {
81 IOUtils.closeQuietly(out);
82 }
83 }
84
85 protected SortedProperties getSortedProperties(Properties properties) {
86 SortedProperties sp = new SortedProperties();
87 sp.putAll(properties);
88 return sp;
89 }
90
91 protected Properties getFormattedProperties(Properties properties, OutputStyle style) {
92 switch (style) {
93 case NORMAL:
94 return properties;
95 case ENVIRONMENT_VARIABLE:
96 return getEnvironmentVariableProperties(properties);
97 default:
98 throw new IllegalArgumentException(outputStyle + " is unknown");
99 }
100 }
101
102 protected Properties getPrefixedProperties(Properties properties, String prefix) {
103 if (StringUtils.isBlank(prefix)) {
104 return properties;
105 }
106 List<String> keys = new ArrayList<String>(properties.stringPropertyNames());
107 Collections.sort(keys);
108 Properties newProperties = new Properties();
109 for (String key : keys) {
110 String value = properties.getProperty(key);
111 String newKey = prefix + "." + key;
112 newProperties.setProperty(newKey, value);
113 }
114 return newProperties;
115 }
116
117 protected Properties getEnvironmentVariableProperties(Properties properties) {
118 List<String> keys = new ArrayList<String>(properties.stringPropertyNames());
119 Collections.sort(keys);
120 Properties newProperties = new Properties();
121 for (String key : keys) {
122 String value = properties.getProperty(key);
123 String newKey = key.toUpperCase().replace(".", "_");
124 newProperties.setProperty(newKey, value);
125 }
126 return newProperties;
127 }
128 }