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.*;
020import static org.apache.juneau.commons.utils.Utils.*;
021
022/**
023 * Converts property names to dashed-lower-case format.
024 *
025 * <h5 class='section'>Example:</h5>
026 * <ul>
027 *    <li><js>"fooBar"</js> -&gt; <js>"foo-bar"</js>
028 *    <li><js>"fooBarURL"</js> -&gt; <js>"foo-bar-url"</js>
029 *    <li><js>"FooBarURL"</js> -&gt; <js>"foo-bar-url"</js>
030 * </ul>
031 *
032 */
033public class PropertyNamerDLC implements PropertyNamer {
034
035   /** Reusable instance. */
036   public static final PropertyNamer INSTANCE = new PropertyNamerDLC();
037
038   @Override /* Overridden from PropertyNamer */
039   public String getPropertyName(String name) {
040      if (e(name))
041         return name;
042
043      var numUCs = 0;
044      var isPrevUC = isUpperCase(name.charAt(0));
045      for (var i = 1; i < name.length(); i++) {
046         var c = name.charAt(i);
047         if (isUpperCase(c)) {
048            if (! isPrevUC)
049               numUCs++;
050            isPrevUC = true;
051         } else {
052            isPrevUC = false;
053         }
054      }
055
056      var name2 = new char[name.length() + numUCs];
057      isPrevUC = isUpperCase(name.charAt(0));
058      var ni = 0;
059      for (var i = 0; i < name.length(); i++) {
060         var c = name.charAt(i);
061         if (isUpperCase(c)) {
062            if (! isPrevUC)
063               name2[ni++] = '-';
064            isPrevUC = true;
065            name2[ni++] = toLowerCase(c);
066         } else {
067            isPrevUC = false;
068            name2[ni++] = c;
069         }
070      }
071
072      return new String(name2);
073   }
074}