001package com.ganteater.ae.util;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.FileNotFoundException;
006import java.io.IOException;
007import java.io.InputStream;
008import java.io.StringReader;
009import java.net.MalformedURLException;
010import java.net.URL;
011import java.text.ParseException;
012import java.util.LinkedHashMap;
013import java.util.Map;
014import java.util.Map.Entry;
015import java.util.Properties;
016import java.util.Set;
017import java.util.TreeMap;
018import java.util.regex.Pattern;
019
020import org.apache.commons.io.IOUtils;
021import org.apache.commons.lang.StringUtils;
022import org.apache.commons.lang.Validate;
023import org.apache.sling.commons.json.JSONException;
024import org.apache.sling.commons.json.JSONObject;
025
026import com.ganteater.ae.util.xml.easyparser.EasyParser;
027import com.ganteater.ae.util.xml.easyparser.Node;
028
029@SuppressWarnings("deprecation")
030public class AEUtils {
031
032        public static InputStream getInputStream(String aFileName, File aBaseDir)
033                        throws FileNotFoundException, IOException, MalformedURLException {
034                InputStream theInputStream = null;
035
036                if ('/' == aFileName.charAt(0) || '\\' == aFileName.charAt(0)) {
037                        theInputStream = new FileInputStream(aFileName);
038
039                } else if (aFileName.startsWith("jar:file:")) {
040                        theInputStream = new URL(aFileName.replace('\\', '/')).openStream();
041
042                } else if (aBaseDir.toString().startsWith("jar:file:")) {
043
044                        String basePath = aBaseDir.toString();
045                        basePath = StringUtils.substringBefore(basePath, "!") + "!"
046                                        + StringUtils.substringAfter(basePath, "!").replace('\\', '/');
047                        String spec = basePath + "/" + aFileName.replace('\\', '/');
048                        theInputStream = new URL(spec).openStream();
049
050                } else {
051                        File file;
052                        boolean matchesFormat = Pattern.matches("^[a-zA-Z]:\\\\.*", aFileName);
053                        if (matchesFormat) {
054                                file = new File(aFileName);
055                        } else {
056                                file = new File(aBaseDir, aFileName);
057                        }
058                        theInputStream = new FileInputStream(file);
059
060                }
061                return theInputStream;
062        }
063
064        public static String loadResource(String fileName, File aBaseDir, String aEncode)
065                        throws IOException, ParseException {
066                Validate.notEmpty(fileName, "Request file name is empty.");
067
068                try (InputStream theInputStream = AEUtils.getInputStream(fileName, aBaseDir)) {
069                        String theEncode = aEncode;
070
071                        Node theHead = null;
072
073                        byte[] theBuffer = IOUtils.toByteArray(theInputStream);
074                        theInputStream.read(theBuffer);
075
076                        int theEndHead = 0;
077
078                        String theDocHead = new String(theBuffer, "UTF-8");
079                        if (theDocHead.indexOf("<?xml") == 0) {
080                                theEndHead = theDocHead.indexOf("?>");
081                                EasyParser theParser = new EasyParser();
082                                theHead = theParser.getObject(theDocHead.substring(0, theEndHead) + "/>");
083                                theEncode = theHead.getAttribute("encoding");
084                                theEndHead += 2;
085                        }
086
087                        if (theEncode == null)
088                                theEncode = "UTF-8";
089
090                        return new String(theBuffer, theEncode);
091                }
092
093        }
094
095        public static Map<String, String> convertStringToMap(String value) {
096                Map<String, String> theValue = null;
097                if (value != null) {
098                        Properties props = new Properties();
099                        try {
100                                Map<String, String> map2 = new LinkedHashMap<String, String>();
101                                for (Map.Entry<Object, Object> e : props.entrySet()) {
102                                        map2.put((String) e.getKey(), (String) e.getValue());
103                                }
104                                String replace = value.substring(1, value.length() - 1).replace(", ", "\n");
105                                props.load(new StringReader(replace));
106                                theValue = new TreeMap<>();
107                                Set<Entry<Object, Object>> entrySet = props.entrySet();
108                                for (Entry<Object, Object> entry : entrySet) {
109                                        theValue.put((String) entry.getKey(), (String) entry.getValue());
110                                }
111                        } catch (IOException e1) {
112                                // skip
113                        }
114                }
115
116                return theValue;
117        }
118
119        public static String format(String text) {
120                StringBuilder formatedText = new StringBuilder();
121
122                boolean jsonDetected = false;
123                for (int i = 0; i < text.length(); i++) {
124                        char charAt = text.charAt(i);
125
126                        if (charAt == '{') {
127                                jsonDetected = true;
128                        }
129                        if (!jsonDetected) {
130                                formatedText.append(charAt);
131                        } else {
132                                StringBuilder jsonBody = new StringBuilder();
133
134                                int counter = 0;
135                                for (; i < text.length(); i++) {
136                                        charAt = text.charAt(i);
137
138                                        if (charAt == '{') {
139                                                counter++;
140                                        }
141
142                                        if (charAt == '}') {
143                                                counter--;
144                                        }
145
146                                        jsonBody.append(charAt);
147
148                                        if (counter < 1) {
149                                                jsonDetected = false;
150                                                break;
151                                        }
152                                }
153
154                                int length = formatedText.toString().trim().length();
155                                formatedText.setLength(length);
156                                if (length > 0) {
157                                        formatedText.append("\n");
158                                }
159
160                                try {
161                                        formatedText.append(new JSONObject(jsonBody.toString()).toString(2));
162                                } catch (JSONException e) {
163                                        formatedText.append(jsonBody.toString());
164                                }
165                        }
166                }
167                return formatedText.toString();
168        }
169
170        public static boolean isEmpty(Object value) {
171                boolean result;
172                if (value instanceof String) {
173                        result = StringUtils.isEmpty((String) value);
174                } else if (value instanceof String[]) {
175                        result = ((String[]) value).length == 0;
176                } else {
177                        result = value == null;
178                }
179                return result;
180        }
181
182        public static String maskEmail(String text) {
183                String atSignSymbol = "@";
184                String[] terminator = new String[] { " ", "=", "\"", "'", "\t", "\n", "\r" };
185                int notMaskLength = 5;
186
187                if (StringUtils.indexOf(text, atSignSymbol) > 0) {
188                        String[] split = StringUtils.split(text, atSignSymbol);
189                        boolean skipNext = false;
190                        for (int i = 0; i < split.length; i++) {
191                                String line = split[i];
192                                int index = StringUtils.lastIndexOfAny(line, terminator);
193                                int maskLength = line.length() - index - notMaskLength;
194
195                                if (skipNext) {
196                                        skipNext = false;
197                                } else {
198                                        if (notMaskLength + maskLength <= 1) {
199                                                skipNext = true;
200                                        } else {
201                                                int curMaskLength = maskLength;
202                                                if (i < split.length - 1) {
203                                                        int startMask = index + notMaskLength + 1;
204                                                        if (startMask >= line.length()) {
205                                                                startMask = index + 1;
206                                                                curMaskLength = line.length() - startMask;
207                                                        }
208                                                        split[i] = StringUtils.substring(line, 0, startMask)
209                                                                        + StringUtils.repeat("*", curMaskLength);
210                                                } else {
211                                                        split[i] = line;
212                                                }
213                                                if (i > 0) {
214                                                        line = split[i];
215                                                        index = StringUtils.indexOfAny(line, terminator);
216                                                        if (index < 0) {
217                                                                index = line.length();
218                                                        }
219                                                        index = index - notMaskLength;
220                                                        split[i] = StringUtils.repeat("*", index)
221                                                                        + StringUtils.substring(line, index, line.length());
222                                                }
223                                        }
224                                }
225                        }
226                        text = StringUtils.join(split, atSignSymbol);
227                }
228                return text;
229        }
230
231        public static String getFullClassName(String className, String defaultPackage) {
232                if (!StringUtils.contains(className, '.')) {
233                        className = defaultPackage + "." + className;
234                }
235                return className;
236        }
237
238        public static String getPrjProperty(String name) throws IOException {
239                String result = null;
240                String propertiesFileName = "prj.properties";
241
242                try (InputStream inputStream = AEUtils.class.getClassLoader().getResourceAsStream(propertiesFileName)) {
243                        if (inputStream != null) {
244                                Properties properties = new Properties();
245                                properties.load(inputStream);
246                                result = properties.getProperty(name);
247                        }
248                        return result;
249                }
250        }
251
252        public static String loadResource(String name) throws IOException {
253                String result = null;
254
255                if (!StringUtils.startsWith(name, "/")) {
256                        name = "/" + name;
257                }
258
259                try (InputStream is = AEUtils.class.getResourceAsStream(name)) {
260                        result = IOUtils.toString(is);
261                }
262                return result;
263        }
264}