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