EMMA Coverage Report (generated Wed Jun 22 19:47:49 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)83%  (318/381)83%  (47.9/58)

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)90%  (285/315)88%  (44/50)
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)
writeFunctionFromResource (String, OsFamily): String 100% (1/1)71%  (20/28)33%  (1/3)
writeUnsetVariables (List, OsFamily): String 100% (1/1)82%  (55/67)89%  (8/9)
<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         return CharStreams.toString(Resources.newReaderSupplier(Resources.getResource(Utils.class, String
137                  .format("/functions/%s.%s", function, ShellToken.SH.to(family))), Charsets.UTF_8));
138      } catch (IOException e) {
139         throw new FunctionNotFoundException(function, family, e);
140      }
141   }
142 
143   public static class FunctionNotFoundException extends RuntimeException {
144      /** The serialVersionUID */
145      private static final long serialVersionUID = 1L;
146 
147      public FunctionNotFoundException(String functionName, OsFamily family) {
148         super("function: " + functionName + " not found for famiy: " + family);
149      }
150 
151      public FunctionNotFoundException(String functionName, OsFamily family, Throwable cause) {
152         super("function: " + functionName + " not found for famiy: " + family, cause);
153      }
154   }
155 
156   public static String writeFunction(String function, String source) {
157      return String.format("{fncl}%s{fncr}%s{fnce}", function, source.replaceAll("^", "   "));
158   }
159 
160   public static final Map<OsFamily, String> OS_TO_POSITIONAL_VAR_PATTERN = ImmutableMap.of(
161            OsFamily.UNIX, "set {key}=$1\nshift\n", OsFamily.WINDOWS, "set {key}=%1\r\nshift\r\n");
162 
163   public static final Map<OsFamily, String> OS_TO_LOCAL_VAR_PATTERN = ImmutableMap.of(
164            OsFamily.UNIX, "set {key}=\"{value}\"\n", OsFamily.WINDOWS, "set {key}={value}\r\n");
165 
166   /**
167    * Writes an initialization statement for use inside a script or a function.
168    * 
169    * @param positionalVariablesInLowerCamelCase
170    *           - transfer the value of args into these statements. Note that there is no check to
171    *           ensure that all source args are indeed present.
172    */
173   public static String writePositionalVars(List<String> positionalVariablesInLowerCamelCase,
174            OsFamily family) {
175      StringBuilder initializers = new StringBuilder();
176      for (String variableInLowerCamelCase : positionalVariablesInLowerCamelCase) {
177         String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE,
178                  variableInLowerCamelCase);
179         initializers.append(replaceTokens(OS_TO_POSITIONAL_VAR_PATTERN.get(family), ImmutableMap
180                  .of("key", key)));
181      }
182      return initializers.toString();
183   }
184 
185   /**
186    * Ensures that variables come from a known source instead of bleeding in from a profile
187    * 
188    * @param variablesInLowerCamelCase
189    *           - System variables to unset
190    */
191   public static String writeUnsetVariables(List<String> variablesInLowerCamelCase, OsFamily family) {
192      switch (family) {
193         case UNIX:
194            return String.format("unset %s\n", Joiner.on(' ').join(
195                     Iterables.transform(variablesInLowerCamelCase,
196                              FUNCTION_LOWER_CAMEL_TO_UPPER_UNDERSCORE)));
197         case WINDOWS:
198            StringBuilder initializers = new StringBuilder();
199            for (String variableInLowerCamelCase : variablesInLowerCamelCase) {
200               String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE,
201                        variableInLowerCamelCase);
202               initializers.append(replaceTokens(OS_TO_LOCAL_VAR_PATTERN.get(family), ImmutableMap
203                        .of("key", key, "value", "")));
204            }
205            return initializers.toString();
206         default:
207            throw new UnsupportedOperationException("unsupported os: " + family);
208      }
209 
210   }
211 
212   public static final Map<OsFamily, String> OS_TO_ZERO_PATH = ImmutableMap.of(OsFamily.WINDOWS,
213            "set PATH=c:\\windows\\;C:\\windows\\system32;c:\\windows\\system32\\wbem\r\n",
214            OsFamily.UNIX, "export PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n");
215 
216   /**
217    * @return line used to zero out the path of the script such that basic commands such as unix ps
218    *         will work.
219    */
220   public static String writeZeroPath(OsFamily family) {
221      return OS_TO_ZERO_PATH.get(family);
222   }
223 
224   public static String writeComment(String comment, OsFamily family) {
225      return String.format("%s%s%s", ShellToken.REM.to(family), comment, ShellToken.LF.to(family));
226   }
227}

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