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.logging.log4j.util;
018
019import java.util.Iterator;
020import java.util.Locale;
021import java.util.Objects;
022
023/**
024 * <em>Consider this class private.</em>
025 * 
026 * @see <a href="http://commons.apache.org/proper/commons-lang/">Apache Commons Lang</a>
027 */
028public final class Strings {
029
030    /**
031     * The empty string.
032     */
033    public static final String EMPTY = "";
034    
035    /**
036     * OS-dependent line separator, defaults to {@code "\n"} if the system property {@code ""line.separator"} cannot be
037     * read.
038     */
039    public static final String LINE_SEPARATOR = PropertiesUtil.getProperties().getStringProperty("line.separator",
040            "\n");
041
042    /**
043     * Returns a double quoted string.
044     * 
045     * @param str a String
046     * @return {@code "str"}
047     */
048    public static String dquote(final String str) {
049        return Chars.DQUOTE + str + Chars.DQUOTE;
050    }
051    
052    /**
053     * Checks if a String is blank. A blank string is one that is {@code null}, empty, or when trimmed using
054     * {@link String#trim()} is empty.
055     *
056     * @param s the String to check, may be {@code null}
057     * @return {@code true} if the String is {@code null}, empty, or trims to empty.
058     */
059    public static boolean isBlank(final String s) {
060        return s == null || s.trim().isEmpty();
061    }
062
063    /**
064     * <p>
065     * Checks if a CharSequence is empty ("") or null.
066     * </p>
067     *
068     * <pre>
069     * Strings.isEmpty(null)      = true
070     * Strings.isEmpty("")        = true
071     * Strings.isEmpty(" ")       = false
072     * Strings.isEmpty("bob")     = false
073     * Strings.isEmpty("  bob  ") = false
074     * </pre>
075     *
076     * <p>
077     * NOTE: This method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is
078     * available in isBlank().
079     * </p>
080     *
081     * <p>
082     * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.isEmpty(CharSequence)
083     * </p>
084     *
085     * @param cs the CharSequence to check, may be null
086     * @return {@code true} if the CharSequence is empty or null
087     */
088    public static boolean isEmpty(final CharSequence cs) {
089        return cs == null || cs.length() == 0;
090    }
091
092    /**
093     * Checks if a String is not blank. The opposite of {@link #isBlank(String)}.
094     *
095     * @param s the String to check, may be {@code null}
096     * @return {@code true} if the String is non-{@code null} and has content after being trimmed.
097     */
098    public static boolean isNotBlank(final String s) {
099        return !isBlank(s);
100    }
101
102    /**
103     * <p>
104     * Checks if a CharSequence is not empty ("") and not null.
105     * </p>
106     *
107     * <pre>
108     * Strings.isNotEmpty(null)      = false
109     * Strings.isNotEmpty("")        = false
110     * Strings.isNotEmpty(" ")       = true
111     * Strings.isNotEmpty("bob")     = true
112     * Strings.isNotEmpty("  bob  ") = true
113     * </pre>
114     *
115     * <p>
116     * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.isNotEmpty(CharSequence)
117     * </p>
118     *
119     * @param cs the CharSequence to check, may be null
120     * @return {@code true} if the CharSequence is not empty and not null
121     */
122    public static boolean isNotEmpty(final CharSequence cs) {
123        return !isEmpty(cs);
124    }
125
126    /**
127     * <p>Joins the elements of the provided {@code Iterable} into
128     * a single String containing the provided elements.</p>
129     *
130     * <p>No delimiter is added before or after the list. Null objects or empty
131     * strings within the iteration are represented by empty strings.</p>
132     *
133     * @param iterable  the {@code Iterable} providing the values to join together, may be null
134     * @param separator  the separator character to use
135     * @return the joined String, {@code null} if null iterator input
136     */
137    public static String join(final Iterable<?> iterable, final char separator) {
138        if (iterable == null) {
139            return null;
140        }
141        return join(iterable.iterator(), separator);
142    }
143
144    /**
145     * <p>Joins the elements of the provided {@code Iterator} into
146     * a single String containing the provided elements.</p>
147     *
148     * <p>No delimiter is added before or after the list. Null objects or empty
149     * strings within the iteration are represented by empty strings.</p>
150     *
151     * @param iterator  the {@code Iterator} of values to join together, may be null
152     * @param separator  the separator character to use
153     * @return the joined String, {@code null} if null iterator input
154     */
155    public static String join(final Iterator<?> iterator, final char separator) {
156
157        // handle null, zero and one elements before building a buffer
158        if (iterator == null) {
159            return null;
160        }
161        if (!iterator.hasNext()) {
162            return EMPTY;
163        }
164        final Object first = iterator.next();
165        if (!iterator.hasNext()) {
166            return Objects.toString(first, EMPTY);
167        }
168
169        // two or more elements
170        final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
171        if (first != null) {
172            buf.append(first);
173        }
174
175        while (iterator.hasNext()) {
176            buf.append(separator);
177            final Object obj = iterator.next();
178            if (obj != null) {
179                buf.append(obj);
180            }
181        }
182
183        return buf.toString();
184    }
185
186    /**
187     * <p>Gets the leftmost {@code len} characters of a String.</p>
188     *
189     * <p>If {@code len} characters are not available, or the
190     * String is {@code null}, the String will be returned without
191     * an exception. An empty String is returned if len is negative.</p>
192     *
193     * <pre>
194     * StringUtils.left(null, *)    = null
195     * StringUtils.left(*, -ve)     = ""
196     * StringUtils.left("", *)      = ""
197     * StringUtils.left("abc", 0)   = ""
198     * StringUtils.left("abc", 2)   = "ab"
199     * StringUtils.left("abc", 4)   = "abc"
200     * </pre>
201     *
202     * <p>
203     * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.
204     * </p>
205     * 
206     * @param str  the String to get the leftmost characters from, may be null
207     * @param len  the length of the required String
208     * @return the leftmost characters, {@code null} if null String input
209     */
210    public static String left(final String str, final int len) {
211        if (str == null) {
212            return null;
213        }
214        if (len < 0) {
215            return EMPTY;
216        }
217        if (str.length() <= len) {
218            return str;
219        }
220        return str.substring(0, len);
221    }
222
223    /**
224     * Returns a quoted string.
225     * 
226     * @param str a String
227     * @return {@code 'str'}
228     */
229    public static String quote(final String str) {
230        return Chars.QUOTE + str + Chars.QUOTE;
231    }
232    
233    /**
234     * <p>
235     * Removes control characters (char &lt;= 32) from both ends of this String returning {@code null} if the String is
236     * empty ("") after the trim or if it is {@code null}.
237     *
238     * <p>
239     * The String is trimmed using {@link String#trim()}. Trim removes start and end characters &lt;= 32.
240     * </p>
241     *
242     * <pre>
243     * Strings.trimToNull(null)          = null
244     * Strings.trimToNull("")            = null
245     * Strings.trimToNull("     ")       = null
246     * Strings.trimToNull("abc")         = "abc"
247     * Strings.trimToNull("    abc    ") = "abc"
248     * </pre>
249     *
250     * <p>
251     * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.trimToNull(String)
252     * </p>
253     *
254     * @param str the String to be trimmed, may be null
255     * @return the trimmed String, {@code null} if only chars &lt;= 32, empty or null String input
256     */
257    public static String trimToNull(final String str) {
258        final String ts = str == null ? null : str.trim();
259        return isEmpty(ts) ? null : ts;
260    }
261
262    private Strings() {
263        // empty
264    }
265
266    /**
267     * Shorthand for {@code str.toUpperCase(Locale.ROOT);}
268     * @param str The string to upper case.
269     * @return a new string
270     * @see String#toLowerCase(Locale)
271     */
272    public static String toRootUpperCase(final String str) {
273        return str.toUpperCase(Locale.ROOT);
274    }
275
276}