001/* 002 * Copyright 2011 Atteo. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. 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 distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014package org.atteo.evo.inflector; 015 016import java.util.ArrayList; 017import java.util.List; 018import java.util.regex.Pattern; 019 020import static java.lang.Character.toLowerCase; 021import static java.lang.Character.toUpperCase; 022 023public abstract class TwoFormInflector { 024 025 private final List<Rule> rules = new ArrayList<Rule>(); 026 027 protected String getPlural(String word) { 028 for (Rule rule : rules) { 029 String result = rule.getPlural(word); 030 if (result != null) { 031 return result; 032 } 033 } 034 return null; 035 } 036 037 protected void uncountable(String[] list) { 038 rules.add(new CategoryRule(list, "", "")); 039 } 040 041 protected void irregular(String singular, String plural) { 042 if (singular.charAt(0) == plural.charAt(0)) { 043 rules.add(new RegExpRule("(?i)(" + singular.charAt(0) + ")" + singular.substring(1) + "$", 044 "$1" + plural.substring(1))); 045 } else { 046 rules.add(new RegExpRule(toUpperCase(singular.charAt(0)) + "(?i)" + singular.substring(1) + "$", 047 toUpperCase(plural.charAt(0)) 048 + plural.substring(1))); 049 rules.add(new RegExpRule(toLowerCase(singular.charAt(0)) + "(?i)" + singular.substring(1) + "$", 050 toLowerCase(plural.charAt(0)) + plural.substring(1))); 051 } 052 } 053 054 protected void irregular(String[][] list) { 055 for (String[] pair : list) { 056 irregular(pair[0], pair[1]); 057 } 058 } 059 060 protected void rule(String singular, String plural) { 061 rules.add(new RegExpRule(Pattern.compile(singular, Pattern.CASE_INSENSITIVE), plural)); 062 } 063 064 protected void rule(String[][] list) { 065 for (String[] pair : list) { 066 rules.add(new RegExpRule(Pattern.compile(pair[0], Pattern.CASE_INSENSITIVE), pair[1])); 067 } 068 } 069 070 protected void categoryRule(String[] list, String singular, String plural) { 071 rules.add(new CategoryRule(list, singular, plural)); 072 } 073}