View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util;
12  
13  import java.text.MessageFormat;
14  import java.util.Collection;
15  
16  import org.eclipse.jgit.internal.JGitText;
17  
18  /**
19   * Miscellaneous string comparison utility methods.
20   */
21  public final class StringUtils {
22  	private static final char[] LC;
23  
24  	static {
25  		LC = new char['Z' + 1];
26  		for (char c = 0; c < LC.length; c++)
27  			LC[c] = c;
28  		for (char c = 'A'; c <= 'Z'; c++)
29  			LC[c] = (char) ('a' + (c - 'A'));
30  	}
31  
32  	/**
33  	 * Convert the input to lowercase.
34  	 * <p>
35  	 * This method does not honor the JVM locale, but instead always behaves as
36  	 * though it is in the US-ASCII locale. Only characters in the range 'A'
37  	 * through 'Z' are converted. All other characters are left as-is, even if
38  	 * they otherwise would have a lowercase character equivalent.
39  	 *
40  	 * @param c
41  	 *            the input character.
42  	 * @return lowercase version of the input.
43  	 */
44  	public static char toLowerCase(char c) {
45  		return c <= 'Z' ? LC[c] : c;
46  	}
47  
48  	/**
49  	 * Convert the input string to lower case, according to the "C" locale.
50  	 * <p>
51  	 * This method does not honor the JVM locale, but instead always behaves as
52  	 * though it is in the US-ASCII locale. Only characters in the range 'A'
53  	 * through 'Z' are converted, all other characters are left as-is, even if
54  	 * they otherwise would have a lowercase character equivalent.
55  	 *
56  	 * @param in
57  	 *            the input string. Must not be null.
58  	 * @return a copy of the input string, after converting characters in the
59  	 *         range 'A'..'Z' to 'a'..'z'.
60  	 */
61  	public static String toLowerCase(String in) {
62  		final StringBuilder r = new StringBuilder(in.length());
63  		for (int i = 0; i < in.length(); i++)
64  			r.append(toLowerCase(in.charAt(i)));
65  		return r.toString();
66  	}
67  
68  
69  	/**
70  	 * Borrowed from commons-lang <code>StringUtils.capitalize()</code> method.
71  	 *
72  	 * <p>
73  	 * Capitalizes a String changing the first letter to title case as per
74  	 * {@link java.lang.Character#toTitleCase(char)}. No other letters are
75  	 * changed.
76  	 * </p>
77  	 * <p>
78  	 * A <code>null</code> input String returns <code>null</code>.
79  	 * </p>
80  	 *
81  	 * @param str
82  	 *            the String to capitalize, may be null
83  	 * @return the capitalized String, <code>null</code> if null String input
84  	 * @since 4.0
85  	 */
86  	public static String capitalize(String str) {
87  		int strLen;
88  		if (str == null || (strLen = str.length()) == 0) {
89  			return str;
90  		}
91  		return new StringBuilder(strLen)
92  				.append(Character.toTitleCase(str.charAt(0)))
93  				.append(str.substring(1)).toString();
94  	}
95  
96  	/**
97  	 * Test if two strings are equal, ignoring case.
98  	 * <p>
99  	 * This method does not honor the JVM locale, but instead always behaves as
100 	 * though it is in the US-ASCII locale.
101 	 *
102 	 * @param a
103 	 *            first string to compare.
104 	 * @param b
105 	 *            second string to compare.
106 	 * @return true if a equals b
107 	 */
108 	public static boolean equalsIgnoreCase(String a, String b) {
109 		if (References.isSameObject(a, b)) {
110 			return true;
111 		}
112 		if (a.length() != b.length())
113 			return false;
114 		for (int i = 0; i < a.length(); i++) {
115 			if (toLowerCase(a.charAt(i)) != toLowerCase(b.charAt(i)))
116 				return false;
117 		}
118 		return true;
119 	}
120 
121 	/**
122 	 * Compare two strings, ignoring case.
123 	 * <p>
124 	 * This method does not honor the JVM locale, but instead always behaves as
125 	 * though it is in the US-ASCII locale.
126 	 *
127 	 * @param a
128 	 *            first string to compare.
129 	 * @param b
130 	 *            second string to compare.
131 	 * @since 2.0
132 	 * @return an int.
133 	 */
134 	public static int compareIgnoreCase(String a, String b) {
135 		for (int i = 0; i < a.length() && i < b.length(); i++) {
136 			int d = toLowerCase(a.charAt(i)) - toLowerCase(b.charAt(i));
137 			if (d != 0)
138 				return d;
139 		}
140 		return a.length() - b.length();
141 	}
142 
143 	/**
144 	 * Compare two strings, honoring case.
145 	 * <p>
146 	 * This method does not honor the JVM locale, but instead always behaves as
147 	 * though it is in the US-ASCII locale.
148 	 *
149 	 * @param a
150 	 *            first string to compare.
151 	 * @param b
152 	 *            second string to compare.
153 	 * @since 2.0
154 	 * @return an int.
155 	 */
156 	public static int compareWithCase(String a, String b) {
157 		for (int i = 0; i < a.length() && i < b.length(); i++) {
158 			int d = a.charAt(i) - b.charAt(i);
159 			if (d != 0)
160 				return d;
161 		}
162 		return a.length() - b.length();
163 	}
164 
165 	/**
166 	 * Parse a string as a standard Git boolean value. See
167 	 * {@link #toBooleanOrNull(String)}.
168 	 *
169 	 * @param stringValue
170 	 *            the string to parse.
171 	 * @return the boolean interpretation of {@code value}.
172 	 * @throws java.lang.IllegalArgumentException
173 	 *             if {@code value} is not recognized as one of the standard
174 	 *             boolean names.
175 	 */
176 	public static boolean toBoolean(String stringValue) {
177 		if (stringValue == null)
178 			throw new NullPointerException(JGitText.get().expectedBooleanStringValue);
179 
180 		final Boolean bool = toBooleanOrNull(stringValue);
181 		if (bool == null)
182 			throw new IllegalArgumentException(MessageFormat.format(JGitText.get().notABoolean, stringValue));
183 
184 		return bool.booleanValue();
185 	}
186 
187 	/**
188 	 * Parse a string as a standard Git boolean value.
189 	 * <p>
190 	 * The terms {@code yes}, {@code true}, {@code 1}, {@code on} can all be
191 	 * used to mean {@code true}.
192 	 * <p>
193 	 * The terms {@code no}, {@code false}, {@code 0}, {@code off} can all be
194 	 * used to mean {@code false}.
195 	 * <p>
196 	 * Comparisons ignore case, via {@link #equalsIgnoreCase(String, String)}.
197 	 *
198 	 * @param stringValue
199 	 *            the string to parse.
200 	 * @return the boolean interpretation of {@code value} or null in case the
201 	 *         string does not represent a boolean value
202 	 */
203 	public static Boolean toBooleanOrNull(String stringValue) {
204 		if (stringValue == null)
205 			return null;
206 
207 		if (equalsIgnoreCase("yes", stringValue) //$NON-NLS-1$
208 				|| equalsIgnoreCase("true", stringValue) //$NON-NLS-1$
209 				|| equalsIgnoreCase("1", stringValue) //$NON-NLS-1$
210 				|| equalsIgnoreCase("on", stringValue)) //$NON-NLS-1$
211 			return Boolean.TRUE;
212 		else if (equalsIgnoreCase("no", stringValue) //$NON-NLS-1$
213 				|| equalsIgnoreCase("false", stringValue) //$NON-NLS-1$
214 				|| equalsIgnoreCase("0", stringValue) //$NON-NLS-1$
215 				|| equalsIgnoreCase("off", stringValue)) //$NON-NLS-1$
216 			return Boolean.FALSE;
217 		else
218 			return null;
219 	}
220 
221 	/**
222 	 * Join a collection of Strings together using the specified separator.
223 	 *
224 	 * @param parts
225 	 *            Strings to join
226 	 * @param separator
227 	 *            used to join
228 	 * @return a String with all the joined parts
229 	 */
230 	public static String join(Collection<String> parts, String separator) {
231 		return StringUtils.join(parts, separator, separator);
232 	}
233 
234 	/**
235 	 * Join a collection of Strings together using the specified separator and a
236 	 * lastSeparator which is used for joining the second last and the last
237 	 * part.
238 	 *
239 	 * @param parts
240 	 *            Strings to join
241 	 * @param separator
242 	 *            separator used to join all but the two last elements
243 	 * @param lastSeparator
244 	 *            separator to use for joining the last two elements
245 	 * @return a String with all the joined parts
246 	 */
247 	public static String join(Collection<String> parts, String separator,
248 			String lastSeparator) {
249 		StringBuilder sb = new StringBuilder();
250 		int i = 0;
251 		int lastIndex = parts.size() - 1;
252 		for (String part : parts) {
253 			sb.append(part);
254 			if (i == lastIndex - 1) {
255 				sb.append(lastSeparator);
256 			} else if (i != lastIndex) {
257 				sb.append(separator);
258 			}
259 			i++;
260 		}
261 		return sb.toString();
262 	}
263 
264 	private StringUtils() {
265 		// Do not create instances
266 	}
267 
268 	/**
269 	 * Test if a string is empty or null.
270 	 *
271 	 * @param stringValue
272 	 *            the string to check
273 	 * @return <code>true</code> if the string is <code>null</code> or empty
274 	 */
275 	public static boolean isEmptyOrNull(String stringValue) {
276 		return stringValue == null || stringValue.length() == 0;
277 	}
278 
279 	/**
280 	 * Replace CRLF, CR or LF with a single space.
281 	 *
282 	 * @param in
283 	 *            A string with line breaks
284 	 * @return in without line breaks
285 	 * @since 3.1
286 	 */
287 	public static String replaceLineBreaksWithSpace(String in) {
288 		char[] buf = new char[in.length()];
289 		int o = 0;
290 		for (int i = 0; i < buf.length; ++i) {
291 			char ch = in.charAt(i);
292 			switch (ch) {
293 			case '\r':
294 				if (i + 1 < buf.length && in.charAt(i + 1) == '\n') {
295 					buf[o++] = ' ';
296 					++i;
297 				} else
298 					buf[o++] = ' ';
299 				break;
300 			case '\n':
301 				buf[o++] = ' ';
302 				break;
303 			default:
304 				buf[o++] = ch;
305 				break;
306 			}
307 		}
308 		return new String(buf, 0, o);
309 	}
310 }