001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau;
018
019import static java.lang.Character.*;
020
021import org.apache.juneau.common.utils.*;
022
023/**
024 * Converts property names to dashed-upper-case-start format.
025 *
026 * <h5 class='section'>Example:</h5>
027 * <ul>
028 *    <li><js>"fooBar"</js> -&gt; <js>"Foo-Bar"</js>
029 *    <li><js>"fooBarURL"</js> -&gt; <js>"Foo-Bar-Url"</js>
030 *    <li><js>"FooBarURL"</js> -&gt; <js>"Foo-Bar-Url"</js>
031 * </ul>
032 *
033 * <h5 class='section'>See Also:</h5><ul>
034
035 * </ul>
036 */
037public class PropertyNamerDUCS implements PropertyNamer {
038
039   /** Reusable instance. */
040   public static final PropertyNamer INSTANCE = new PropertyNamerDUCS();
041
042   @Override /* PropertyNamer */
043   public String getPropertyName(String name) {
044      if (Utils.isEmpty(name))
045         return name;
046
047      int numUCs = 0;
048      boolean isPrevUC = isUpperCase(name.charAt(0));
049      for (int i = 1; i < name.length(); i++) {
050         char c = name.charAt(i);
051         if (isUpperCase(c)) {
052            if (! isPrevUC)
053               numUCs++;
054            isPrevUC = true;
055         } else {
056            isPrevUC = false;
057         }
058      }
059
060      char[] name2 = new char[name.length() + numUCs];
061      isPrevUC = true;
062      int ni = 0;
063      for (int i = 0; i < name.length(); i++) {
064         char c = name.charAt(i);
065         if (i == 0) {
066            name2[ni++] = toUpperCase(c);
067         } else {
068            if (isUpperCase(c)) {
069               if (! isPrevUC) {
070                  name2[ni++] = '-';
071                  name2[ni++] = toUpperCase(c);
072               } else {
073                  name2[ni++] = toLowerCase(c);
074               }
075               isPrevUC = true;
076            } else {
077               isPrevUC = false;
078               name2[ni++] = c;
079            }
080         }
081      }
082
083      return new String(name2);
084   }
085}