View Javadoc
1   /*
2    * Copyright 2012-2022 Bloomreach
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.onehippo.forge.utilities.commons;
18  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.Collection;
22  import java.util.HashMap;
23  import java.util.List;
24  import java.util.Map;
25  import java.util.regex.Matcher;
26  import java.util.regex.Pattern;
27  
28  import com.google.common.base.Joiner;
29  
30  import org.slf4j.Logger;
31  import org.slf4j.LoggerFactory;
32  
33  /**
34   * HippoUtil
35   */
36  public final class HippoUtil {
37      @SuppressWarnings("unused")
38      private static Logger log = LoggerFactory.getLogger(HippoUtil.class);
39  
40      /**
41       * Private constructor preventing instantiation.
42       */
43      private HippoUtil() {
44      }
45  
46      /**
47       * Map from mime type to common file extension, e.g. "application/pdf" to "pdf".
48       */
49      public static final Map<String, String> MIME_TYPE_TO_EXTENSION_MAP =
50          new HashMap<String , String>() {
51              private static final long serialVersionUID = -3566373789286953339L;
52          {
53              put("text/plain",                    "txt");
54              put("text/html",                     "html");
55              put("application/pdf",               "pdf");
56              put("application/zip",               "zip");
57              put("application/msword",            "doc");
58              put("application/vnd.ms-excel",      "xls");
59              put("application/vnd.ms-powerpoint", "ppt");
60              put("application/vnd.openxmlformats-officedocument.wordprocessingml.document",   "docx");
61              put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",         "xlsx");
62              put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
63              put("application/vnd.oasis.opendocument.text",         "odt");
64              put("application/vnd.oasis.opendocument.graphics",     "odg");
65              put("application/vnd.oasis.opendocument.spreadsheet",  "ods");
66              put("application/vnd.oasis.opendocument.presentation", "odp");
67              put("application/vnd.oasis.opendocument.graphics",     "odg");
68              put("application/vnd.oasis.opendocument.chart",        "odc");
69              put("application/vnd.oasis.opendocument.formula",      "odf");
70              put("application/vnd.oasis.opendocument.image",        "odi");
71              put("application/vnd.oasis.opendocument.text-master",  "odm");
72          }};
73  
74      /**
75       * A String array with length zero.
76       */
77      public static final String[] EMPTY_STRING_ARRAY = new String[0];
78  
79      private static final String DEFAULT_APPEND_TEXT = " ...";
80  
81      /**
82       * Abbreviate a text to _approximately_ some number of characters, trying to
83       * find a nice word end and then appending some string (defaulting to three dots).
84       */
85      public static String abbreviateText(final String text, final int numberOfCharacters, final String appendText) {
86  
87          int nrChars = numberOfCharacters;
88  
89          if (nrChars > 0 && text != null && text.length() > nrChars) {
90  
91              // search a nice word end, _backwards_ from nrChars
92  
93              int spaceIndex = text.lastIndexOf(' ', nrChars);
94              int dotIndex = text.lastIndexOf('.', nrChars);
95              int commaIndex = text.lastIndexOf(',', nrChars);
96              int questionIndex = text.lastIndexOf('?', nrChars);
97              int exclamationIndex = text.lastIndexOf('!', nrChars);
98  
99              // set index to last space
100             nrChars = spaceIndex;
101 
102             if (dotIndex > nrChars) {
103                 nrChars = dotIndex;
104             }
105             if (commaIndex > nrChars) {
106                 nrChars = commaIndex;
107             }
108             if (questionIndex > nrChars) {
109                 nrChars = questionIndex;
110             }
111             if (exclamationIndex > nrChars) {
112                 nrChars = exclamationIndex;
113             }
114             // final check for < 0
115             if (nrChars < 0) {
116                 nrChars = 0;
117             }
118 
119             if (appendText != null) {
120                 return text.substring(0, nrChars) + appendText;
121             }
122             else {
123                 return text.substring(0, nrChars) + DEFAULT_APPEND_TEXT;
124             }
125         }
126         return text;
127     }
128 
129     /**
130      * Abbreviate a text to _approximately_ some number of characters, trying to
131      * find a nice word end and then appending three dots.
132      */
133     public static String abbreviateText(final String text, final int numberOfCharacters) {
134         return abbreviateText(text, numberOfCharacters, null);
135     }
136 
137     /**
138      * Concatenates a collection of strings by concatenating the strings and inserting a separator in between
139      * each of them. Nulls are handled automatically and there is no separator at the end of sequence.
140      *
141      * @param strings   collection of strings (collection may contain null objects, those are ignored)
142      * @param separator the separator
143      * @return concatenated string
144      */
145     public static String concat(Collection<String> strings, String separator) {
146         StringBuilder builder = new StringBuilder();
147         Joiner.on(separator).skipNulls().appendTo(builder, strings);
148         return builder.toString();
149     }
150 
151     /**
152      * Concatenates an array of strings by concatenating the strings and inserting a separator in between
153      * each of them. Nulls are handled automatically and there is no separator at the end of sequence.
154      *
155      * @param strings   the strings
156      * @param separator the separator
157      * @return concatenated string
158      */
159     public static String concat(String[] strings, String separator) {
160         StringBuilder builder = new StringBuilder();
161         Joiner.on(separator).skipNulls().appendTo(builder, strings);
162         return builder.toString();
163     }
164 
165     /**
166      * Remove empty (length zero when trimmed) values from a list.
167      */
168     public static List<String> removeEmptyValues(final List<String> values) {
169 
170         if (values == null) {
171             return null;
172         }
173 
174         final List<String> result = new ArrayList<String>(values.size());
175         for (String value : values) {
176             if (!(value.trim().length() == 0)) {
177                 result.add(value);
178             }
179         }
180         return result;
181     }
182 
183     /**
184      * Remove empty (length zero when trimmed) values from an array.
185      */
186     public static String[] removeEmptyValues(final String[] values) {
187 
188         if (values == null) {
189             return null;
190         }
191 
192         final List<String> result = removeEmptyValues(Arrays.asList(values));
193         return result.toArray(new String[result.size()]);
194     }
195 
196     /**
197      * Replaces <strong>{@code ${variableName}}</strong> variable in a template with the replacement value provided.
198      *
199      * @param variableName     variable name
200      * @param replacementValue replacement value
201      * @param template         string which contains variable e.g
202      *                         <strong>{@code My name is ${username} and my login is ${login}}</strong>
203      * @return string (template with string replacements)
204      */
205     public static String replacePlaceHolders(final String variableName, final String replacementValue,
206             final String template) {
207         Pattern pattern = Pattern.compile("(\\$\\{" + variableName + "*\\})");
208         Matcher matcher = pattern.matcher(template);
209         StringBuffer buffer = new StringBuffer();
210         while ((matcher.find())) {
211             matcher.appendReplacement(buffer, replacementValue);
212         }
213         matcher.appendTail(buffer);
214         return buffer.toString();
215     }
216 
217     /**
218      * Simplify a genuine mime type into a simple one like "pdf", "image" or an extension like "doc".
219      */
220     public static String simplifyMimeType(final String mimeType) {
221 
222         String simplified = "";
223         if (mimeType != null) {
224 
225             final String extension = getExtensionFromMimeType(mimeType);
226             if (extension != null) {
227                 simplified = extension;
228             }
229             else if (mimeType.startsWith("image/")) {
230                 simplified = "image";
231             }
232             else if (mimeType.indexOf("pdf") > -1) {
233                 simplified = "pdf";
234             }
235         }
236 
237         return simplified;
238     }
239 
240     /**
241      * Get an extension from a mime type.
242      */
243     public static String getExtensionFromMimeType(final String mimeType) {
244 
245         if (mimeType == null) {
246             return null;
247         }
248 
249         return MIME_TYPE_TO_EXTENSION_MAP.get(mimeType);
250     }
251 
252 }