List of usage examples for com.google.common.base CaseFormat UPPER_UNDERSCORE
CaseFormat UPPER_UNDERSCORE
To view the source code for com.google.common.base CaseFormat UPPER_UNDERSCORE.
Click Source Link
From source file:com.google.template.soy.shared.internal.AbstractGenerateSoyEscapingDirectiveCode.java
/** * Appends Code to the given buffer.//from www . j a v a2s. c o m * * <p> * The output Code contains symbol definitions in the appropriate scope (the soy namespace in * JavaScript or a module in Python). * <pre> * ...ESCAPES_FOR_ESCAPE_HTML_ = { ... } // Maps of characters to escaped versions * ...MATCHER_FOR_ESCAPE_HTML_ = <regex> // A single character matching RegExp * ...REPLACER_FOR_ESCAPE_HTML_ = <function> // Usable with replace functions * ...FILTER_FOR_ESCAPE_HTML_ = <regex> // Optional regular expression that vets values. * // A function that uses the above definitions. * ...escapeHtmlHelper = <function> * </pre> * * <p>There is not necessarily a one-to-one relationship between any of the symbols above * and escape directives except for the {@code ...escape...Helper} function. * * @param availableIdentifiers Determines whether a qualified identifier, like * {@code goog.foo.Bar}, is available. * @param outputCode Receives output code. */ @VisibleForTesting void generateCode(Predicate<String> availableIdentifiers, StringBuilder outputCode) { outputCode.append(GENERATED_CODE_START_MARKER).append('\n'); // Before entering the real logic, generate any needed prefix. generatePrefix(outputCode); // First we collect all the side tables. // Like { '\n': '\\n', ... } that map characters to escape. List<Map<Character, String>> escapeMaps = Lists.newArrayList(); // Mangled directive names corresponding to escapeMaps used to generate <namespace>..._ names. List<String> escapeMapNames = Lists.newArrayList(); // Like /[\n\r'"]/g or r'[\n\r\'"]'that match all the characters that need escaping. List<String> matchers = Lists.newArrayList(); // Mangled directive names corresponding to matchers. List<String> matcherNames = Lists.newArrayList(); // RegExps that vet input values. List<String> filters = Lists.newArrayList(); // Mangled directive names corresponding to filters. List<String> filterNames = Lists.newArrayList(); // Bundles of directiveNames and indices into escapeMaps, matchers, etc. List<DirectiveDigest> digests = Lists.newArrayList(); escaperLoop: for (EscapingConventions.CrossLanguageStringXform escaper : EscapingConventions .getAllEscapers()) { // "|escapeHtml" -> "escapeHtml" String escapeDirectiveIdent = escaper.getDirectiveName().substring(1); // "escapeHtml" -> "ESCAPE_HTML" String escapeDirectiveUIdent = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, escapeDirectiveIdent); // If there is an existing function, use it. for (String existingFunction : escaper.getLangFunctionNames(getLanguage())) { if (availableIdentifiers.apply(existingFunction)) { useExistingLibraryFunction(outputCode, escapeDirectiveIdent, existingFunction); continue escaperLoop; } } // Else generate definitions for side tables. int escapesVar = -1; int matcherVar = -1; if (!escaper.getEscapes().isEmpty()) { Map<Character, String> escapeMap = Maps.newTreeMap(); StringBuilder matcherRegexBuf = new StringBuilder(getRegexStart() + "["); int lastCodeUnit = Integer.MIN_VALUE; int rangeStart = Integer.MIN_VALUE; for (EscapingConventions.Escape esc : escaper.getEscapes()) { char ch = esc.getPlainText(); if (ch == lastCodeUnit) { throw new IllegalStateException( "Ambiguous escape " + esc.getEscaped() + " for " + escapeDirectiveIdent); } escapeMap.put(ch, esc.getEscaped()); if (ch != lastCodeUnit + 1) { if (rangeStart != Integer.MIN_VALUE) { escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); } rangeStart = ch; } lastCodeUnit = ch; } if (rangeStart < 0) { throw new IllegalStateException(); } escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); matcherRegexBuf.append("]").append(getRegexEnd()); // See if we can reuse an existing map. int numEscapeMaps = escapeMaps.size(); for (int i = 0; i < numEscapeMaps; ++i) { if (mapsHaveCompatibleOverlap(escapeMaps.get(i), escapeMap)) { escapesVar = i; break; } } if (escapesVar == -1) { escapesVar = numEscapeMaps; escapeMaps.add(escapeMap); escapeMapNames.add(escapeDirectiveUIdent); } else { escapeMaps.get(escapesVar).putAll(escapeMap); // ESCAPE_JS -> ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX escapeMapNames.set(escapesVar, escapeMapNames.get(escapesVar) + "__AND__" + escapeDirectiveUIdent); } String matcherRegex = matcherRegexBuf.toString(); matcherVar = matchers.indexOf(matcherRegex); if (matcherVar < 0) { matcherVar = matchers.size(); matchers.add(matcherRegex); matcherNames.add(escapeDirectiveUIdent); } else { matcherNames.set(matcherVar, matcherNames.get(matcherVar) + "__AND__" + escapeDirectiveUIdent); } } // Find a suitable filter or add one to filters. int filterVar = -1; Pattern filterPatternJava = escaper.getValueFilter(); if (filterPatternJava != null) { // This is an approximate translation from Java patterns to JavaScript patterns. String filterPattern = convertFromJavaRegex(filterPatternJava); filterVar = filters.indexOf(filterPattern); if (filterVar == -1) { filterVar = filters.size(); filters.add(filterPattern); filterNames.add(escapeDirectiveUIdent); } else { filterNames.set(filterVar, filterNames.get(filterVar) + "__AND__" + escapeDirectiveUIdent); } } digests.add(new DirectiveDigest(escapeDirectiveIdent, escapesVar, matcherVar, filterVar, escaper.getNonAsciiPrefix(), escaper.getInnocuousOutput())); } // TODO(user): Maybe use java Soy templates to generate the JS? // Output the tables. for (int i = 0; i < escapeMaps.size(); ++i) { Map<Character, String> escapeMap = escapeMaps.get(i); String escapeMapName = escapeMapNames.get(i); generateCharacterMapSignature(outputCode, escapeMapName); outputCode.append(" = {"); boolean needsComma = false; for (Map.Entry<Character, String> e : escapeMap.entrySet()) { if (needsComma) { outputCode.append(','); } outputCode.append("\n "); writeUnsafeStringLiteral(e.getKey(), outputCode); outputCode.append(": "); writeStringLiteral(e.getValue(), outputCode); needsComma = true; } outputCode.append("\n}").append(getLineEndSyntax()).append("\n"); generateReplacerFunction(outputCode, escapeMapName); } for (int i = 0; i < matchers.size(); ++i) { String matcherName = matcherNames.get(i); String matcher = matchers.get(i); generateMatcher(outputCode, matcherName, matcher); } for (int i = 0; i < filters.size(); ++i) { String filterName = filterNames.get(i); String filter = filters.get(i); generateFilter(outputCode, filterName, filter); } // Finally, define the helper functions that use the escapes, filters, matchers, etc. for (DirectiveDigest digest : digests) { digest.updateNames(escapeMapNames, matcherNames, filterNames); generateHelperFunction(outputCode, digest); } // Emit patterns and constants needed by escaping functions that are not part of any one // escaping convention. generateCommonConstants(outputCode); outputCode.append('\n').append(GENERATED_CODE_END_MARKER).append('\n'); }
From source file:brooklyn.util.flags.TypeCoercions.java
/** * Type coercion {@link Function function} for {@link Enum enums}. * <p>// ww w. j a v a 2 s . c o m * Tries to convert the string to {@link CaseFormat#UPPER_UNDERSCORE} first, * handling all of the different {@link CaseFormat format} possibilites. Failing * that, it tries a case-insensitive comparison with the valid enum values. * <p> * Returns {@code defaultValue} if the string cannot be converted. * * @see TypeCoercions#coerce(Object, Class) * @see Enum#valueOf(Class, String) */ public static <E extends Enum<E>> Function<String, E> stringToEnum(final Class<E> type, @Nullable final E defaultValue) { return new Function<String, E>() { @Override public E apply(String input) { Preconditions.checkNotNull(input, "input"); List<String> options = ImmutableList.of(input, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input)); for (String value : options) { try { return Enum.valueOf(type, value); } catch (IllegalArgumentException iae) { continue; } } Maybe<E> result = Enums.valueOfIgnoreCase(type, input); return (result.isPresent()) ? result.get() : defaultValue; } }; }
From source file:com.facebook.buck.cxx.CxxGenruleDescription.java
private ImmutableMap<String, MacroReplacer> getMacroReplacersForTargetTranslation(BuildTarget target, CellPathResolver cellNames, TargetNodeTranslator translator) { BuildTargetPatternParser<?> buildTargetPatternParser = BuildTargetPatternParser .forBaseName(target.getBaseName()); ImmutableMap.Builder<String, MacroReplacer> macros = ImmutableMap.builder(); ImmutableList.of("exe", "location", "location-platform", "cppflags", "cxxppflags", "solibs") .forEach(name -> macros.put(name, new TargetTranslatorMacroReplacer(new AsIsMacroReplacer(name), Filter.NONE, buildTargetPatternParser, cellNames, translator))); ImmutableList.of("platform-name", "cc", "cflags", "cxx", "cxxflags", "ld") .forEach(name -> macros.put(name, new AsIsMacroReplacer(name))); for (Linker.LinkableDepType style : Linker.LinkableDepType.values()) { for (Filter filter : Filter.values()) { String name = String.format("ldflags-%s%s", CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, style.toString()), filter == Filter.PARAM ? "-filter" : ""); macros.put(name, new TargetTranslatorMacroReplacer(new AsIsMacroReplacer(name), filter, buildTargetPatternParser, cellNames, translator)); }// w w w . java 2 s. co m } return macros.build(); }
From source file:org.solenopsis.checkstyle.JavadocDetailNodeParser.java
/** * Gets token type of ParseTree node from JavadocTokenTypes class. * @param node ParseTree node.//from w w w . ja va 2s . c om * @return token type from JavadocTokenTypes */ private static int getTokenType(ParseTree node) { final int tokenType; if (node.getChildCount() == 0) { tokenType = ((TerminalNode) node).getSymbol().getType(); } else { final String className = getNodeClassNameWithoutContext(node); final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className); tokenType = JavadocUtils.getTokenId(typeName); } return tokenType; }
From source file:org.ballerinalang.langserver.compiler.format.TextDocumentFormatUtil.java
/** * Generate json representation for the given node. * * @param node Node to get the json representation * @param anonStructs Map of anonymous structs * @param symbolMetaInfoMap symbol meta information map * @return {@link JsonElement} Json Representation of the node * @throws JSONGenerationException when Json error occurs *//*from w w w . ja va 2s . c o m*/ public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs, Map<BLangNode, List<SymbolMetaInfo>> symbolMetaInfoMap) throws JSONGenerationException { if (node == null) { return JsonNull.INSTANCE; } Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream() .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet()); JsonObject nodeJson = new JsonObject(); JsonArray wsJsonArray = new JsonArray(); Set<Whitespace> ws = node.getWS(); if (ws != null && !ws.isEmpty()) { for (Whitespace whitespace : ws) { JsonObject wsJson = new JsonObject(); wsJson.addProperty("ws", whitespace.getWs()); wsJson.addProperty("i", whitespace.getIndex()); wsJson.addProperty("text", whitespace.getPrevious()); wsJson.addProperty("static", whitespace.isStatic()); wsJsonArray.add(wsJson); } nodeJson.add("ws", wsJsonArray); } Diagnostic.DiagnosticPosition position = node.getPosition(); if (position != null) { JsonObject positionJson = new JsonObject(); positionJson.addProperty("startColumn", position.getStartColumn()); positionJson.addProperty("startLine", position.getStartLine()); positionJson.addProperty("endColumn", position.getEndColumn()); positionJson.addProperty("endLine", position.getEndLine()); nodeJson.add("position", positionJson); } /* Virtual props */ // Add UUID for each node. nodeJson.addProperty("id", UUID.randomUUID().toString()); // Add the visible endpoints for a given node if (symbolMetaInfoMap.containsKey(node)) { List<SymbolMetaInfo> endpointMetaList = symbolMetaInfoMap.get(node); JsonArray endpoints = new JsonArray(); endpointMetaList.forEach(symbolMetaInfo -> endpoints.add(symbolMetaInfo.getJson())); nodeJson.add("VisibleEndpoints", endpoints); } JsonArray type = getType(node); if (type != null) { nodeJson.add(SYMBOL_TYPE, type); } if (node.getKind() == NodeKind.INVOCATION) { assert node instanceof BLangInvocation : node.getClass(); BLangInvocation invocation = (BLangInvocation) node; if (invocation.symbol != null && invocation.symbol.kind != null) { nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString()); } } for (Method m : methods) { String name = m.getName(); if (name.equals("getWS") || name.equals("getPosition")) { continue; } String jsonName; if (name.startsWith("get")) { jsonName = toJsonName(name, 3); } else if (name.startsWith("is")) { jsonName = toJsonName(name, 2); } else { continue; } Object prop = null; try { prop = m.invoke(node); } catch (IllegalAccessException | InvocationTargetException e) { throw new JSONGenerationException("Error occurred while generating JSON", e); } /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */ if ((node.getKind() == NodeKind.LITERAL || node.getKind() == NodeKind.NUMERIC_LITERAL) && "value".equals(jsonName)) { if (prop instanceof String) { nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"'); nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop)); } else { nodeJson.addProperty(jsonName, String.valueOf(prop)); } continue; } if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) { JsonArray attachmentPoints = new JsonArray(); ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue) .map(JsonPrimitive::new).forEach(attachmentPoints::add); nodeJson.add("attachmentPoints", attachmentPoints); } if (prop instanceof List && jsonName.equals("types")) { // Currently we don't need any Symbols for the UI. So skipping for now. continue; } /* Node classes */ if (prop instanceof Node) { nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs, symbolMetaInfoMap)); } else if (prop instanceof List) { List listProp = (List) prop; JsonArray listPropJson = new JsonArray(); nodeJson.add(jsonName, listPropJson); for (Object listPropItem : listProp) { if (listPropItem instanceof Node) { /* Remove top level anon func and struct */ if (node.getKind() == NodeKind.COMPILATION_UNIT) { if (listPropItem instanceof BLangFunction && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) { continue; } } listPropJson.add(generateJSON((Node) listPropItem, anonStructs, symbolMetaInfoMap)); } else if (listPropItem instanceof BLangRecordVarRef.BLangRecordVarRefKeyValue) { listPropJson.add(generateJSON( ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getVariableName(), anonStructs, symbolMetaInfoMap)); listPropJson.add(generateJSON( ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getBindingPattern(), anonStructs, symbolMetaInfoMap)); } else if (listPropItem instanceof BLangRecordVariable.BLangRecordVariableKeyValue) { listPropJson.add(generateJSON( ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getKey(), anonStructs, symbolMetaInfoMap)); listPropJson.add(generateJSON( ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getValue(), anonStructs, symbolMetaInfoMap)); } else if (listPropItem instanceof String) { listPropJson.add((String) listPropItem); } else { logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem); } } /* Runtime model classes */ } else if (prop instanceof Set && jsonName.equals("flags")) { Set flags = (Set) prop; for (Flag flag : Flag.values()) { nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag)); } } else if (prop instanceof Set) { // TODO : limit this else if to getInputs getOutputs of transform. Set vars = (Set) prop; JsonArray listVarJson = new JsonArray(); nodeJson.add(jsonName, listVarJson); for (Object obj : vars) { listVarJson.add(obj.toString()); } } else if (prop instanceof NodeKind) { String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString()); nodeJson.addProperty(jsonName, kindName); } else if (prop instanceof OperatorKind) { nodeJson.addProperty(jsonName, prop.toString()); /* Generic classes */ } else if (prop instanceof String) { nodeJson.addProperty(jsonName, (String) prop); } else if (prop instanceof Number) { nodeJson.addProperty(jsonName, (Number) prop); } else if (prop instanceof Boolean) { nodeJson.addProperty(jsonName, (Boolean) prop); } else if (prop instanceof Enum) { nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name())); } else if (prop instanceof int[]) { int[] intArray = ((int[]) prop); JsonArray intArrayPropJson = new JsonArray(); nodeJson.add(jsonName, intArrayPropJson); for (int intProp : intArray) { intArrayPropJson.add(intProp); } } else if (prop != null) { nodeJson.addProperty(jsonName, prop.toString()); } } return nodeJson; }
From source file:com.google.template.soy.jssrc.internal.GenerateSoyUtilsEscapingDirectiveCode.java
/** * Appends JavaScript to the given buffer. * * <p>/*from w ww .ja v a2 s . c o m*/ * The output JavaScript contains symbol definitions in the soy namespace. * <pre> * soy.esc.$$ESCAPES_FOR_ESCAPE_HTML_ = { ... }; // Maps of characters to escaped versions * soy.esc.$$MATCHER_FOR_ESCAPE_HTML_ = /.../g; // A single character matching RegExp * soy.esc.$$REPLACER_FOR_ESCAPE_HTML_ = function(ch) { ... }; // Usable with String.replace * soy.esc.$$FILTER_FOR_ESCAPE_HTML_ = /.../g; // Optional regular expression that vets values. * // A function that uses the above definitions. * soy.esc.$$escapeHtmlHelper = function(value) { return ...; }; * </pre> * These definitions are all marked {@code @private} and have Closure compiler type * annotations. * * <p>There is not necessarily a one-to-one relationship between any of the symbols above * and escape directives except for the {@code soy.esc.$$escape...Helper} function. * * @param availableJavaScript Determines whether a qualified JavaScript identifier, like * {@code goog.foo.Bar}, is available. * @param outputJs Receives output JavaScript. */ @VisibleForTesting void generateJavaScript(Predicate<String> availableJavaScript, StringBuilder outputJs) { /** * The JS identifiers associated with the support for a particular escaping directive. */ class DirectiveDigest { /** The name of the directive to output. */ final String directiveName; /** Index into escapes of the object that maps characters to escaped text. */ final int escapesVar; /** Index into matchers. */ final int matcherVar; /** Index into filters. */ final int filterVar; /** The prefix to use for non-ASCII characters not in the escape map. */ final @Nullable String nonAsciiPrefix; /** Innocuous output for this context. */ final String innocuousOutput; DirectiveDigest(String directiveName, int escapesVar, int matcherVar, int filterVar, @Nullable String nonAsciiPrefix, String innocuousOutput) { this.directiveName = directiveName; this.escapesVar = escapesVar; this.matcherVar = matcherVar; this.filterVar = filterVar; this.nonAsciiPrefix = nonAsciiPrefix; this.innocuousOutput = innocuousOutput; } } outputJs.append('\n').append(GENERATED_CODE_START_MARKER).append('\n'); // First we collect all the side tables. // Like { '\n': '\\n', ... } that map characters to escape. List<Map<Character, String>> escapeMaps = Lists.newArrayList(); // Mangled directive names corresponding to escapeMaps used to generate soy.esc.$$..._ names. List<String> escapeMapNames = Lists.newArrayList(); // Like /[\n\r'"]/g that match all the characters that need escaping. List<String> matchers = Lists.newArrayList(); // Mangled directive names corresponding to matchers. List<String> matcherNames = Lists.newArrayList(); // RegExps that vet input values. List<String> filters = Lists.newArrayList(); // Mangled directive names corresponding to filters. List<String> filterNames = Lists.newArrayList(); // Bundles of directiveNames and indices into escapeMaps, matchers, etc. List<DirectiveDigest> digests = Lists.newArrayList(); escaperLoop: for (EscapingConventions.CrossLanguageStringXform escaper : EscapingConventions .getAllEscapers()) { // "|escapeHtml" -> "escapeHtml" String escapeDirectiveIdent = escaper.getDirectiveName().substring(1); // "escapeHtml" -> "ESCAPE_HTML" String escapeDirectiveUIdent = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, escapeDirectiveIdent); // If there is an existing function, use it. for (String existingFunction : escaper.getJsFunctionNames()) { if (availableJavaScript.apply(existingFunction)) { // soy.esc.$$escapeFooHelper = bar; outputJs.append('\n').append("/**\n").append(" * @type {function (*) : string}\n") .append(" */\n").append("soy.esc.$$").append(escapeDirectiveIdent) .append("Helper = function(v) {\n").append(" return ").append(existingFunction) .append("(String(v));\n").append("};\n"); continue escaperLoop; } } // Else generate definitions for side tables. int escapesVar = -1; int matcherVar = -1; if (!escaper.getEscapes().isEmpty()) { Map<Character, String> escapeMap = Maps.newLinkedHashMap(); StringBuilder matcherRegexBuf = new StringBuilder("/["); int lastCodeUnit = Integer.MIN_VALUE; int rangeStart = Integer.MIN_VALUE; for (EscapingConventions.Escape esc : escaper.getEscapes()) { char ch = esc.getPlainText(); if (ch == lastCodeUnit) { throw new IllegalStateException( "Ambiguous escape " + esc.getEscaped() + " for " + escapeDirectiveIdent); } escapeMap.put(ch, esc.getEscaped()); if (ch != lastCodeUnit + 1) { if (rangeStart != Integer.MIN_VALUE) { escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); } rangeStart = ch; } lastCodeUnit = ch; } if (rangeStart < 0) { throw new IllegalStateException(); } escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); matcherRegexBuf.append("]/g"); // See if we can reuse an existing map. int numEscapeMaps = escapeMaps.size(); for (int i = 0; i < numEscapeMaps; ++i) { if (mapsHaveCompatibleOverlap(escapeMaps.get(i), escapeMap)) { escapesVar = i; break; } } if (escapesVar == -1) { escapesVar = numEscapeMaps; escapeMaps.add(escapeMap); escapeMapNames.add(escapeDirectiveUIdent); } else { escapeMaps.get(escapesVar).putAll(escapeMap); // ESCAPE_JS -> ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX escapeMapNames.set(escapesVar, escapeMapNames.get(escapesVar) + "__AND__" + escapeDirectiveUIdent); } String matcherRegex = matcherRegexBuf.toString(); matcherVar = matchers.indexOf(matcherRegex); if (matcherVar < 0) { matcherVar = matchers.size(); matchers.add(matcherRegex); matcherNames.add(escapeDirectiveUIdent); } else { matcherNames.set(matcherVar, matcherNames.get(matcherVar) + "__AND__" + escapeDirectiveUIdent); } } // Find a suitable filter or add one to filters. int filterVar = -1; Pattern filterPatternJava = escaper.getValueFilter(); if (filterPatternJava != null) { // This is an approximate translation from Java patterns to JavaScript patterns. String filterPattern = javaRegexToJs(filterPatternJava); filterVar = filters.indexOf(filterPattern); if (filterVar == -1) { filterVar = filters.size(); filters.add(filterPattern); filterNames.add(escapeDirectiveUIdent); } else { filterNames.set(filterVar, filterNames.get(filterVar) + "__AND__" + escapeDirectiveUIdent); } } digests.add(new DirectiveDigest(escapeDirectiveIdent, escapesVar, matcherVar, filterVar, escaper.getNonAsciiPrefix(), escaper.getInnocuousOutput())); } // TODO: Maybe use java Soy templates to generate the JS? // Output the tables. for (int i = 0; i < escapeMaps.size(); ++i) { Map<Character, String> escapeMap = escapeMaps.get(i); String escapeMapName = escapeMapNames.get(i); outputJs.append('\n').append("/**\n") .append(" * Maps charcters to the escaped versions for the named escape directives.\n") .append(" * @type {Object.<string, string>}\n").append(" * @private\n").append(" */\n") .append("soy.esc.$$ESCAPE_MAP_FOR_").append(escapeMapName).append("_ = {"); boolean needsComma = false; for (Map.Entry<Character, String> e : escapeMap.entrySet()) { if (needsComma) { outputJs.append(','); } outputJs.append("\n "); writeJsChar(e.getKey(), outputJs); outputJs.append(": "); writeJsString(e.getValue(), outputJs); needsComma = true; } outputJs.append("\n};\n"); outputJs.append('\n').append("/**\n").append(" * A function that can be used with String.replace..\n") .append(" * @param {string} ch A single character matched by a compatible matcher.\n") .append(" * @return {string} A token in the output language.\n").append(" * @private\n") .append(" */\n").append("soy.esc.$$REPLACER_FOR_").append(escapeMapName) .append("_ = function(ch) {\n").append(" return soy.esc.$$ESCAPE_MAP_FOR_") .append(escapeMapName).append("_[ch];\n").append("};\n"); } for (int i = 0; i < matchers.size(); ++i) { String matcher = matchers.get(i); String matcherName = matcherNames.get(i); outputJs.append('\n').append("/**\n") .append(" * Matches characters that need to be escaped for the named directives.\n") .append(" * @type RegExp\n").append(" * @private\n").append(" */\n") .append("soy.esc.$$MATCHER_FOR_").append(matcherName).append("_ = ").append(matcher) .append(";\n"); } for (int i = 0; i < filters.size(); ++i) { String filter = filters.get(i); String filterName = filterNames.get(i); outputJs.append('\n').append("/**\n") .append(" * A pattern that vets values produced by the named directives.\n") .append(" * @type RegExp\n").append(" * @private\n").append(" */\n") .append("soy.esc.$$FILTER_FOR_").append(filterName).append("_ = ").append(filter).append(";\n"); } // Finally, define the helper functions that use the escapes, filters, matchers, etc. for (DirectiveDigest digest : digests) { String name = digest.directiveName; outputJs.append('\n').append("/**\n").append(" * A helper for the Soy directive |").append(name) .append('\n') .append(" * @param {*} value Can be of any type but will be coerced to a string.\n") .append(" * @return {string} The escaped text.\n").append(" */\n").append("soy.esc.$$") .append(name).append("Helper = function(value) {\n").append(" var str = String(value);\n"); if (digest.filterVar != -1) { String filterName = filterNames.get(digest.filterVar); outputJs.append(" if (!soy.esc.$$FILTER_FOR_").append(filterName).append("_.test(str)) {\n"); if (availableJavaScript.apply("goog.asserts.fail")) { outputJs.append(" goog.asserts.fail('Bad value `%s` for |").append(name) .append("', [str]);\n"); } outputJs.append(" return '").append(digest.innocuousOutput).append("';\n").append(" }\n"); } if (digest.nonAsciiPrefix != null) { // TODO: We can add a second replace of all non-ascii codepoints below. throw new UnsupportedOperationException("Non ASCII prefix escapers not implemented yet."); } if (digest.escapesVar >= 0) { String escapeMapName = escapeMapNames.get(digest.escapesVar); String matcherName = matcherNames.get(digest.matcherVar); outputJs.append(" return str.replace(\n").append(" soy.esc.$$MATCHER_FOR_") .append(matcherName).append("_,\n").append(" soy.esc.$$REPLACER_FOR_") .append(escapeMapName).append("_);\n"); } else { outputJs.append(" return str;\n"); } outputJs.append("};\n"); } // Emit patterns and constants needed by escaping functions that are not part of any one // escaping convention. outputJs.append('\n').append("/**\n") .append(" * Matches all tags, HTML comments, and DOCTYPEs in tag soup HTML.\n") .append(" * By removing these, and replacing any '<' or '>' characters with\n") .append(" * entities we guarantee that the result can be embedded into a\n") .append(" * an attribute without introducing a tag boundary.\n").append(" *\n") .append(" * @type {RegExp}\n").append(" * @private\n").append(" */\n") .append("soy.esc.$$HTML_TAG_REGEX_ = ").append(javaRegexToJs(EscapingConventions.HTML_TAG_CONTENT)) .append("g;\n").append("\n").append("/**\n").append(" * Matches all occurrences of '<'.\n") .append(" *\n").append(" * @type {RegExp}\n").append(" * @private\n").append(" */\n") .append("soy.esc.$$LT_REGEX_ = /</g;\n"); outputJs.append('\n').append("/**\n").append(" * Maps lower-case names of innocuous tags to 1.\n") .append(" *\n").append(" * @type {Object.<string,number>}\n").append(" * @private\n") .append(" */\n").append("soy.esc.$$SAFE_TAG_WHITELIST_ = ") .append(toJsStringSet(TagWhitelist.FORMATTING.asSet())).append(";\n"); outputJs.append('\n').append(GENERATED_CODE_END_MARKER).append('\n'); }
From source file:cake.bootstrap.spi.CakeSourcePackages.java
static void createEnums(String directory, Iterable<Path> paths) throws IOException { for (Path pp : paths) { for (String str : Files.readAllLines(pp, Charset.defaultCharset())) { if (str.contains("kind=\"src\"") && (str.contains("main") || str.contains("test")) && !str.contains("combineaccessrules") && !str.contains("private")) { String p = str.split("\"")[3]; String v = p.substring(0, p.indexOf("/src")); if (v.contains("/")) { v = v.substring(v.lastIndexOf("/") + 1); }//from ww w . j a v a2s . com v = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, v); p = "../" + directory + "/" + p; System.out.println(" " + v + (str.contains("main") ? "" : "_TEST") + "(\"" + p + "\"),"); } else if (str.contains("bootstrap")) { String p = str.split("\"")[3]; String v = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, p.split("/")[0]); System.out.println(" " + v + "(\"" + p + "\"),"); } } } }
From source file:stroom.util.config.StroomProperties.java
private static String getEnv(final String propertyName) { // Environment variable names are transformations of property names. // E.g. stroom.temp => STROOM_TEMP. // E.g. stroom.jdbcDriverUsername => STROOM_JDBC_DRIVER_USERNAME String environmentVariableName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, propertyName.replace('.', '_')); String environmentVariable = System.getenv(environmentVariableName); if (StringUtils.isNotBlank(environmentVariable)) { return environmentVariable; }//www .jav a2 s .co m return null; }
From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.java
/** * Gets token type of ParseTree node from JavadocTokenTypes class. * @param node ParseTree node.//from ww w.ja v a 2s. co m * @return token type from JavadocTokenTypes */ private static int getTokenType(ParseTree node) { int tokenType; if (node.getChildCount() == 0) { tokenType = ((TerminalNode) node).getSymbol().getType(); } else { final String className = getNodeClassNameWithoutContext(node); final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className); tokenType = JavadocUtils.getTokenId(typeName); } return tokenType; }
From source file:net.simonvt.schematic.compiler.TableWriter.java
public void createValuesBuilder(Filer filer, String outPackage) throws IOException { String name = Character.toUpperCase(this.name.charAt(0)) + this.name.substring(1); String valuesPackage = outPackage + ".values"; String className = name + "ValuesBuilder"; String qualifiedName = outPackage + ".values." + className; JavaFileObject jfo = filer.createSourceFile(qualifiedName); Writer out = jfo.openWriter(); TypeSpec.Builder valuesBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC); FieldSpec valuesSpec = FieldSpec.builder(Clazz.CONTENT_VALUES, "values") .initializer("new $T()", Clazz.CONTENT_VALUES).build(); valuesBuilder.addField(valuesSpec);// w w w . j av a 2s .c o m for (VariableElement element : columns) { String elmName = element.getSimpleName().toString(); elmName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, elmName); DataType dataType = element.getAnnotation(DataType.class); DataType.Type type = dataType.value(); String column = element.getSimpleName().toString(); switch (type) { case INTEGER: valuesBuilder .addMethod(makePutMethodSpec(valuesPackage, className, elmName, column, Integer.class)); valuesBuilder.addMethod(makePutMethodSpec(valuesPackage, className, elmName, column, Long.class)); break; case REAL: valuesBuilder.addMethod(makePutMethodSpec(valuesPackage, className, elmName, column, Float.class)); valuesBuilder.addMethod(makePutMethodSpec(valuesPackage, className, elmName, column, Double.class)); break; case TEXT: valuesBuilder.addMethod(makePutMethodSpec(valuesPackage, className, elmName, column, String.class)); break; case BLOB: // TODO: What do I call here? break; } } valuesBuilder.addMethod(MethodSpec.methodBuilder("values").returns(Clazz.CONTENT_VALUES) .addModifiers(Modifier.PUBLIC).addStatement("return values").build()); JavaFile javaFile = JavaFile.builder(valuesPackage, valuesBuilder.build()).build(); javaFile.writeTo(out); out.flush(); out.close(); }