EMMA Coverage Report (generated Fri Aug 26 14:14:05 EDT 2011)
[all classes][org.jclouds.scriptbuilder.util]

COVERAGE SUMMARY FOR SOURCE FILE [Utils.java]

nameclass, %method, %block, %line, %
Utils.java80%  (4/5)79%  (15/19)84%  (336/399)83%  (49.9/60)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class Utils$FunctionNotFoundException0%   (0/1)0%   (0/2)0%   (0/31)0%   (0/4)
Utils$FunctionNotFoundException (String, OsFamily): void 0%   (0/1)0%   (0/15)0%   (0/2)
Utils$FunctionNotFoundException (String, OsFamily, Throwable): void 0%   (0/1)0%   (0/16)0%   (0/2)
     
class Utils$1100% (1/1)100% (1/1)89%  (17/19)89%  (0.9/1)
<static initializer> 100% (1/1)89%  (17/19)89%  (0.9/1)
     
class Utils100% (1/1)83%  (10/12)91%  (303/333)88%  (46/52)
Utils (): void 0%   (0/1)0%   (0/3)0%   (0/2)
writeFunction (String, String, OsFamily): String 0%   (0/1)0%   (0/7)0%   (0/1)
writeUnsetVariables (List, OsFamily): String 100% (1/1)82%  (55/67)89%  (8/9)
writeFunctionFromResource (String, OsFamily): String 100% (1/1)83%  (38/46)60%  (3/5)
<static initializer> 100% (1/1)100% (30/30)100% (6/6)
replaceTokens (String, Map): String 100% (1/1)100% (56/56)100% (13/13)
writeComment (String, OsFamily): String 100% (1/1)100% (21/21)100% (1/1)
writeFunction (String, String): String 100% (1/1)100% (16/16)100% (1/1)
writePositionalVars (List, OsFamily): String 100% (1/1)100% (34/34)100% (6/6)
writeVariableExporters (Map): String 100% (1/1)100% (42/42)100% (6/6)
writeVariableExporters (Map, OsFamily): String 100% (1/1)100% (6/6)100% (1/1)
writeZeroPath (OsFamily): String 100% (1/1)100% (5/5)100% (1/1)
     
class Utils$LowerCamelToUpperUnderscore100% (1/1)100% (2/2)100% (8/8)100% (2/2)
Utils$LowerCamelToUpperUnderscore (): void 100% (1/1)100% (3/3)100% (1/1)
apply (String): String 100% (1/1)100% (5/5)100% (1/1)
     
class Utils$UpperUnderscoreToLowerCamel100% (1/1)100% (2/2)100% (8/8)100% (2/2)
Utils$UpperUnderscoreToLowerCamel (): void 100% (1/1)100% (3/3)100% (1/1)
apply (String): String 100% (1/1)100% (5/5)100% (1/1)

