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
32
33
34
35
36 public abstract class AbstractWritePropertiesMojo extends AbstractMojo {
37
38
39
40
41
42
43 MavenProject project;
44
45
46
47
48
49
50
51 File outputFile;
52
53
54
55
56
57
58
59
60 OutputStyle outputStyle;
61
62 protected void writeProperties(File file, Properties properties, OutputStyle outputStyle) throws MojoExecutionException {
63 Properties formatted = getProperties(properties, outputStyle);
64 Properties sorted = getSortedProperties(formatted);
65 OutputStream out = null;
66 try {
67 out = FileUtils.openOutputStream(file);
68 sorted.store(out, "Created by the properties-maven-plugin");
69 } catch (IOException e) {
70 throw new MojoExecutionException("Error creating properties file", e);
71 } finally {
72 IOUtils.closeQuietly(out);
73 }
74 }
75
76 protected SortedProperties getSortedProperties(Properties properties) {
77 SortedProperties sp = new SortedProperties();
78 sp.putAll(properties);
79 return sp;
80 }
81
82 protected Properties getProperties(Properties properties, OutputStyle style) {
83 switch (style) {
84 case NORMAL:
85 return properties;
86 case ENVIRONMENT_VARIABLE:
87 return getEnvironmentVariableProperties(properties);
88 default:
89 throw new IllegalArgumentException(outputStyle + " is unknown");
90 }
91 }
92
93 protected Properties getEnvironmentVariableProperties(Properties properties) {
94 List<String> keys = new ArrayList<String>(properties.stringPropertyNames());
95 Collections.sort(keys);
96 Properties newProperties = new Properties();
97 for (String key : keys) {
98 String value = properties.getProperty(key);
99 String newKey = key.toUpperCase().replace(".", "_");
100 newProperties.setProperty(newKey, value);
101 }
102 return newProperties;
103 }
104 }