001// Copyright 2012 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.internal.clojure; 016 017import clojure.lang.Symbol; 018import org.apache.tapestry5.clojure.MethodToFunctionSymbolMapper; 019 020import java.lang.reflect.Method; 021import java.util.regex.MatchResult; 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025/** 026 * Default implementation that transforms a camelCased method-name to a clojure-style function name. 027 */ 028public class DefaultMapper implements MethodToFunctionSymbolMapper 029{ 030 public Symbol mapMethod(String namespace, Method method) 031 { 032 return mapMethodName(namespace, method.getName()); 033 } 034 035 private Symbol mapMethodName(String namespace, String name) 036 { 037 return Symbol.create(namespace, transformName(name)); 038 } 039 040 private final Pattern transition = Pattern.compile("(\\p{Lower}\\p{Upper})"); 041 042 private String transformName(String name) 043 { 044 045 Matcher matcher = transition.matcher(name); 046 047 StringBuilder builder = new StringBuilder(); 048 049 int lastx = 0; 050 051 while (matcher.find()) 052 { 053 MatchResult matchResult = matcher.toMatchResult(); 054 055 int start = matchResult.start(); 056 int end = matchResult.end(); 057 058 builder.append(name.substring(lastx, start + 1)); 059 builder.append("-"); 060 // TODO: An acronym (such as "URL") should not be lower cased here. 061 builder.append(name.substring(end - 1, end).toLowerCase()); 062 063 lastx = end; 064 } 065 066 if (lastx == 0) 067 { 068 return name; 069 } 070 071 builder.append(name.substring(lastx)); 072 073 return builder.toString(); 074 } 075 076}