1 package org.codehaus.mojo.jaxb2.shared.environment.locale;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.plugin.MojoExecutionException;
23 import org.apache.maven.plugin.logging.Log;
24 import org.codehaus.mojo.jaxb2.shared.Validate;
25 import org.codehaus.mojo.jaxb2.shared.environment.AbstractLogAwareFacet;
26
27 import java.util.Locale;
28 import java.util.StringTokenizer;
29
30
31
32
33
34
35
36 public class LocaleFacet extends AbstractLogAwareFacet {
37
38
39 private Locale originalLocale;
40 private Locale newLocale;
41
42
43
44
45
46
47
48 public LocaleFacet(final Log log, final Locale newLocale) {
49 super(log);
50
51
52 Validate.notNull(newLocale, "usedLocale");
53
54
55 this.originalLocale = Locale.getDefault();
56 this.newLocale = newLocale;
57 }
58
59
60
61
62
63 @Override
64 public void setup() {
65
66 if (log.isInfoEnabled()) {
67 log.info("Setting default locale to [" + newLocale + "]");
68 }
69
70 try {
71 Locale.setDefault(newLocale);
72 } catch (Exception e) {
73 log.error("Could not switch locale to ["
74 + newLocale + "]. Continuing with standard locale.", e);
75 }
76 }
77
78
79
80
81
82 @Override
83 public void restore() {
84
85 if (log.isInfoEnabled()) {
86 log.info("Restoring default locale to [" + originalLocale + "]");
87 }
88
89 try {
90 Locale.setDefault(originalLocale);
91 } catch (Exception e) {
92 log.error("Could not restore locale to [" + originalLocale + "]. Continuing with ["
93 + Locale.getDefault() + "]", e);
94 }
95 }
96
97
98
99
100
101
102
103
104
105
106 public static LocaleFacet createFor(final String localeString, final Log log) throws MojoExecutionException {
107
108
109 Validate.notNull(log, "log");
110 Validate.notEmpty(localeString, "localeString");
111
112 final StringTokenizer tok = new StringTokenizer(localeString, ",", false);
113 final int numTokens = tok.countTokens();
114 if (numTokens > 3 || numTokens == 0) {
115 throw new MojoExecutionException("A localeString must consist of up to 3 comma-separated parts on the "
116 + "form <language>[,<country>[,<variant>]]. Received incorrect value '" + localeString + "'");
117 }
118
119 Locale locale = null;
120 switch (numTokens) {
121 case 3:
122 locale = new Locale(tok.nextToken().trim(), tok.nextToken().trim(), tok.nextToken().trim());
123 break;
124
125 case 2:
126 locale = new Locale(tok.nextToken().trim(), tok.nextToken().trim());
127 break;
128
129 default:
130 locale = new Locale(tok.nextToken().trim());
131 break;
132 }
133
134
135 return new LocaleFacet(log, locale);
136 }
137 }