001/**
002 *
003 * Copyright 2019 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * 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.jivesoftware.smack.util;
018
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.List;
022
023public class ToStringUtil {
024
025    public static Builder builderFor(Class<?> clazz) {
026        StringBuilder sb = new StringBuilder();
027        sb.append(clazz.getSimpleName()).append('(');
028        return new Builder(sb);
029    }
030
031    public static final class Builder {
032        private final StringBuilder sb;
033
034        private Builder(StringBuilder sb) {
035            this.sb = sb;
036        }
037
038        public Builder addValue(String name, Object value) {
039            if (value == null) {
040                return this;
041            }
042            if (sb.charAt(sb.length() - 1) != '(') {
043                sb.append(' ');
044            }
045            sb.append(name).append("='").append(value).append('\'');
046            return this;
047        }
048
049        public <V> Builder add(String name, Collection<? extends V> values, Function<?, V> toStringFunction) {
050            if (values.isEmpty()) {
051                return this;
052            }
053
054            sb.append(' ').append(name).append('[');
055
056            List<String> stringValues = new ArrayList<>(values.size());
057            for (V value : values) {
058                String valueString = toStringFunction.apply(value).toString();
059                stringValues.add(valueString);
060            }
061
062            StringUtils.appendTo(stringValues, ", ", sb);
063
064            sb.append(']');
065
066            return this;
067        }
068
069        public String build() {
070            sb.append(')');
071
072            return sb.toString();
073        }
074    }
075}