• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
3  * Copyright (C) 2011, 2013-2016 The JavaParser Team.
4  *
5  * This file is part of JavaParser.
6  *
7  * JavaParser can be used either under the terms of
8  * a) the GNU Lesser General Public License as published by
9  *     the Free Software Foundation, either version 3 of the License, or
10  *     (at your option) any later version.
11  * b) the terms of the Apache License
12  *
13  * You should have received a copy of both licenses in LICENCE.LGPL and
14  * LICENCE.APACHE. Please refer to those files for details.
15  *
16  * JavaParser is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Lesser General Public License for more details.
20  */
21 
22 package com.github.javaparser.utils;
23 
24 import java.io.IOException;
25 import java.io.Reader;
26 import java.nio.file.Files;
27 import java.util.*;
28 import java.util.function.Predicate;
29 import java.util.function.Function;
30 
31 import static java.util.Arrays.*;
32 
33 /**
34  * Any kind of utility.
35  *
36  * @author Federico Tomassetti
37  */
38 public class Utils {
39     public static final String EOL = System.getProperty("line.separator");
40 
isNullOrEmpty(Collection<E> collection)41     public static <E> boolean isNullOrEmpty(Collection<E> collection) {
42         return collection == null || collection.isEmpty();
43     }
44 
assertNotNull(T o)45     public static <T> T assertNotNull(T o) {
46         if (o == null) {
47             throw new AssertionError("A reference was unexpectedly null.");
48         }
49         return o;
50     }
51 
assertNonEmpty(String string)52     public static String assertNonEmpty(String string) {
53         if (string == null || string.isEmpty()) {
54             throw new AssertionError("A string was unexpectedly empty.");
55         }
56         return string;
57     }
58 
assertNonNegative(T number)59     public static <T extends Number> T assertNonNegative(T number) {
60         if (number.longValue() < 0) {
61             throw new AssertionError("A number was unexpectedly negative.");
62         }
63         return number;
64     }
65 
assertPositive(T number)66     public static <T extends Number> T assertPositive(T number) {
67         if (number.longValue() <= 0) {
68             throw new AssertionError("A number was unexpectedly non-positive.");
69         }
70         return number;
71     }
72 
73     /**
74      * @return string with ASCII characters 10 and 13 replaced by the text "\n" and "\r".
75      */
escapeEndOfLines(String string)76     public static String escapeEndOfLines(String string) {
77         StringBuilder escapedString = new StringBuilder();
78         for (char c : string.toCharArray()) {
79             switch (c) {
80                 case '\n':
81                     escapedString.append("\\n");
82                     break;
83                 case '\r':
84                     escapedString.append("\\r");
85                     break;
86                 default:
87                     escapedString.append(c);
88             }
89         }
90         return escapedString.toString();
91     }
92 
readerToString(Reader reader)93     public static String readerToString(Reader reader) throws IOException {
94         final StringBuilder result = new StringBuilder();
95         final char[] buffer = new char[8 * 1024];
96         int numChars;
97 
98         while ((numChars = reader.read(buffer, 0, buffer.length)) > 0) {
99             result.append(buffer, 0, numChars);
100         }
101 
102         return result.toString();
103     }
104 
105     /**
106      * @deprecated use screamingToCamelCase
107      */
toCamelCase(String original)108     public static String toCamelCase(String original) {
109         return screamingToCamelCase(original);
110     }
111 
112     /**
113      * Transform a string to the camel case conversion.
114      * <p>
115      * For example "ABC_DEF" becomes "abcDef"
116      */
screamingToCamelCase(String original)117     public static String screamingToCamelCase(String original) {
118         StringBuilder sb = new StringBuilder();
119         String[] parts = original.toLowerCase().split("_");
120         for (int i = 0; i < parts.length; i++) {
121             sb.append(i == 0 ? parts[i] : capitalize(parts[i]));
122         }
123         return sb.toString();
124     }
125 
126 
127     /**
128      * @param input "aCamelCaseString"
129      * @return "A_CAMEL_CASE_STRING"
130      */
camelCaseToScreaming(String input)131     public static String camelCaseToScreaming(String input) {
132         if (input.isEmpty()) {
133             return "";
134         }
135         StringBuilder scream = new StringBuilder(input.substring(0, 1).toUpperCase());
136         for (char c : input.substring(1).toCharArray()) {
137             if (Character.isUpperCase(c)) {
138                 scream.append("_");
139             }
140             scream.append(Character.toUpperCase(c));
141         }
142         return scream.toString();
143     }
144 
145     /**
146      * Return the next word of the string, in other words it stops when a space is encountered.
147      */
nextWord(String string)148     public static String nextWord(String string) {
149         int index = 0;
150         while (index < string.length() && !Character.isWhitespace(string.charAt(index))) {
151             index++;
152         }
153         return string.substring(0, index);
154     }
155 
156     /**
157      * Make an indent by appending indentLevel tab characters to the builder.
158      */
indent(StringBuilder builder, int indentLevel)159     public static StringBuilder indent(StringBuilder builder, int indentLevel) {
160         for (int i = 0; i < indentLevel; i++) {
161             builder.append("\t");
162         }
163         return builder;
164     }
165 
166     /**
167      * Capitalizes the first character in the string.
168      */
capitalize(String s)169     public static String capitalize(String s) {
170         return stringTransformer(s, "capitalize", String::toUpperCase);
171     }
172 
173     /**
174      * Lower-cases the first character in the string.
175      */
decapitalize(String s)176     public static String decapitalize(String s) {
177         return stringTransformer(s, "decapitalize", String::toLowerCase);
178     }
179 
stringTransformer(String s, String operationDescription, Function<String, String> transformation)180     private static String stringTransformer(String s, String operationDescription, Function<String, String> transformation) {
181         if (s.isEmpty()) {
182             throw new IllegalArgumentException(String.format("You cannot %s an empty string", operationDescription));
183         }
184         return transformation.apply(s.substring(0, 1)) +
185                 s.substring(1);
186     }
187 
188     /**
189      * @return true if the value is null, an empty Optional, or an empty String.
190      */
valueIsNullOrEmpty(Object value)191     public static boolean valueIsNullOrEmpty(Object value) {
192         if (value == null) {
193             return true;
194         }
195         if (value instanceof Optional) {
196             if (((Optional) value).isPresent()) {
197                 value = ((Optional) value).get();
198             } else {
199                 return true;
200             }
201         }
202         if (value instanceof Collection) {
203             if (((Collection) value).isEmpty()) {
204                 return true;
205             }
206         }
207         return false;
208     }
209 
valueIsNullOrEmptyStringOrOptional(Object value)210     public static boolean valueIsNullOrEmptyStringOrOptional(Object value) {
211         if (value == null) {
212             return true;
213         }
214         if (value instanceof Optional) {
215             if (((Optional) value).isPresent()) {
216                 value = ((Optional) value).get();
217             } else {
218                 return true;
219             }
220         }
221         return false;
222     }
223 
224     /**
225      * Like {@link List#set(int, Object)} at {@link List#indexOf(Object)}, but using ==, not equals.
226      */
replaceElementByObjectIdentity(List<E> list, E oldObject, E newObject)227     public static <E> void replaceElementByObjectIdentity(List<E> list, E oldObject, E newObject) {
228         int index = indexOfElementByObjectIdentity(list, oldObject);
229         if (index == -1) {
230             return;
231         }
232         list.set(index, newObject);
233     }
234 
235     /**
236      * Like {@link List#remove(Object)}, but using ==, not equals.
237      */
removeElementByObjectIdentity(List<E> list, E o)238     public static <E> void removeElementByObjectIdentity(List<E> list, E o) {
239         int index = indexOfElementByObjectIdentity(list, o);
240         if (index == -1) {
241             return;
242         }
243         list.remove(index);
244     }
245 
246     /**
247      * Like {@link List#indexOf(Object)}, but using ==, not equals.
248      */
indexOfElementByObjectIdentity(List<E> list, E o)249     public static <E> int indexOfElementByObjectIdentity(List<E> list, E o) {
250         for (int i = 0; i < list.size(); i++) {
251             Object listO = list.get(i);
252             if (o == listO) {
253                 return i;
254             }
255         }
256         return -1;
257     }
258 
259     /**
260      * @return a set of the items.
261      */
set(T... items)262     public static <T> Set<T> set(T... items) {
263         return new HashSet<>(asList(items));
264     }
265 
266     /**
267      * @return content with all kinds of EOL characters replaced by endOfLineCharacter
268      */
normalizeEolInTextBlock(String content, String endOfLineCharacter)269     public static String normalizeEolInTextBlock(String content, String endOfLineCharacter) {
270         return content
271                 .replaceAll("\\R", endOfLineCharacter);
272     }
273 
274     /**
275      * @return the filename with the last "." and everything following it removed.
276      */
removeFileExtension(String filename)277     public static String removeFileExtension(String filename) {
278         int extensionIndex = filename.lastIndexOf(".");
279         if (extensionIndex == -1)
280             return filename;
281 
282         return filename.substring(0, extensionIndex);
283     }
284 
285     /**
286      * Like {@link String#trim()}, but only the trailing spaces.
287      */
trimTrailingSpaces(String line)288     public static String trimTrailingSpaces(String line) {
289         while (line.length() > 0 && line.charAt(line.length() - 1) <= 0x20) {
290             line = line.substring(0, line.length() - 1);
291         }
292         return line;
293     }
294 
295 }
296