1/**
2 *
3 * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
4 *
5 * ====================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ====================================================================
18 */
19package org.jclouds.scriptbuilder.util;
20 
21import java.io.IOException;
22import java.util.List;
23import java.util.Map;
24import java.util.Map.Entry;
25import java.util.regex.Matcher;
26import java.util.regex.Pattern;
27 
28import org.jclouds.scriptbuilder.domain.OsFamily;
29import org.jclouds.scriptbuilder.domain.ShellToken;
30 
31import com.google.common.base.CaseFormat;
32import com.google.common.base.Charsets;
33import com.google.common.base.Function;
34import com.google.common.base.Joiner;
35import com.google.common.collect.ImmutableMap;
36import com.google.common.collect.Iterables;
37import com.google.common.io.CharStreams;
38import com.google.common.io.Resources;
39 
40/**
41 * Utilities used to build init scripts.
42 * 
43 * @author Adrian Cole
44 */
45public class Utils {
46 
47   public static final LowerCamelToUpperUnderscore FUNCTION_LOWER_CAMEL_TO_UPPER_UNDERSCORE = new LowerCamelToUpperUnderscore();
48 
49   public static final class LowerCamelToUpperUnderscore implements Function<String, String> {
50      @Override
51      public String apply(String from) {
52         return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, from);
53      }
54   }
55 
56   public static final UpperUnderscoreToLowerCamel FUNCTION_UPPER_UNDERSCORE_TO_LOWER_CAMEL = new UpperUnderscoreToLowerCamel();
57 
58   public static final class UpperUnderscoreToLowerCamel implements Function<String, String> {
59      @Override
60      public String apply(String from) {
61         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, from);
62      }
63   }
64 
65   private static final Pattern pattern = Pattern.compile("\\{(.+?)\\}");
66 
67   /**
68    * replaces tokens that are expressed as <code>{token}</code>
69    * 
70    * <p/>
71    * ex. if input is "hello {where}"<br/>
72    * and replacements is "where" -> "world" <br/>
73    * then replaceTokens returns "hello world"
74    * 
75    * @param input
76    *           source to replace
77    * @param replacements
78    *           token/value pairs
79    */
80   public static String replaceTokens(String input, Map<String, String> replacements) {
81      Matcher matcher = pattern.matcher(input);
82      StringBuilder builder = new StringBuilder();
83      int i = 0;
84      while (matcher.find()) {
85         String replacement = replacements.get(matcher.group(1));
86         builder.append(input.substring(i, matcher.start()));
87         if (replacement == null)
88            builder.append(matcher.group(0));
89         else
90            builder.append(replacement);
91         i = matcher.end();
92      }
93      builder.append(input.substring(i, input.length()));
94      return builder.toString();
95   }
96 
97   /**
98    * converts a map into variable exports relevant to the specified platform.
99    * <p/>
100    * ex. if variablesInLowerCamelCase is "mavenOpts" -> "-Xms64m -Xmx256m" <br/>
101    * and family is UNIX<br/>
102    * then writeVariableExporters returns literally {@code export MAVEN_OPTS="-Xms64m -Xmx256m"\n}
103    * 
104    * @param variablesInLowerCamelCase
105    *           lower camel keys to values
106    * @param family
107    *           operating system for formatting
108    */
109   public static String writeVariableExporters(Map<String, String> variablesInLowerCamelCase,
110            OsFamily family) {
111      return replaceTokens(writeVariableExporters(variablesInLowerCamelCase), ShellToken
112               .tokenValueMap(family));
113   }
114 
115   /**
116    * converts a map into variable exporters in shell intermediate language.
117    * 
118    * @param variablesInLowerCamelCase
119    *           lower camel keys to values
120    */
121   public static String writeVariableExporters(Map<String, String> variablesInLowerCamelCase) {
122      StringBuilder initializers = new StringBuilder();
123      for (Entry<String, String> entry : variablesInLowerCamelCase.entrySet()) {
124         String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, entry.getKey());
125         initializers.append(String.format("{export} %s={vq}%s{vq}{lf}", key, entry.getValue()));
126      }
127      return initializers.toString();
128   }
129 
130   public static String writeFunction(String function, String source, OsFamily family) {
131      return replaceTokens(writeFunction(function, source), ShellToken.tokenValueMap(family));
132   }
133 
134   public static String writeFunctionFromResource(String function, OsFamily family) {
135      try {
136         String toReturn = CharStreams.toString(Resources.newReaderSupplier(Resources.getResource(Utils.class, String
137                  .format("/functions/%s.%s", function, ShellToken.SH.to(family))), Charsets.UTF_8));
138         String lf = ShellToken.LF.to(family);
139         return toReturn.endsWith(lf) ? toReturn : new StringBuilder(toReturn).append(lf).toString();
140      } catch (IOException e) {
141         throw new FunctionNotFoundException(function, family, e);
142      }
143   }
144 
145   public static class FunctionNotFoundException extends RuntimeException {
146      /** The serialVersionUID */
147      private static final long serialVersionUID = 1L;
148 
149      public FunctionNotFoundException(String functionName, OsFamily family) {
150         super("function: " + functionName + " not found for famiy: " + family);
151      }
152 
153      public FunctionNotFoundException(String functionName, OsFamily family, Throwable cause) {
154         super("function: " + functionName + " not found for famiy: " + family, cause);
155      }
156   }
157 
158   public static String writeFunction(String function, String source) {
159      return String.format("{fncl}%s{fncr}%s{fnce}", function, source.replaceAll("^", "   "));
160   }
161 
162   public static final Map<OsFamily, String> OS_TO_POSITIONAL_VAR_PATTERN = ImmutableMap.of(
163            OsFamily.UNIX, "set {key}=$1\nshift\n", OsFamily.WINDOWS, "set {key}=%1\r\nshift\r\n");
164 
165   public static final Map<OsFamily, String> OS_TO_LOCAL_VAR_PATTERN = ImmutableMap.of(
166            OsFamily.UNIX, "set {key}=\"{value}\"\n", OsFamily.WINDOWS, "set {key}={value}\r\n");
167 
168   /**
169    * Writes an initialization statement for use inside a script or a function.
170    * 
171    * @param positionalVariablesInLowerCamelCase
172    *           - transfer the value of args into these statements. Note that there is no check to
173    *           ensure that all source args are indeed present.
174    */
175   public static String writePositionalVars(List<String> positionalVariablesInLowerCamelCase,
176            OsFamily family) {
177      StringBuilder initializers = new StringBuilder();
178      for (String variableInLowerCamelCase : positionalVariablesInLowerCamelCase) {
179         String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE,
180                  variableInLowerCamelCase);
181         initializers.append(replaceTokens(OS_TO_POSITIONAL_VAR_PATTERN.get(family), ImmutableMap
182                  .of("key", key)));
183      }
184      return initializers.toString();
185   }
186 
187   /**
188    * Ensures that variables come from a known source instead of bleeding in from a profile
189    * 
190    * @param variablesInLowerCamelCase
191    *           - System variables to unset
192    */
193   public static String writeUnsetVariables(List<String> variablesInLowerCamelCase, OsFamily family) {
194      switch (family) {
195         case UNIX:
196            return String.format("unset %s\n", Joiner.on(' ').join(
197                     Iterables.transform(variablesInLowerCamelCase,
198                              FUNCTION_LOWER_CAMEL_TO_UPPER_UNDERSCORE)));
199         case WINDOWS:
200            StringBuilder initializers = new StringBuilder();
201            for (String variableInLowerCamelCase : variablesInLowerCamelCase) {
202               String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE,
203                        variableInLowerCamelCase);
204               initializers.append(replaceTokens(OS_TO_LOCAL_VAR_PATTERN.get(family), ImmutableMap
205                        .of("key", key, "value", "")));
206            }
207            return initializers.toString();
208         default:
209            throw new UnsupportedOperationException("unsupported os: " + family);
210      }
211 
212   }
213 
214   public static final Map<OsFamily, String> OS_TO_ZERO_PATH = ImmutableMap.of(OsFamily.WINDOWS,
215            "set PATH=c:\\windows\\;C:\\windows\\system32;c:\\windows\\system32\\wbem\r\n",
216            OsFamily.UNIX, "export PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n");
217 
218   /**
219    * @return line used to zero out the path of the script such that basic commands such as unix ps
220    *         will work.
221    */
222   public static String writeZeroPath(OsFamily family) {
223      return OS_TO_ZERO_PATH.get(family);
224   }
225 
226   public static String writeComment(String comment, OsFamily family) {
227      return String.format("%s%s%s", ShellToken.REM.to(family), comment, ShellToken.LF.to(family));
228   }
229}

[all classes][org.jclouds.scriptbuilder.util]
EMMA 2.0.5312 (C) Vladimir Roubtsov