001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.tools;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
018    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
019    import com.liferay.portal.kernel.util.ArrayUtil;
020    import com.liferay.portal.kernel.util.CharPool;
021    import com.liferay.portal.kernel.util.ClassUtil;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.ListUtil;
024    import com.liferay.portal.kernel.util.PropertiesUtil;
025    import com.liferay.portal.kernel.util.PropsKeys;
026    import com.liferay.portal.kernel.util.StringBundler;
027    import com.liferay.portal.kernel.util.StringPool;
028    import com.liferay.portal.kernel.util.StringUtil;
029    import com.liferay.portal.kernel.util.Tuple;
030    import com.liferay.portal.kernel.util.Validator;
031    import com.liferay.portal.kernel.xml.Document;
032    import com.liferay.portal.kernel.xml.DocumentException;
033    import com.liferay.portal.kernel.xml.Element;
034    import com.liferay.portal.util.FileImpl;
035    import com.liferay.portal.xml.SAXReaderImpl;
036    import com.liferay.util.ContentUtil;
037    
038    import java.io.File;
039    import java.io.FileInputStream;
040    import java.io.FileNotFoundException;
041    import java.io.IOException;
042    import java.io.InputStream;
043    
044    import java.net.URL;
045    
046    import java.util.ArrayList;
047    import java.util.Arrays;
048    import java.util.Collection;
049    import java.util.Collections;
050    import java.util.HashMap;
051    import java.util.HashSet;
052    import java.util.List;
053    import java.util.Map;
054    import java.util.Properties;
055    import java.util.Set;
056    import java.util.TreeSet;
057    import java.util.regex.Matcher;
058    import java.util.regex.Pattern;
059    
060    import org.apache.tools.ant.DirectoryScanner;
061    
062    /**
063     * @author Brian Wing Shun Chan
064     * @author Igor Spasic
065     * @author Wesley Gong
066     * @author Hugo Huijser
067     */
068    public class SourceFormatter {
069    
070            public static void main(String[] args) {
071                    try {
072                            _excludes = StringUtil.split(
073                                    GetterUtil.getString(
074                                            System.getProperty("source.formatter.excludes")));
075    
076                            _portalSource = _isPortalSource();
077    
078                            _sourceFormatterHelper = new SourceFormatterHelper(false);
079    
080                            _sourceFormatterHelper.init();
081    
082                            Thread thread1 = new Thread () {
083    
084                                    @Override
085                                    public void run() {
086                                            try {
087                                                    _formatJSP();
088                                                    _formatAntXML();
089                                                    _formatDDLStructuresXML();
090                                                    _formatFriendlyURLRoutesXML();
091                                                    _formatFTL();
092                                                    _formatJS();
093                                                    _formatPortalProperties();
094                                                    _formatPortletXML();
095                                                    _formatServiceXML();
096                                                    _formatSH();
097                                                    _formatSQL();
098                                                    _formatStrutsConfigXML();
099                                                    _formatTilesDefsXML();
100                                                    _formatWebXML();
101                                            }
102                                            catch (Exception e) {
103                                                    e.printStackTrace();
104                                            }
105                                    }
106    
107                            };
108    
109                            Thread thread2 = new Thread () {
110    
111                                    @Override
112                                    public void run() {
113                                            try {
114                                                    _formatJava();
115                                            }
116                                            catch (Exception e) {
117                                                    e.printStackTrace();
118                                            }
119                                    }
120    
121                            };
122    
123                            thread1.start();
124                            thread2.start();
125    
126                            thread1.join();
127                            thread2.join();
128    
129                            _sourceFormatterHelper.close();
130                    }
131                    catch (Exception e) {
132                            e.printStackTrace();
133                    }
134            }
135    
136            public static String stripJavaImports(
137                            String content, String packageDir, String className)
138                    throws IOException {
139    
140                    Matcher matcher = _javaImportPattern.matcher(content);
141    
142                    if (!matcher.find()) {
143                            return content;
144                    }
145    
146                    String imports = matcher.group();
147    
148                    Set<String> classes = ClassUtil.getClasses(
149                            new UnsyncStringReader(content), className);
150    
151                    StringBundler sb = new StringBundler();
152    
153                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
154                            new UnsyncStringReader(imports));
155    
156                    String line = null;
157    
158                    while ((line = unsyncBufferedReader.readLine()) != null) {
159                            if (line.contains("import ")) {
160                                    int importX = line.indexOf(" ");
161                                    int importY = line.lastIndexOf(".");
162    
163                                    String importPackage = line.substring(importX + 1, importY);
164                                    String importClass = line.substring(
165                                            importY + 1, line.length() - 1);
166    
167                                    if (!packageDir.equals(importPackage)) {
168                                            if (!importClass.equals("*")) {
169                                                    if (classes.contains(importClass)) {
170                                                            sb.append(line);
171                                                            sb.append("\n");
172                                                    }
173                                            }
174                                            else {
175                                                    sb.append(line);
176                                                    sb.append("\n");
177                                            }
178                                    }
179                            }
180                    }
181    
182                    imports = _formatImports(sb.toString(), 7);
183    
184                    content =
185                            content.substring(0, matcher.start()) + imports +
186                                    content.substring(matcher.end());
187    
188                    // Ensure a blank line exists between the package and the first import
189    
190                    content = content.replaceFirst(
191                            "(?m)^[ \t]*(package .*;)\\s*^[ \t]*import", "$1\n\nimport");
192    
193                    // Ensure a blank line exists between the last import (or package if
194                    // there are no imports) and the class comment
195    
196                    content = content.replaceFirst(
197                            "(?m)^[ \t]*((?:package|import) .*;)\\s*^[ \t]*/\\*\\*",
198                            "$1\n\n/**");
199    
200                    return content;
201            }
202    
203            private static void _addJSPIncludeFileNames(
204                    String fileName, Set<String> includeFileNames) {
205    
206                    String content = _jspContents.get(fileName);
207    
208                    if (Validator.isNull(content)) {
209                            return;
210                    }
211    
212                    for (int x = 0;;) {
213                            x = content.indexOf("<%@ include file=", x);
214    
215                            if (x == -1) {
216                                    break;
217                            }
218    
219                            x = content.indexOf(StringPool.QUOTE, x);
220    
221                            if (x == -1) {
222                                    break;
223                            }
224    
225                            int y = content.indexOf(StringPool.QUOTE, x + 1);
226    
227                            if (y == -1) {
228                                    break;
229                            }
230    
231                            String includeFileName = content.substring(x + 1, y);
232    
233                            Matcher matcher = _jspIncludeFilePattern.matcher(includeFileName);
234    
235                            if (!matcher.find()) {
236                                    throw new RuntimeException(
237                                            "Invalid include " + includeFileName);
238                            }
239    
240                            String docrootPath = fileName.substring(
241                                    0, fileName.indexOf("docroot") + 7);
242    
243                            includeFileName = docrootPath + includeFileName;
244    
245                            if ((includeFileName.endsWith("jsp") ||
246                                     includeFileName.endsWith("jspf")) &&
247                                    !includeFileNames.contains(includeFileName) &&
248                                    !includeFileName.contains("html/portlet/init.jsp")) {
249    
250                                    includeFileNames.add(includeFileName);
251                            }
252    
253                            x = y;
254                    }
255            }
256    
257            private static void _addJSPReferenceFileNames(
258                    String fileName, Set<String> includeFileNames) {
259    
260                    for (Map.Entry<String, String> entry : _jspContents.entrySet()) {
261                            String referenceFileName = entry.getKey();
262                            String content = entry.getValue();
263    
264                            if (content.contains("<%@ include file=\"" + fileName) &&
265                                    !includeFileNames.contains(referenceFileName)) {
266    
267                                    includeFileNames.add(referenceFileName);
268                            }
269                    }
270            }
271    
272            private static void _addJSPUnusedImports(
273                    String fileName, List<String> importLines,
274                    List<String> unneededImports) {
275    
276                    for (String importLine : importLines) {
277                            Set<String> includeFileNames = new HashSet<String>();
278    
279                            includeFileNames.add(fileName);
280    
281                            Set<String> checkedFileNames = new HashSet<String>();
282    
283                            int x = importLine.indexOf(StringPool.QUOTE);
284                            int y = importLine.indexOf(StringPool.QUOTE, x + 1);
285    
286                            if ((x == -1) || (y == -1)) {
287                                    continue;
288                            }
289    
290                            String className = importLine.substring(x + 1, y);
291    
292                            className = className.substring(
293                                    className.lastIndexOf(StringPool.PERIOD) + 1);
294    
295                            if (!_isJSPImportRequired(
296                                            fileName, className, includeFileNames, checkedFileNames)) {
297    
298                                    unneededImports.add(importLine);
299                            }
300                    }
301            }
302    
303            private static List<String> _addParameterTypes(
304                    String line, List<String> parameterTypes) {
305    
306                    int x = line.indexOf(StringPool.OPEN_PARENTHESIS);
307    
308                    if (x != -1) {
309                            line = line.substring(x + 1);
310    
311                            if (Validator.isNull(line) ||
312                                    line.startsWith(StringPool.CLOSE_PARENTHESIS)) {
313    
314                                    return parameterTypes;
315                            }
316                    }
317    
318                    for (x = 0;;) {
319                            x = line.indexOf(StringPool.SPACE);
320    
321                            if (x == -1) {
322                                    return parameterTypes;
323                            }
324    
325                            String parameterType = line.substring(0, x);
326    
327                            if (parameterType.equals("throws")) {
328                                    return parameterTypes;
329                            }
330    
331                            if (parameterType.endsWith("...")) {
332                                    parameterType = StringUtil.replaceLast(
333                                            parameterType, "...", StringPool.BLANK);
334                            }
335    
336                            int pos = parameterType.lastIndexOf(StringPool.PERIOD);
337    
338                            if (pos != -1) {
339                                    parameterType = parameterType.substring(pos + 1);
340                            }
341    
342                            parameterTypes.add(parameterType);
343    
344                            int y = line.indexOf(StringPool.COMMA);
345                            int z = line.indexOf(StringPool.CLOSE_PARENTHESIS);
346    
347                            if ((y == -1) || ((z != -1) && (z < y))) {
348                                    return parameterTypes;
349                            }
350    
351                            line = line.substring(y + 1);
352                            line = line.trim();
353                    }
354            }
355    
356            private static void _checkIfClause(
357                    String ifClause, String fileName, int lineCount) {
358    
359                    int quoteCount = StringUtil.count(ifClause, StringPool.QUOTE);
360    
361                    if ((quoteCount % 2) == 1) {
362                            return;
363                    }
364    
365                    ifClause = _stripQuotes(ifClause);
366    
367                    if (ifClause.contains(StringPool.DOUBLE_SLASH) ||
368                            ifClause.contains("/*") || ifClause.contains("*/")) {
369    
370                            return;
371                    }
372    
373                    ifClause = _stripRedundantParentheses(ifClause);
374    
375                    ifClause = StringUtil.replace(
376                            ifClause, new String[] {"'('", "')'"},
377                            new String[] {StringPool.BLANK, StringPool.BLANK});
378    
379                    int level = 0;
380                    int max = StringUtil.count(ifClause, StringPool.OPEN_PARENTHESIS);
381                    int previousParenthesisPos = -1;
382    
383                    int[] levels = new int[max];
384    
385                    for (int i = 0; i < ifClause.length(); i++) {
386                            char c = ifClause.charAt(i);
387    
388                            if ((c == CharPool.OPEN_PARENTHESIS) ||
389                                    (c == CharPool.CLOSE_PARENTHESIS)) {
390    
391                                    if (previousParenthesisPos != -1) {
392                                            String s = ifClause.substring(
393                                                    previousParenthesisPos + 1, i);
394    
395                                            _checkMissingParentheses(s, fileName, lineCount);
396                                    }
397    
398                                    previousParenthesisPos = i;
399    
400                                    if (c == CharPool.OPEN_PARENTHESIS) {
401                                            levels[level] = i;
402    
403                                            level += 1;
404                                    }
405                                    else {
406                                            int posOpenParenthesis = levels[level - 1];
407    
408                                            if (level > 1) {
409                                                    char nextChar = ifClause.charAt(i + 1);
410                                                    char previousChar = ifClause.charAt(
411                                                            posOpenParenthesis - 1);
412    
413                                                    if (!Character.isLetterOrDigit(nextChar) &&
414                                                            (nextChar != CharPool.PERIOD) &&
415                                                            !Character.isLetterOrDigit(previousChar)) {
416    
417                                                            String s = ifClause.substring(
418                                                                    posOpenParenthesis + 1, i);
419    
420                                                            if (Validator.isNotNull(s) &&
421                                                                    !s.contains(StringPool.SPACE)) {
422    
423                                                                    _sourceFormatterHelper.printError(
424                                                                            fileName,
425                                                                            "redundant parentheses: " + fileName + " " +
426                                                                                    lineCount);
427                                                            }
428                                                    }
429    
430                                                    if ((previousChar == CharPool.OPEN_PARENTHESIS) &&
431                                                            (nextChar == CharPool.CLOSE_PARENTHESIS)) {
432    
433                                                            _sourceFormatterHelper.printError(
434                                                                    fileName,
435                                                                    "redundant parentheses: " + fileName + " " +
436                                                                            lineCount);
437                                                    }
438                                            }
439    
440                                            level -= 1;
441                                    }
442                            }
443                    }
444            }
445    
446            private static void _checkMissingParentheses(
447                    String s, String fileName, int lineCount) {
448    
449                    if (Validator.isNull(s)) {
450                            return;
451                    }
452    
453                    boolean containsAndOrOperator = (s.contains("&&") || s.contains("||"));
454    
455                    boolean containsCompareOperator =
456                            (s.contains(" == ") || s.contains(" != ") || s.contains(" < ") ||
457                             s.contains(" > ") || s.contains(" =< ") || s.contains(" => ") ||
458                             s.contains(" <= ") || s.contains(" >= "));
459    
460                    boolean containsMathOperator =
461                            (s.contains(" = ") || s.contains(" - ") || s.contains(" + ") ||
462                             s.contains(" & ") || s.contains(" % ") || s.contains(" * ") ||
463                             s.contains(" / "));
464    
465                    if (containsCompareOperator &&
466                            (containsAndOrOperator ||
467                             (containsMathOperator && !s.contains(StringPool.OPEN_BRACKET)))) {
468    
469                            _sourceFormatterHelper.printError(
470                                    fileName, "missing parentheses: " + fileName + " " + lineCount);
471                    }
472            }
473    
474            private static boolean _checkTaglibVulnerability(
475                    String jspContent, String vulnerability) {
476    
477                    int pos1 = -1;
478    
479                    do {
480                            pos1 = jspContent.indexOf(vulnerability, pos1 + 1);
481    
482                            if (pos1 != -1) {
483                                    int pos2 = jspContent.lastIndexOf(CharPool.LESS_THAN, pos1);
484    
485                                    while ((pos2 > 0) &&
486                                               (jspContent.charAt(pos2 + 1) == CharPool.PERCENT)) {
487    
488                                            pos2 = jspContent.lastIndexOf(CharPool.LESS_THAN, pos2 - 1);
489                                    }
490    
491                                    String tagContent = jspContent.substring(pos2, pos1);
492    
493                                    if (!tagContent.startsWith("<aui:") &&
494                                            !tagContent.startsWith("<liferay-portlet:") &&
495                                            !tagContent.startsWith("<liferay-util:") &&
496                                            !tagContent.startsWith("<portlet:")) {
497    
498                                            return true;
499                                    }
500                            }
501                    }
502                    while (pos1 != -1);
503    
504                    return false;
505            }
506    
507            private static void _checkXSS(String fileName, String jspContent) {
508                    Matcher matcher = _xssPattern.matcher(jspContent);
509    
510                    while (matcher.find()) {
511                            boolean xssVulnerable = false;
512    
513                            String jspVariable = matcher.group(1);
514    
515                            String anchorVulnerability = " href=\"<%= " + jspVariable + " %>";
516    
517                            if (_checkTaglibVulnerability(jspContent, anchorVulnerability)) {
518                                    xssVulnerable = true;
519                            }
520    
521                            String inputVulnerability = " value=\"<%= " + jspVariable + " %>";
522    
523                            if (_checkTaglibVulnerability(jspContent, inputVulnerability)) {
524                                    xssVulnerable = true;
525                            }
526    
527                            String inlineStringVulnerability1 = "'<%= " + jspVariable + " %>";
528    
529                            if (jspContent.contains(inlineStringVulnerability1)) {
530                                    xssVulnerable = true;
531                            }
532    
533                            String inlineStringVulnerability2 = "(\"<%= " + jspVariable + " %>";
534    
535                            if (jspContent.contains(inlineStringVulnerability2)) {
536                                    xssVulnerable = true;
537                            }
538    
539                            String inlineStringVulnerability3 = " \"<%= " + jspVariable + " %>";
540    
541                            if (jspContent.contains(inlineStringVulnerability3)) {
542                                    xssVulnerable = true;
543                            }
544    
545                            String documentIdVulnerability = ".<%= " + jspVariable + " %>";
546    
547                            if (jspContent.contains(documentIdVulnerability)) {
548                                    xssVulnerable = true;
549                            }
550    
551                            if (xssVulnerable) {
552                                    _sourceFormatterHelper.printError(
553                                            fileName, "(xss): " + fileName + " (" + jspVariable + ")");
554                            }
555                    }
556            }
557    
558            private static void _compareJavaTermNames(
559                    String fileName, String previousJavaTermName, String javaTermName,
560                    int lineCount) {
561    
562                    if (Validator.isNull(previousJavaTermName) ||
563                            Validator.isNull(javaTermName)) {
564    
565                            return;
566                    }
567    
568                    if (javaTermName.equals("_log")) {
569                            _sourceFormatterHelper.printError(
570                                    fileName, "sort: " + fileName + " " + lineCount);
571    
572                            return;
573                    }
574    
575                    if (previousJavaTermName.equals("_instance") ||
576                            previousJavaTermName.equals("_log")) {
577    
578                            return;
579                    }
580    
581                    if (javaTermName.equals("_instance")) {
582                            _sourceFormatterHelper.printError(
583                                    fileName, "sort: " + fileName + " " + lineCount);
584    
585                            return;
586                    }
587    
588                    if (previousJavaTermName.compareToIgnoreCase(javaTermName) <= 0) {
589                            return;
590                    }
591    
592                    String javaTermNameLowerCase = javaTermName.toLowerCase();
593                    String previousJavaTermNameLowerCase =
594                            previousJavaTermName.toLowerCase();
595    
596                    if (fileName.contains("persistence") &&
597                            ((previousJavaTermName.startsWith("doCount") &&
598                              javaTermName.startsWith("doCount")) ||
599                             (previousJavaTermName.startsWith("doFind") &&
600                              javaTermName.startsWith("doFind")) ||
601                             (previousJavaTermNameLowerCase.startsWith("count") &&
602                              javaTermNameLowerCase.startsWith("count")) ||
603                             (previousJavaTermNameLowerCase.startsWith("filter") &&
604                              javaTermNameLowerCase.startsWith("filter")) ||
605                             (previousJavaTermNameLowerCase.startsWith("find") &&
606                              javaTermNameLowerCase.startsWith("find")) ||
607                             (previousJavaTermNameLowerCase.startsWith("join") &&
608                              javaTermNameLowerCase.startsWith("join")))) {
609    
610                            return;
611                    }
612    
613                    _sourceFormatterHelper.printError(
614                            fileName, "sort: " + fileName + " " + lineCount);
615            }
616    
617            private static void _compareMethodParameterTypes(
618                    String fileName, List<String> previousMethodParameterTypes,
619                    List<String> methodParameterTypes, int lineCount) {
620    
621                    if (methodParameterTypes.isEmpty()) {
622                            _sourceFormatterHelper.printError(
623                                    fileName, "sort: " + fileName + " " + lineCount);
624    
625                            return;
626                    }
627    
628                    for (int i = 0; i < previousMethodParameterTypes.size(); i++) {
629                            if (methodParameterTypes.size() < (i + 1)) {
630                                    _sourceFormatterHelper.printError(
631                                            fileName, "sort: " + fileName + " " + lineCount);
632    
633                                    return;
634                            }
635    
636                            String previousParameterType = previousMethodParameterTypes.get(i);
637    
638                            if (previousParameterType.endsWith("...")) {
639                                    previousParameterType = StringUtil.replaceLast(
640                                            previousParameterType, "...", StringPool.BLANK);
641                            }
642    
643                            String parameterType = methodParameterTypes.get(i);
644    
645                            if (previousParameterType.compareToIgnoreCase(parameterType) < 0) {
646                                    return;
647                            }
648    
649                            if (previousParameterType.compareToIgnoreCase(parameterType) > 0) {
650                                    _sourceFormatterHelper.printError(
651                                            fileName, "sort: " + fileName + " " + lineCount);
652    
653                                    return;
654                            }
655    
656                            if (previousParameterType.compareTo(parameterType) > 0) {
657                                    return;
658                            }
659    
660                            if (previousParameterType.compareTo(parameterType) < 0) {
661                                    _sourceFormatterHelper.printError(
662                                            fileName, "sort: " + fileName + " " + lineCount);
663    
664                                    return;
665                            }
666                    }
667            }
668    
669            private static String _fixAntXMLProjectName(
670                            String basedir, String fileName, String content)
671                    throws IOException {
672    
673                    int x = 0;
674    
675                    if (fileName.endsWith("-ext/build.xml")) {
676                            x = fileName.indexOf("ext/");
677    
678                            if (x == -1) {
679                                    x = 0;
680                            }
681                            else {
682                                    x = x + 4;
683                            }
684                    }
685                    else if (fileName.endsWith("-hook/build.xml")) {
686                            x = fileName.indexOf("hooks/");
687    
688                            if (x == -1) {
689                                    x = 0;
690                            }
691                            else {
692                                    x = x + 6;
693                            }
694                    }
695                    else if (fileName.endsWith("-layouttpl/build.xml")) {
696                            x = fileName.indexOf("layouttpl/");
697    
698                            if (x == -1) {
699                                    x = 0;
700                            }
701                            else {
702                                    x = x + 10;
703                            }
704                    }
705                    else if (fileName.endsWith("-portlet/build.xml")) {
706                            x = fileName.indexOf("portlets/");
707    
708                            if (x == -1) {
709                                    x = 0;
710                            }
711                            else {
712                                    x = x + 9;
713                            }
714                    }
715                    else if (fileName.endsWith("-theme/build.xml")) {
716                            x = fileName.indexOf("themes/");
717    
718                            if (x == -1) {
719                                    x = 0;
720                            }
721                            else {
722                                    x = x + 7;
723                            }
724                    }
725                    else if (fileName.endsWith("-web/build.xml") &&
726                                     !fileName.endsWith("/ext-web/build.xml")) {
727    
728                            x = fileName.indexOf("webs/");
729    
730                            if (x == -1) {
731                                    x = 0;
732                            }
733                            else {
734                                    x = x + 5;
735                            }
736                    }
737                    else {
738                            return content;
739                    }
740    
741                    int y = fileName.indexOf("/", x);
742    
743                    String correctProjectElementText =
744                            "<project name=\"" + fileName.substring(x, y) + "\"";
745    
746                    if (!content.contains(correctProjectElementText)) {
747                            x = content.indexOf("<project name=\"");
748    
749                            y = content.indexOf("\"", x) + 1;
750                            y = content.indexOf("\"", y) + 1;
751    
752                            content =
753                                    content.substring(0, x) + correctProjectElementText +
754                                            content.substring(y);
755    
756                            _sourceFormatterHelper.printError(
757                                    fileName, fileName + " has an incorrect project name");
758    
759                            _fileUtil.write(basedir + fileName, content);
760                    }
761    
762                    return content;
763            }
764    
765            private static String _fixDataAccessConnection(
766                    String className, String content) {
767    
768                    int x = content.indexOf("package ");
769    
770                    int y = content.indexOf(CharPool.SEMICOLON, x);
771    
772                    if ((x == -1) || (y == -1)) {
773                            return content;
774                    }
775    
776                    String packageName = content.substring(x + 8, y);
777    
778                    if (!packageName.startsWith("com.liferay.portal.kernel.upgrade") &&
779                            !packageName.startsWith("com.liferay.portal.kernel.verify") &&
780                            !packageName.startsWith("com.liferay.portal.upgrade") &&
781                            !packageName.startsWith("com.liferay.portal.verify")) {
782    
783                            return content;
784                    }
785    
786                    content = StringUtil.replace(
787                            content, "DataAccess.getConnection",
788                            "DataAccess.getUpgradeOptimizedConnection");
789    
790                    return content;
791            }
792    
793            private static void _formatAntXML() throws DocumentException, IOException {
794                    String basedir = "./";
795    
796                    DirectoryScanner directoryScanner = new DirectoryScanner();
797    
798                    directoryScanner.setBasedir(basedir);
799                    directoryScanner.setIncludes(new String[] {"**\\b*.xml"});
800                    directoryScanner.setExcludes(new String[] {"**\\tools\\**"});
801    
802                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
803                            directoryScanner);
804    
805                    for (String fileName : fileNames) {
806                            File file = new File(basedir + fileName);
807    
808                            String content = _fileUtil.read(file);
809    
810                            String newContent = _trimContent(content);
811    
812                            newContent = _fixAntXMLProjectName(basedir, fileName, newContent);
813    
814                            Document document = _saxReaderUtil.read(newContent);
815    
816                            Element rootElement = document.getRootElement();
817    
818                            String previousName = StringPool.BLANK;
819    
820                            List<Element> targetElements = rootElement.elements("target");
821    
822                            for (Element targetElement : targetElements) {
823                                    String name = targetElement.attributeValue("name");
824    
825                                    if (name.equals("Test")) {
826                                            name = name.toLowerCase();
827                                    }
828    
829                                    if (name.compareTo(previousName) < -1) {
830                                            _sourceFormatterHelper.printError(
831                                                    fileName,
832                                                    fileName + " has an unordered target " + name);
833    
834                                            break;
835                                    }
836    
837                                    previousName = name;
838                            }
839    
840                            if ((newContent != null) && !content.equals(newContent)) {
841                                    _fileUtil.write(file, newContent);
842    
843                                    _sourceFormatterHelper.printError(fileName, file);
844                            }
845                    }
846            }
847    
848            private static void _formatDDLStructuresXML()
849                    throws DocumentException, IOException {
850    
851                    String basedir =
852                            "./portal-impl/src/com/liferay/portal/events/dependencies/";
853    
854                    if (!_fileUtil.exists(basedir)) {
855                            return;
856                    }
857    
858                    DirectoryScanner directoryScanner = new DirectoryScanner();
859    
860                    directoryScanner.setBasedir(basedir);
861                    directoryScanner.setIncludes(new String[] {"**\\*structures.xml"});
862    
863                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
864                            directoryScanner);
865    
866                    for (String fileName : fileNames) {
867                            File file = new File(basedir + fileName);
868    
869                            String content = _fileUtil.read(file);
870    
871                            String newContent = _trimContent(content);
872    
873                            newContent = _formatDDLStructuresXML(content);
874    
875                            if ((newContent != null) && !content.equals(newContent)) {
876                                    _fileUtil.write(file, newContent);
877    
878                                    _sourceFormatterHelper.printError(fileName, file);
879                            }
880                    }
881            }
882    
883            private static String _formatDDLStructuresXML(String content)
884                    throws DocumentException, IOException {
885    
886                    Document document = _saxReaderUtil.read(content);
887    
888                    Element rootElement = document.getRootElement();
889    
890                    rootElement.sortAttributes(true);
891    
892                    rootElement.sortElementsByChildElement("structure", "name");
893    
894                    List<Element> structureElements = rootElement.elements("structure");
895    
896                    for (Element structureElement : structureElements) {
897                            Element structureRootElement = structureElement.element("root");
898    
899                            structureRootElement.sortElementsByAttribute(
900                                    "dynamic-element", "name");
901    
902                            List<Element> dynamicElementElements =
903                                    structureRootElement.elements("dynamic-element");
904    
905                            for (Element dynamicElementElement : dynamicElementElements) {
906                                    Element metaDataElement = dynamicElementElement.element(
907                                            "meta-data");
908    
909                                    metaDataElement.sortElementsByAttribute("entry", "name");
910                            }
911                    }
912    
913                    return document.formattedString();
914            }
915    
916            private static void _formatFriendlyURLRoutesXML()
917                    throws DocumentException, IOException {
918    
919                    String basedir = "./";
920    
921                    DirectoryScanner directoryScanner = new DirectoryScanner();
922    
923                    directoryScanner.setBasedir(basedir);
924                    directoryScanner.setIncludes(new String[] {"**\\*routes.xml"});
925                    directoryScanner.setExcludes(
926                            new String[] {"**\\classes\\**", "**\\bin\\**"});
927    
928                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
929                            directoryScanner);
930    
931                    for (String fileName : fileNames) {
932                            File file = new File(basedir + fileName);
933    
934                            String content = _fileUtil.read(file);
935    
936                            if (content.contains("<!-- SourceFormatter.Ignore -->")) {
937                                    continue;
938                            }
939    
940                            String newContent = _trimContent(content);
941    
942                            newContent = _formatFriendlyURLRoutesXML(content);
943    
944                            if ((newContent != null) && !content.equals(newContent)) {
945                                    _fileUtil.write(file, newContent);
946    
947                                    _sourceFormatterHelper.printError(fileName, file);
948                            }
949                    }
950            }
951    
952            private static String _formatFriendlyURLRoutesXML(String content)
953                    throws DocumentException {
954    
955                    Document document = _saxReaderUtil.read(content);
956    
957                    Element rootElement = document.getRootElement();
958    
959                    List<ComparableRoute> comparableRoutes =
960                            new ArrayList<ComparableRoute>();
961    
962                    for (Element routeElement : rootElement.elements("route")) {
963                            String pattern = routeElement.elementText("pattern");
964    
965                            ComparableRoute comparableRoute = new ComparableRoute(pattern);
966    
967                            for (Element generatedParameterElement :
968                                            routeElement.elements("generated-parameter")) {
969    
970                                    String name = generatedParameterElement.attributeValue("name");
971                                    String value = generatedParameterElement.getText();
972    
973                                    comparableRoute.addGeneratedParameter(name, value);
974                            }
975    
976                            for (Element ignoredParameterElement :
977                                            routeElement.elements("ignored-parameter")) {
978    
979                                    String name = ignoredParameterElement.attributeValue("name");
980    
981                                    comparableRoute.addIgnoredParameter(name);
982                            }
983    
984                            for (Element implicitParameterElement :
985                                            routeElement.elements("implicit-parameter")) {
986    
987                                    String name = implicitParameterElement.attributeValue("name");
988                                    String value = implicitParameterElement.getText();
989    
990                                    comparableRoute.addImplicitParameter(name, value);
991                            }
992    
993                            for (Element overriddenParameterElement :
994                                            routeElement.elements("overridden-parameter")) {
995    
996                                    String name = overriddenParameterElement.attributeValue("name");
997                                    String value = overriddenParameterElement.getText();
998    
999                                    comparableRoute.addOverriddenParameter(name, value);
1000                            }
1001    
1002                            comparableRoutes.add(comparableRoute);
1003                    }
1004    
1005                    Collections.sort(comparableRoutes);
1006    
1007                    StringBundler sb = new StringBundler();
1008    
1009                    sb.append("<?xml version=\"1.0\"?>\n");
1010                    sb.append("<!DOCTYPE routes PUBLIC \"-//Liferay//DTD Friendly URL ");
1011                    sb.append("Routes 6.2.0//EN\" \"http://www.liferay.com/dtd/");
1012                    sb.append("liferay-friendly-url-routes_6_2_0.dtd\">\n\n<routes>\n");
1013    
1014                    for (ComparableRoute comparableRoute : comparableRoutes) {
1015                            sb.append("\t<route>\n");
1016                            sb.append("\t\t<pattern>");
1017                            sb.append(comparableRoute.getPattern());
1018                            sb.append("</pattern>\n");
1019    
1020                            Map<String, String> generatedParameters =
1021                                    comparableRoute.getGeneratedParameters();
1022    
1023                            for (Map.Entry<String, String> entry :
1024                                            generatedParameters.entrySet()) {
1025    
1026                                    sb.append("\t\t<generated-parameter name=\"");
1027                                    sb.append(entry.getKey());
1028                                    sb.append("\">");
1029                                    sb.append(entry.getValue());
1030                                    sb.append("</generated-parameter>\n");
1031                            }
1032    
1033                            Set<String> ignoredParameters =
1034                                    comparableRoute.getIgnoredParameters();
1035    
1036                            for (String entry : ignoredParameters) {
1037                                    sb.append("\t\t<ignored-parameter name=\"");
1038                                    sb.append(entry);
1039                                    sb.append("\" />\n");
1040                            }
1041    
1042                            Map<String, String> implicitParameters =
1043                                    comparableRoute.getImplicitParameters();
1044    
1045                            for (Map.Entry<String, String> entry :
1046                                            implicitParameters.entrySet()) {
1047    
1048                                    sb.append("\t\t<implicit-parameter name=\"");
1049                                    sb.append(entry.getKey());
1050                                    sb.append("\">");
1051                                    sb.append(entry.getValue());
1052                                    sb.append("</implicit-parameter>\n");
1053                            }
1054    
1055                            Map<String, String> overriddenParameters =
1056                                    comparableRoute.getOverriddenParameters();
1057    
1058                            for (Map.Entry<String, String> entry :
1059                                            overriddenParameters.entrySet()) {
1060    
1061                                    sb.append("\t\t<overridden-parameter name=\"");
1062                                    sb.append(entry.getKey());
1063                                    sb.append("\">");
1064                                    sb.append(entry.getValue());
1065                                    sb.append("</overridden-parameter>\n");
1066                            }
1067    
1068                            sb.append("\t</route>\n");
1069                    }
1070    
1071                    sb.append("</routes>");
1072    
1073                    return sb.toString();
1074            }
1075    
1076            private static void _formatFTL() throws IOException {
1077                    String basedir = "./";
1078    
1079                    DirectoryScanner directoryScanner = new DirectoryScanner();
1080    
1081                    directoryScanner.setBasedir(basedir);
1082                    directoryScanner.setIncludes(new String[] {"**\\*.ftl"});
1083                    directoryScanner.setExcludes(
1084                            new String[] {
1085                                    "**\\journal\\dependencies\\template.ftl",
1086                                    "**\\servicebuilder\\dependencies\\props.ftl"
1087                            }
1088                    );
1089    
1090                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
1091                            directoryScanner);
1092    
1093                    for (String fileName : fileNames) {
1094                            File file = new File(basedir + fileName);
1095    
1096                            String content = _fileUtil.read(file);
1097    
1098                            String newContent = _trimContent(content);
1099    
1100                            if ((newContent != null) && !content.equals(newContent)) {
1101                                    _fileUtil.write(file, newContent);
1102    
1103                                    _sourceFormatterHelper.printError(fileName, file);
1104                            }
1105                    }
1106            }
1107    
1108            private static String _formatImports(String imports, int classStartPos)
1109                    throws IOException {
1110    
1111                    if (imports.contains("/*") || imports.contains("*/") ||
1112                            imports.contains("//")) {
1113    
1114                            return imports + "\n";
1115                    }
1116    
1117                    List<String> importsList = new ArrayList<String>();
1118    
1119                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
1120                            new UnsyncStringReader(imports));
1121    
1122                    String line = null;
1123    
1124                    while ((line = unsyncBufferedReader.readLine()) != null) {
1125                            if ((line.contains("import=") || line.contains("import ")) &&
1126                                    !importsList.contains(line)) {
1127    
1128                                    importsList.add(line);
1129                            }
1130                    }
1131    
1132                    importsList = ListUtil.sort(importsList);
1133    
1134                    StringBundler sb = new StringBundler();
1135    
1136                    String temp = null;
1137    
1138                    for (int i = 0; i < importsList.size(); i++) {
1139                            String s = importsList.get(i);
1140    
1141                            int pos = s.indexOf(".");
1142    
1143                            pos = s.indexOf(".", pos + 1);
1144    
1145                            if (pos == -1) {
1146                                    pos = s.indexOf(".");
1147                            }
1148    
1149                            String packageLevel = s.substring(classStartPos, pos);
1150    
1151                            if ((i != 0) && !packageLevel.equals(temp)) {
1152                                    sb.append("\n");
1153                            }
1154    
1155                            temp = packageLevel;
1156    
1157                            sb.append(s);
1158                            sb.append("\n");
1159                    }
1160    
1161                    return sb.toString();
1162            }
1163    
1164            private static void _formatJava() throws IOException {
1165                    String copyright = _getCopyright();
1166                    String oldCopyright = _getOldCopyright();
1167    
1168                    boolean portalJavaFiles = true;
1169    
1170                    Collection<String> fileNames = null;
1171    
1172                    if (_portalSource) {
1173                            fileNames = _getPortalJavaFiles();
1174    
1175                            _javaTermAlphabetizeExclusionsProperties =
1176                                    _getPortalExclusionsProperties(
1177                                            "source_formatter_javaterm_alphabetize_exclusions." +
1178                                                    "properties");
1179                            _lineLengthExclusionsProperties = _getPortalExclusionsProperties(
1180                                    "source_formatter_line_length_exclusions.properties");
1181                    }
1182                    else {
1183                            portalJavaFiles = false;
1184    
1185                            fileNames = _getPluginJavaFiles();
1186    
1187                            _javaTermAlphabetizeExclusionsProperties =
1188                                    _getPluginExclusionsProperties(
1189                                            "source_formatter_javaterm_alphabetize_exclusions." +
1190                                                    "properties");
1191                            _lineLengthExclusionsProperties = _getPluginExclusionsProperties(
1192                                    "source_formatter_line_length_exclusions.properties");
1193                    }
1194    
1195                    for (String fileName : fileNames) {
1196                            File file = new File(fileName);
1197    
1198                            String content = _fileUtil.read(file);
1199    
1200                            if (_isGenerated(content)) {
1201                                    continue;
1202                            }
1203    
1204                            String className = file.getName();
1205    
1206                            className = className.substring(0, className.length() - 5);
1207    
1208                            String packagePath = fileName;
1209    
1210                            int packagePathX = packagePath.indexOf(
1211                                    File.separator + "src" + File.separator);
1212                            int packagePathY = packagePath.lastIndexOf(File.separator);
1213    
1214                            if ((packagePathX + 5) >= packagePathY) {
1215                                    packagePath = StringPool.BLANK;
1216                            }
1217                            else {
1218                                    packagePath = packagePath.substring(
1219                                            packagePathX + 5, packagePathY);
1220                            }
1221    
1222                            packagePath = StringUtil.replace(
1223                                    packagePath, File.separator, StringPool.PERIOD);
1224    
1225                            if (packagePath.endsWith(".model")) {
1226                                    if (content.contains("extends " + className + "Model")) {
1227                                            continue;
1228                                    }
1229                            }
1230    
1231                            String newContent = content;
1232    
1233                            if (newContent.contains("$\n */")) {
1234                                    _sourceFormatterHelper.printError(fileName, "*: " + fileName);
1235    
1236                                    newContent = StringUtil.replace(
1237                                            newContent, "$\n */", "$\n *\n */");
1238                            }
1239    
1240                            if ((oldCopyright != null) && newContent.contains(oldCopyright)) {
1241                                    newContent = StringUtil.replace(
1242                                            newContent, oldCopyright, copyright);
1243    
1244                                    _sourceFormatterHelper.printError(
1245                                            fileName, "old (c): " + fileName);
1246                            }
1247    
1248                            if (!newContent.contains(copyright)) {
1249                                    String customCopyright = _getCustomCopyright(file);
1250    
1251                                    if (Validator.isNull(customCopyright) ||
1252                                            !newContent.contains(customCopyright)) {
1253    
1254                                            _sourceFormatterHelper.printError(
1255                                                    fileName, "(c): " + fileName);
1256                                    }
1257                            }
1258    
1259                            if (newContent.contains(className + ".java.html")) {
1260                                    _sourceFormatterHelper.printError(
1261                                            fileName, "Java2HTML: " + fileName);
1262                            }
1263    
1264                            if (newContent.contains(" * @author Raymond Aug") &&
1265                                    !newContent.contains(" * @author Raymond Aug\u00e9")) {
1266    
1267                                    newContent = newContent.replaceFirst(
1268                                            "Raymond Aug.++", "Raymond Aug\u00e9");
1269    
1270                                    _sourceFormatterHelper.printError(
1271                                            fileName, "UTF-8: " + fileName);
1272                            }
1273    
1274                            newContent = _fixDataAccessConnection(className, newContent);
1275    
1276                            newContent = StringUtil.replace(
1277                                    newContent,
1278                                    new String[] {
1279                                            "com.liferay.portal.PortalException",
1280                                            "com.liferay.portal.SystemException",
1281                                            "com.liferay.util.LocalizationUtil",
1282                                            "private static final Log _log"
1283                                    },
1284                                    new String[] {
1285                                            "com.liferay.portal.kernel.exception.PortalException",
1286                                            "com.liferay.portal.kernel.exception.SystemException",
1287                                            "com.liferay.portal.kernel.util.LocalizationUtil",
1288                                            "private static Log _log"
1289                                    });
1290    
1291                            newContent = stripJavaImports(newContent, packagePath, className);
1292    
1293                            newContent = StringUtil.replace(
1294                                    newContent,
1295                                    new String[] {
1296                                            ";\n/**", "\t/*\n\t *", "else{", "if(", "for(", "while(",
1297                                            "List <", "){\n", "]{\n", "\n\n\n"
1298                                    },
1299                                    new String[] {
1300                                            ";\n\n/**", "\t/**\n\t *", "else {", "if (", "for (",
1301                                            "while (", "List<", ") {\n", "] {\n", "\n\n"
1302                                    });
1303    
1304                            if (newContent.contains("*/\npackage ")) {
1305                                    _sourceFormatterHelper.printError(
1306                                            fileName, "package: " + fileName);
1307                            }
1308    
1309                            if (!newContent.endsWith("\n\n}") && !newContent.endsWith("{\n}")) {
1310                                    _sourceFormatterHelper.printError(fileName, "}: " + fileName);
1311                            }
1312    
1313                            if (portalJavaFiles && !className.equals("BaseServiceImpl") &&
1314                                    className.endsWith("ServiceImpl") &&
1315                                    newContent.contains("ServiceUtil.")) {
1316    
1317                                    _sourceFormatterHelper.printError(
1318                                            fileName, "ServiceUtil: " + fileName);
1319                            }
1320    
1321                            if (!className.equals("DeepNamedValueScanner") &&
1322                                    !className.equals("ProxyUtil") &&
1323                                    newContent.contains("import java.lang.reflect.Proxy;")) {
1324    
1325                                    _sourceFormatterHelper.printError(
1326                                            fileName, "Proxy: " + fileName);
1327                            }
1328    
1329                            // LPS-28266
1330    
1331                            for (int pos1 = -1;;) {
1332                                    pos1 = newContent.indexOf(StringPool.TAB + "try {", pos1 + 1);
1333    
1334                                    if (pos1 == -1) {
1335                                            break;
1336                                    }
1337    
1338                                    int pos2 = newContent.indexOf(
1339                                            StringPool.TAB + "try {", pos1 + 1);
1340                                    int pos3 = newContent.indexOf("\"select count(", pos1);
1341    
1342                                    if ((pos2 != -1) && (pos3 != -1) && (pos2 < pos3)) {
1343                                            continue;
1344                                    }
1345    
1346                                    int pos4 = newContent.indexOf("rs.getLong(1)", pos1);
1347                                    int pos5 = newContent.indexOf(
1348                                            StringPool.TAB + "finally {", pos1);
1349    
1350                                    if ((pos3 == -1) || (pos4 == -1) || (pos5 == -1)) {
1351                                            break;
1352                                    }
1353    
1354                                    if ((pos3 < pos4) && (pos4 < pos5)) {
1355                                            _sourceFormatterHelper.printError(
1356                                                    fileName, "Use getInt(1) for count: " + fileName);
1357                                    }
1358                            }
1359    
1360                            String oldContent = newContent;
1361    
1362                            for (;;) {
1363                                    newContent = _formatJava(fileName, oldContent);
1364    
1365                                    if (oldContent.equals(newContent)) {
1366                                            break;
1367                                    }
1368    
1369                                    oldContent = newContent;
1370                            }
1371    
1372                            if ((newContent != null) && !content.equals(newContent)) {
1373                                    _fileUtil.write(file, newContent);
1374    
1375                                    _sourceFormatterHelper.printError(fileName, file);
1376                            }
1377                    }
1378            }
1379    
1380            private static String _formatJava(String fileName, String content)
1381                    throws IOException {
1382    
1383                    StringBundler sb = new StringBundler();
1384    
1385                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
1386                            new UnsyncStringReader(content));
1387    
1388                    int lineCount = 0;
1389    
1390                    String line = null;
1391    
1392                    String previousLine = StringPool.BLANK;
1393    
1394                    int lineToSkipIfEmpty = 0;
1395    
1396                    String javaTermName = null;
1397                    int javaTermType = 0;
1398    
1399                    String previousJavaTermName = null;
1400                    int previousJavaTermType = 0;
1401    
1402                    List<String> parameterTypes = new ArrayList<String>();
1403                    List<String> previousParameterTypes = null;
1404    
1405                    boolean hasSameConstructorOrMethodName = false;
1406                    boolean readParameterTypes = false;
1407    
1408                    String ifClause = StringPool.BLANK;
1409    
1410                    String packageName = StringPool.BLANK;
1411    
1412                    while ((line = unsyncBufferedReader.readLine()) != null) {
1413                            lineCount++;
1414    
1415                            line = _trimLine(line);
1416    
1417                            line = StringUtil.replace(
1418                                    line,
1419                                    new String[] {
1420                                            "* Copyright (c) 2000-2011 Liferay, Inc."
1421                                    },
1422                                    new String[] {
1423                                            "* Copyright (c) 2000-2012 Liferay, Inc."
1424                                    });
1425    
1426                            if (line.startsWith("package ")) {
1427                                    packageName = line.substring(8, line.length() - 1);
1428                            }
1429    
1430                            if (line.startsWith("import ")) {
1431                                    int pos = line.lastIndexOf(StringPool.PERIOD);
1432    
1433                                    if (pos != -1) {
1434                                            String importPackageName = line.substring(7, pos);
1435    
1436                                            if (importPackageName.equals(packageName)) {
1437                                                    continue;
1438                                            }
1439                                    }
1440                            }
1441    
1442                            if (line.contains(StringPool.TAB + "for (") && line.contains(":") &&
1443                                    !line.contains(" :")) {
1444    
1445                                    line = StringUtil.replace(line, ":" , " :");
1446                            }
1447    
1448                            line = _replacePrimitiveWrapperInstantiation(
1449                                    fileName, line, lineCount);
1450    
1451                            String trimmedLine = StringUtil.trimLeading(line);
1452    
1453                            if (trimmedLine.startsWith(StringPool.EQUAL)) {
1454                                    _sourceFormatterHelper.printError(
1455                                            fileName, "equal: " + fileName + " " + lineCount);
1456                            }
1457    
1458                            if (!trimmedLine.equals("{") && line.endsWith("{") &&
1459                                    !line.endsWith(" {")) {
1460    
1461                                    line = StringUtil.replaceLast(line, "{", " {");
1462                            }
1463    
1464                            line = _sortExceptions(line);
1465    
1466                            if (trimmedLine.startsWith("if (") ||
1467                                    trimmedLine.startsWith("else if (") ||
1468                                    trimmedLine.startsWith("while (") ||
1469                                    Validator.isNotNull(ifClause)) {
1470    
1471                                    if (Validator.isNull(ifClause) ||
1472                                            ifClause.endsWith(StringPool.OPEN_PARENTHESIS)) {
1473    
1474                                            ifClause = ifClause + trimmedLine;
1475                                    }
1476                                    else {
1477                                            ifClause = ifClause + StringPool.SPACE + trimmedLine;
1478                                    }
1479    
1480                                    if (ifClause.endsWith(") {")) {
1481                                            _checkIfClause(ifClause, fileName, lineCount);
1482    
1483                                            ifClause = StringPool.BLANK;
1484                                    }
1485                            }
1486    
1487                            String excluded = null;
1488    
1489                            if (_javaTermAlphabetizeExclusionsProperties != null) {
1490                                    excluded = _javaTermAlphabetizeExclusionsProperties.getProperty(
1491                                            StringUtil.replace(
1492                                                    fileName, "\\", "/") + StringPool.AT + lineCount);
1493    
1494                                    if (excluded == null) {
1495                                            excluded =
1496                                                    _javaTermAlphabetizeExclusionsProperties.getProperty(
1497                                                            StringUtil.replace(fileName, "\\", "/"));
1498                                    }
1499                            }
1500    
1501                            if (line.startsWith(StringPool.TAB + "private ") ||
1502                                    line.startsWith(StringPool.TAB + "protected ") ||
1503                                    line.startsWith(StringPool.TAB + "public ")) {
1504    
1505                                    hasSameConstructorOrMethodName = false;
1506    
1507                                    Tuple tuple = _getJavaTermTuple(line);
1508    
1509                                    if (tuple != null) {
1510                                            javaTermName = (String)tuple.getObject(0);
1511    
1512                                            if (Validator.isNotNull(javaTermName)) {
1513                                                    javaTermType = (Integer)tuple.getObject(1);
1514    
1515                                                    boolean isConstructorOrMethod =
1516                                                            _isInJavaTermTypeGroup(
1517                                                                    javaTermType, _TYPE_CONSTRUCTOR) ||
1518                                                            _isInJavaTermTypeGroup(javaTermType, _TYPE_METHOD);
1519    
1520                                                    if (isConstructorOrMethod) {
1521                                                            readParameterTypes = true;
1522                                                    }
1523    
1524                                                    if (excluded == null) {
1525                                                            if (_isInJavaTermTypeGroup(
1526                                                                            javaTermType, _TYPE_VARIABLE_NOT_FINAL)) {
1527    
1528                                                                    char firstChar = javaTermName.charAt(0);
1529    
1530                                                                    if (firstChar == CharPool.UNDERLINE) {
1531                                                                            firstChar = javaTermName.charAt(1);
1532                                                                    }
1533    
1534                                                                    if (Character.isUpperCase(firstChar)) {
1535                                                                            _sourceFormatterHelper.printError(
1536                                                                                    fileName,
1537                                                                                    "final: " + fileName + " " + lineCount);
1538                                                                    }
1539                                                            }
1540    
1541                                                            if (Validator.isNotNull(previousJavaTermName)) {
1542                                                                    if (previousJavaTermType > javaTermType) {
1543                                                                            _sourceFormatterHelper.printError(
1544                                                                                    fileName,
1545                                                                                    "order: " + fileName + " " + lineCount);
1546                                                                    }
1547                                                                    else if (previousJavaTermType == javaTermType) {
1548                                                                            if (isConstructorOrMethod &&
1549                                                                                    previousJavaTermName.equals(
1550                                                                                            javaTermName)) {
1551    
1552                                                                                    hasSameConstructorOrMethodName = true;
1553                                                                            }
1554                                                                            else {
1555                                                                                    _compareJavaTermNames(
1556                                                                                            fileName, previousJavaTermName,
1557                                                                                            javaTermName, lineCount);
1558                                                                            }
1559                                                                    }
1560                                                            }
1561                                                    }
1562    
1563                                                    previousJavaTermName = javaTermName;
1564                                                    previousJavaTermType = javaTermType;
1565                                            }
1566                                    }
1567                            }
1568    
1569                            if (readParameterTypes) {
1570                                    parameterTypes = _addParameterTypes(
1571                                            trimmedLine, parameterTypes);
1572    
1573                                    if (trimmedLine.contains(StringPool.CLOSE_PARENTHESIS)) {
1574                                            if (hasSameConstructorOrMethodName) {
1575                                                    _compareMethodParameterTypes(
1576                                                            fileName, previousParameterTypes, parameterTypes,
1577                                                            lineCount);
1578                                            }
1579    
1580                                            readParameterTypes = false;
1581    
1582                                            previousParameterTypes = ListUtil.copy(parameterTypes);
1583    
1584                                            parameterTypes.clear();
1585                                    }
1586                            }
1587    
1588                            if (!trimmedLine.contains(StringPool.DOUBLE_SLASH) &&
1589                                    !trimmedLine.startsWith(StringPool.STAR)) {
1590    
1591                                    while (trimmedLine.contains(StringPool.TAB)) {
1592                                            line = StringUtil.replaceLast(
1593                                                    line, StringPool.TAB, StringPool.SPACE);
1594    
1595                                            trimmedLine = StringUtil.replaceLast(
1596                                                    trimmedLine, StringPool.TAB, StringPool.SPACE);
1597                                    }
1598    
1599                                    if (line.contains(StringPool.TAB + StringPool.SPACE) &&
1600                                            !previousLine.endsWith("&&") &&
1601                                            !previousLine.endsWith("||") &&
1602                                            !previousLine.contains(StringPool.TAB + "((") &&
1603                                            !previousLine.contains(StringPool.TAB + StringPool.SPACE) &&
1604                                            !previousLine.contains(StringPool.TAB + "implements ") &&
1605                                            !previousLine.contains(StringPool.TAB + "throws ")) {
1606    
1607                                            line = StringUtil.replace(
1608                                                    line, StringPool.TAB + StringPool.SPACE,
1609                                                    StringPool.TAB);
1610                                    }
1611    
1612                                    while (trimmedLine.contains(StringPool.DOUBLE_SPACE) &&
1613                                               !trimmedLine.contains(
1614                                                       StringPool.QUOTE + StringPool.DOUBLE_SPACE) &&
1615                                               !fileName.contains("Test")) {
1616    
1617                                            line = StringUtil.replaceLast(
1618                                                    line, StringPool.DOUBLE_SPACE, StringPool.SPACE);
1619    
1620                                            trimmedLine = StringUtil.replaceLast(
1621                                                    trimmedLine, StringPool.DOUBLE_SPACE, StringPool.SPACE);
1622                                    }
1623    
1624                                    if (!line.contains(StringPool.QUOTE)) {
1625                                            if ((trimmedLine.startsWith("private ") ||
1626                                                     trimmedLine.startsWith("protected ") ||
1627                                                     trimmedLine.startsWith("public ")) &&
1628                                                    line.contains(" (")) {
1629    
1630                                                    line = StringUtil.replace(line, " (", "(");
1631                                            }
1632    
1633                                            if (line.contains(" [")) {
1634                                                    line = StringUtil.replace(line, " [", "[");
1635                                            }
1636    
1637                                            for (int x = -1;;) {
1638                                                    int posComma = line.indexOf(StringPool.COMMA, x + 1);
1639                                                    int posSemicolon = line.indexOf(
1640                                                            StringPool.SEMICOLON, x + 1);
1641    
1642                                                    if ((posComma == -1) && (posSemicolon == -1)) {
1643                                                            break;
1644                                                    }
1645    
1646                                                    x = Math.min(posComma, posSemicolon);
1647    
1648                                                    if (x == -1) {
1649                                                            x = Math.max(posComma, posSemicolon);
1650                                                    }
1651    
1652                                                    if (line.length() > (x + 1)) {
1653                                                            char nextChar = line.charAt(x + 1);
1654    
1655                                                            if ((nextChar != CharPool.APOSTROPHE) &&
1656                                                                    (nextChar != CharPool.CLOSE_PARENTHESIS) &&
1657                                                                    (nextChar != CharPool.SPACE) &&
1658                                                                    (nextChar != CharPool.STAR)) {
1659    
1660                                                                    line = StringUtil.insert(
1661                                                                            line, StringPool.SPACE, x + 1);
1662                                                            }
1663                                                    }
1664    
1665                                                    if (x > 0) {
1666                                                            char previousChar = line.charAt(x - 1);
1667    
1668                                                            if (previousChar == CharPool.SPACE) {
1669                                                                    line = line.substring(0, x - 1).concat(
1670                                                                            line.substring(x));
1671                                                            }
1672                                                    }
1673                                            }
1674                                    }
1675                            }
1676    
1677                            if ((line.contains(" && ") || line.contains(" || ")) &&
1678                                    line.endsWith(StringPool.OPEN_PARENTHESIS)) {
1679    
1680                                    _sourceFormatterHelper.printError(
1681                                            fileName, "line break: " + fileName + " " + lineCount);
1682                            }
1683    
1684                            if (line.contains(StringPool.COMMA) &&
1685                                    !line.contains(StringPool.CLOSE_PARENTHESIS) &&
1686                                    !line.contains(StringPool.GREATER_THAN) &&
1687                                    !line.contains(StringPool.QUOTE) &&
1688                                    line.endsWith(StringPool.OPEN_PARENTHESIS)) {
1689    
1690                                    _sourceFormatterHelper.printError(
1691                                            fileName, "line break: " + fileName + " " + lineCount);
1692                            }
1693    
1694                            if (line.endsWith(" +") || line.endsWith(" -") ||
1695                                    line.endsWith(" *") || line.endsWith(" /")) {
1696    
1697                                    int x = line.indexOf(" = ");
1698    
1699                                    if (x != -1) {
1700                                            int y = line.indexOf(StringPool.QUOTE);
1701    
1702                                            if ((y == -1) || (x < y)) {
1703                                                    _sourceFormatterHelper.printError(
1704                                                            fileName,
1705                                                            "line break: " + fileName + " " + lineCount);
1706                                            }
1707                                    }
1708                            }
1709    
1710                            if (line.contains("    ") && !line.matches("\\s*\\*.*")) {
1711                                    if (!fileName.endsWith("StringPool.java")) {
1712                                            _sourceFormatterHelper.printError(
1713                                                    fileName, "tab: " + fileName + " " + lineCount);
1714                                    }
1715                            }
1716    
1717                            if (line.contains("  {") && !line.matches("\\s*\\*.*")) {
1718                                    _sourceFormatterHelper.printError(
1719                                            fileName, "{:" + fileName + " " + lineCount);
1720                            }
1721    
1722                            excluded = null;
1723    
1724                            if (_lineLengthExclusionsProperties != null) {
1725                                    excluded = _lineLengthExclusionsProperties.getProperty(
1726                                            StringUtil.replace(
1727                                                    fileName, "\\", "/") + StringPool.AT + lineCount);
1728    
1729                                    if (excluded == null) {
1730                                            excluded = _lineLengthExclusionsProperties.getProperty(
1731                                                    StringUtil.replace(fileName, "\\", "/"));
1732                                    }
1733                            }
1734    
1735                            Tuple combinedLines = null;
1736                            int lineLength = _getLineLength(line);
1737    
1738                            if ((excluded == null) &&
1739                                    !line.startsWith("import ") && !line.startsWith("package ") &&
1740                                    !line.matches("\\s*\\*.*")) {
1741    
1742                                    if (fileName.endsWith("Table.java") &&
1743                                            line.contains("String TABLE_SQL_CREATE = ")) {
1744                                    }
1745                                    else if (fileName.endsWith("Table.java") &&
1746                                                     line.contains("String TABLE_SQL_DROP = ")) {
1747                                    }
1748                                    else if (fileName.endsWith("Table.java") &&
1749                                                     line.contains(" index IX_")) {
1750                                    }
1751                                    else {
1752                                            if (lineLength > 80) {
1753                                                    _sourceFormatterHelper.printError(
1754                                                            fileName, "> 80: " + fileName + " " + lineCount);
1755                                            }
1756                                            else {
1757                                                    int lineTabCount = StringUtil.count(
1758                                                            line, StringPool.TAB);
1759                                                    int previousLineTabCount = StringUtil.count(
1760                                                            previousLine, StringPool.TAB);
1761    
1762                                                    if (previousLine.endsWith(StringPool.COMMA) &&
1763                                                            previousLine.contains(
1764                                                                    StringPool.OPEN_PARENTHESIS) &&
1765                                                            !previousLine.contains("for (") &&
1766                                                            (lineTabCount > previousLineTabCount)) {
1767    
1768                                                            _sourceFormatterHelper.printError(
1769                                                                    fileName,
1770                                                                    "line break: " + fileName + " " + lineCount);
1771                                                    }
1772    
1773                                                    if (Validator.isNotNull(trimmedLine) &&
1774                                                            ((previousLine.endsWith(StringPool.COLON) &&
1775                                                              previousLine.contains(StringPool.TAB + "for ")) ||
1776                                                             (previousLine.endsWith(
1777                                                                     StringPool.OPEN_PARENTHESIS) &&
1778                                                              previousLine.contains(StringPool.TAB + "if "))) &&
1779                                                            ((previousLineTabCount + 2) != lineTabCount)) {
1780    
1781                                                            _sourceFormatterHelper.printError(
1782                                                                    fileName,
1783                                                                    "line break: " + fileName + " " + lineCount);
1784                                                    }
1785    
1786                                                    if (previousLine.endsWith(StringPool.PERIOD)) {
1787                                                            int x = trimmedLine.indexOf(
1788                                                                    StringPool.OPEN_PARENTHESIS);
1789    
1790                                                            if ((x != -1) &&
1791                                                                    ((_getLineLength(previousLine) + x) < 80) &&
1792                                                                    (trimmedLine.endsWith(
1793                                                                            StringPool.OPEN_PARENTHESIS) ||
1794                                                                     (trimmedLine.charAt(x + 1) !=
1795                                                                             CharPool.CLOSE_PARENTHESIS))) {
1796    
1797                                                                    _sourceFormatterHelper.printError(
1798                                                                            fileName,
1799                                                                            "line break: " + fileName + " " +
1800                                                                                    lineCount);
1801                                                            }
1802                                                    }
1803    
1804                                                    combinedLines = _getCombinedLines(
1805                                                            trimmedLine, previousLine, lineTabCount,
1806                                                            previousLineTabCount);
1807                                            }
1808                                    }
1809                            }
1810    
1811                            if (combinedLines != null) {
1812                                    previousLine = (String)combinedLines.getObject(0);
1813    
1814                                    if (combinedLines.getSize() > 1) {
1815                                            String linePart = (String)combinedLines.getObject(1);
1816                                            boolean addToPreviousLine =
1817                                                    (Boolean)combinedLines.getObject(2);
1818    
1819                                            if (addToPreviousLine) {
1820                                                    previousLine = previousLine + linePart;
1821                                                    line = StringUtil.replaceFirst(
1822                                                            line, linePart, StringPool.BLANK);
1823                                            }
1824                                            else {
1825                                                    if (((linePart.length() + lineLength) <= 80) &&
1826                                                            (line.endsWith(StringPool.OPEN_CURLY_BRACE) ||
1827                                                             line.endsWith(StringPool.SEMICOLON))) {
1828    
1829                                                            previousLine = StringUtil.replaceLast(
1830                                                                    previousLine, linePart, StringPool.BLANK);
1831    
1832                                                            line = StringUtil.replaceLast(
1833                                                                    line, StringPool.TAB,
1834                                                                    StringPool.TAB + linePart);
1835                                                    }
1836                                                    else {
1837                                                            _sourceFormatterHelper.printError(
1838                                                                    fileName,
1839                                                                    "line break: " + fileName + " " + lineCount);
1840                                                    }
1841                                            }
1842    
1843                                            sb.append(previousLine);
1844                                            sb.append("\n");
1845    
1846                                            previousLine = line;
1847                                    }
1848                                    else if (line.endsWith(StringPool.OPEN_CURLY_BRACE) &&
1849                                                     !previousLine.contains(" class ")) {
1850    
1851                                            lineToSkipIfEmpty = lineCount + 1;
1852                                    }
1853                            }
1854                            else {
1855                                    if ((lineCount > 1) &&
1856                                            (Validator.isNotNull(previousLine) ||
1857                                             (lineToSkipIfEmpty != (lineCount - 1)))) {
1858    
1859                                            sb.append(previousLine);
1860    
1861                                            if (Validator.isNotNull(previousLine) &&
1862                                                    Validator.isNotNull(trimmedLine) &&
1863                                                    !previousLine.contains("/*")) {
1864    
1865                                                    String trimmedPreviousLine = StringUtil.trimLeading(
1866                                                            previousLine);
1867    
1868                                                    if ((trimmedPreviousLine.startsWith("// ") &&
1869                                                             !trimmedLine.startsWith("// ")) ||
1870                                                            (!trimmedPreviousLine.startsWith("// ") &&
1871                                                             trimmedLine.startsWith("// "))) {
1872    
1873                                                            sb.append("\n");
1874                                                    }
1875                                                    else if (previousLine.endsWith(
1876                                                                            StringPool.TAB +
1877                                                                                    StringPool.CLOSE_CURLY_BRACE) &&
1878                                                                     !trimmedLine.startsWith(
1879                                                                             StringPool.CLOSE_CURLY_BRACE) &&
1880                                                                     !trimmedLine.startsWith(
1881                                                                             StringPool.CLOSE_PARENTHESIS) &&
1882                                                                     !trimmedLine.startsWith(
1883                                                                             StringPool.DOUBLE_SLASH) &&
1884                                                                     !trimmedLine.startsWith("catch ") &&
1885                                                                     !trimmedLine.startsWith("else ") &&
1886                                                                     !trimmedLine.startsWith("finally ") &&
1887                                                                     !trimmedLine.startsWith("while ")) {
1888    
1889                                                            sb.append("\n");
1890                                                    }
1891                                            }
1892    
1893                                            sb.append("\n");
1894                                    }
1895    
1896                                    previousLine = line;
1897                            }
1898                    }
1899    
1900                    sb.append(previousLine);
1901    
1902                    unsyncBufferedReader.close();
1903    
1904                    String newContent = sb.toString();
1905    
1906                    if (newContent.endsWith("\n")) {
1907                            newContent = newContent.substring(0, newContent.length() - 1);
1908                    }
1909    
1910                    return newContent;
1911            }
1912    
1913            private static void _formatJS() throws IOException {
1914                    String basedir = "./";
1915    
1916                    DirectoryScanner directoryScanner = new DirectoryScanner();
1917    
1918                    directoryScanner.setBasedir(basedir);
1919    
1920                    String[] excludes = {
1921                            "**\\js\\aui\\**", "**\\js\\editor\\**", "**\\js\\misc\\**",
1922                            "**\\tools\\**", "**\\VAADIN\\**"
1923                    };
1924    
1925                    excludes = ArrayUtil.append(excludes, _excludes);
1926    
1927                    directoryScanner.setExcludes(excludes);
1928    
1929                    directoryScanner.setIncludes(new String[] {"**\\*.js"});
1930    
1931                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
1932                            directoryScanner);
1933    
1934                    for (String fileName : fileNames) {
1935                            File file = new File(basedir + fileName);
1936    
1937                            String content = _fileUtil.read(file);
1938    
1939                            String newContent = _trimContent(content);
1940    
1941                            newContent = StringUtil.replace(
1942                                    newContent,
1943                                    new String[] {
1944                                            "else{", "for(", "function (", "if(", "while(", "){\n",
1945                                            "= new Array();", "= new Object();"
1946                                    },
1947                                    new String[] {
1948                                            "else {", "for (", "function(", "if (", "while (", ") {\n",
1949                                            "= [];", "= {};"
1950                                    });
1951    
1952                            Pattern pattern = Pattern.compile("\t+var \\w+\\, ");
1953    
1954                            for (;;) {
1955                                    Matcher matcher = pattern.matcher(newContent);
1956    
1957                                    if (!matcher.find()) {
1958                                            break;
1959                                    }
1960    
1961                                    String match = newContent.substring(
1962                                            matcher.start(), matcher.end());
1963    
1964                                    int pos = match.indexOf("var ");
1965    
1966                                    StringBundler sb = new StringBundler(4);
1967    
1968                                    sb.append(match.substring(0, match.length() - 2));
1969                                    sb.append(StringPool.SEMICOLON);
1970                                    sb.append("\n");
1971                                    sb.append(match.substring(0, pos + 4));
1972    
1973                                    newContent = StringUtil.replace(
1974                                            newContent, match, sb.toString());
1975                            }
1976    
1977                            if (newContent.endsWith("\n")) {
1978                                    newContent = newContent.substring(0, newContent.length() - 1);
1979                            }
1980    
1981                            if ((newContent != null) && !content.equals(newContent)) {
1982                                    _fileUtil.write(file, newContent);
1983    
1984                                    _sourceFormatterHelper.printError(fileName, file);
1985                            }
1986                    }
1987            }
1988    
1989            private static void _formatJSP() throws IOException {
1990                    String basedir = "./";
1991    
1992                    String copyright = _getCopyright();
1993                    String oldCopyright = _getOldCopyright();
1994    
1995                    DirectoryScanner directoryScanner = new DirectoryScanner();
1996    
1997                    directoryScanner.setBasedir(basedir);
1998    
1999                    String[] excludes = {
2000                            "**\\portal\\aui\\**", "**\\bin\\**", "**\\null.jsp", "**\\tmp\\**",
2001                            "**\\tools\\**"
2002                    };
2003    
2004                    excludes = ArrayUtil.append(excludes, _excludes);
2005    
2006                    directoryScanner.setExcludes(excludes);
2007    
2008                    directoryScanner.setIncludes(
2009                            new String[] {"**\\*.jsp", "**\\*.jspf", "**\\*.vm"});
2010    
2011                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
2012                            directoryScanner);
2013    
2014                    for (String fileName : fileNames) {
2015                            File file = new File(basedir + fileName);
2016    
2017                            String content = _fileUtil.read(file);
2018    
2019                            fileName = fileName.replace(
2020                                    CharPool.BACK_SLASH, CharPool.FORWARD_SLASH);
2021    
2022                            _jspContents.put(fileName, content);
2023                    }
2024    
2025                    boolean stripJSPImports = true;
2026    
2027                    for (String fileName : fileNames) {
2028                            File file = new File(basedir + fileName);
2029    
2030                            String content = _fileUtil.read(file);
2031    
2032                            String oldContent = content;
2033                            String newContent = StringPool.BLANK;
2034    
2035                            for (;;) {
2036                                    newContent = _formatJSP(fileName, oldContent);
2037    
2038                                    if (oldContent.equals(newContent)) {
2039                                            break;
2040                                    }
2041    
2042                                    oldContent = newContent;
2043                            }
2044    
2045                            newContent = StringUtil.replace(
2046                                    newContent,
2047                                    new String[] {
2048                                            "<br/>", "\"/>", "\" >", "@page import", "\"%>", ")%>",
2049                                            "javascript: "
2050                                    },
2051                                    new String[] {
2052                                            "<br />", "\" />", "\">", "@ page import", "\" %>", ") %>",
2053                                            "javascript:"
2054                                    });
2055    
2056                            if (stripJSPImports) {
2057                                    try {
2058                                            newContent = _stripJSPImports(fileName, newContent);
2059                                    }
2060                                    catch (RuntimeException re) {
2061                                            stripJSPImports = false;
2062                                    }
2063                            }
2064    
2065                            newContent = StringUtil.replace(
2066                                    newContent,
2067                                    new String[] {
2068                                            "* Copyright (c) 2000-2011 Liferay, Inc."
2069                                    },
2070                                    new String[] {
2071                                            "* Copyright (c) 2000-2012 Liferay, Inc."
2072                                    });
2073    
2074                            if (fileName.endsWith(".jsp") || fileName.endsWith(".jspf")) {
2075                                    if ((oldCopyright != null) &&
2076                                            newContent.contains(oldCopyright)) {
2077    
2078                                            newContent = StringUtil.replace(
2079                                                    newContent, oldCopyright, copyright);
2080    
2081                                            _sourceFormatterHelper.printError(
2082                                                    fileName, "old (c): " + fileName);
2083                                    }
2084    
2085                                    if (!newContent.contains(copyright)) {
2086                                            String customCopyright = _getCustomCopyright(file);
2087    
2088                                            if (Validator.isNull(customCopyright) ||
2089                                                    !newContent.contains(customCopyright)) {
2090    
2091                                                    _sourceFormatterHelper.printError(
2092                                                            fileName, "(c): " + fileName);
2093                                            }
2094                                            else {
2095                                                    newContent = StringUtil.replace(
2096                                                            newContent, "<%\n" + customCopyright + "\n%>",
2097                                                            "<%--\n" + customCopyright + "\n--%>");
2098                                            }
2099                                    }
2100                                    else {
2101                                            newContent = StringUtil.replace(
2102                                                    newContent, "<%\n" + copyright + "\n%>",
2103                                                    "<%--\n" + copyright + "\n--%>");
2104                                    }
2105                            }
2106    
2107                            newContent = StringUtil.replace(
2108                                    newContent,
2109                                    new String[] {
2110                                            "alert('<%= LanguageUtil.",
2111                                            "alert(\"<%= LanguageUtil.", "confirm('<%= LanguageUtil.",
2112                                            "confirm(\"<%= LanguageUtil."
2113                                    },
2114                                    new String[] {
2115                                            "alert('<%= UnicodeLanguageUtil.",
2116                                            "alert(\"<%= UnicodeLanguageUtil.",
2117                                            "confirm('<%= UnicodeLanguageUtil.",
2118                                            "confirm(\"<%= UnicodeLanguageUtil."
2119                                    });
2120    
2121                            if (newContent.contains("    ")) {
2122                                    if (!fileName.matches(".*template.*\\.vm$")) {
2123                                            _sourceFormatterHelper.printError(
2124                                                    fileName, "tab: " + fileName);
2125                                    }
2126                            }
2127    
2128                            if (fileName.endsWith("init.jsp")) {
2129                                    int x = newContent.indexOf("<%@ page import=");
2130    
2131                                    int y = newContent.lastIndexOf("<%@ page import=");
2132    
2133                                    y = newContent.indexOf("%>", y);
2134    
2135                                    if ((x != -1) && (y != -1) && (y > x)) {
2136    
2137                                            // Set compressImports to false to decompress imports
2138    
2139                                            boolean compressImports = true;
2140    
2141                                            if (compressImports) {
2142                                                    String imports = newContent.substring(x, y);
2143    
2144                                                    imports = StringUtil.replace(
2145                                                            imports, new String[] {"%>\r\n<%@ ", "%>\n<%@ "},
2146                                                            new String[] {"%><%@\r\n", "%><%@\n"});
2147    
2148                                                    newContent =
2149                                                            newContent.substring(0, x) + imports +
2150                                                                    newContent.substring(y);
2151                                            }
2152                                    }
2153                            }
2154    
2155                            _checkXSS(fileName, newContent);
2156    
2157                            if ((newContent != null) && !content.equals(newContent)) {
2158                                    _fileUtil.write(file, newContent);
2159    
2160                                    _sourceFormatterHelper.printError(fileName, file);
2161                            }
2162                    }
2163            }
2164    
2165            private static String _formatJSP(String fileName, String content)
2166                    throws IOException {
2167    
2168                    StringBundler sb = new StringBundler();
2169    
2170                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
2171                            new UnsyncStringReader(content));
2172    
2173                    int lineCount = 0;
2174    
2175                    String line = null;
2176    
2177                    String previousLine = StringPool.BLANK;
2178    
2179                    String currentAttributeAndValue = null;
2180                    String previousAttribute = null;
2181                    String previousAttributeAndValue = null;
2182    
2183                    boolean readAttributes = false;
2184    
2185                    String currentException = null;
2186                    String previousException = null;
2187    
2188                    boolean hasUnsortedExceptions = false;
2189    
2190                    while ((line = unsyncBufferedReader.readLine()) != null) {
2191                            lineCount++;
2192    
2193                            if (!fileName.contains("jsonw") ||
2194                                    !fileName.endsWith("action.jsp")) {
2195    
2196                                    line = _trimLine(line);
2197                            }
2198    
2199                            if (line.contains("<aui:button ") &&
2200                                    line.contains("type=\"button\"")) {
2201    
2202                                    _sourceFormatterHelper.printError(
2203                                            fileName, "aui:button " + fileName + " " + lineCount);
2204                            }
2205    
2206                            String trimmedLine = StringUtil.trimLeading(line);
2207                            String trimmedPreviousLine = StringUtil.trimLeading(previousLine);
2208    
2209                            if (!trimmedLine.equals("%>") && line.contains("%>") &&
2210                                    !line.contains("--%>") && !line.contains(" %>")) {
2211    
2212                                    line = StringUtil.replace(line, "%>", " %>");
2213                            }
2214    
2215                            if (line.contains("<%=") && !line.contains("<%= ")) {
2216                                    line = StringUtil.replace(line, "<%=", "<%= ");
2217                            }
2218    
2219                            if (trimmedPreviousLine.equals("%>") && Validator.isNotNull(line) &&
2220                                    !trimmedLine.equals("-->")) {
2221    
2222                                    sb.append("\n");
2223                            }
2224                            else if (Validator.isNotNull(previousLine) &&
2225                                             !trimmedPreviousLine.equals("<!--") &&
2226                                             trimmedLine.equals("<%")) {
2227    
2228                                    sb.append("\n");
2229                            }
2230                            else if (trimmedPreviousLine.equals("<%") &&
2231                                             Validator.isNull(line)) {
2232    
2233                                    continue;
2234                            }
2235                            else if (trimmedPreviousLine.equals("<%") &&
2236                                             trimmedLine.startsWith("//")) {
2237    
2238                                    sb.append("\n");
2239                            }
2240                            else if (Validator.isNull(previousLine) &&
2241                                             trimmedLine.equals("%>") && (sb.index() > 2)) {
2242    
2243                                    String lineBeforePreviousLine = sb.stringAt(sb.index() - 3);
2244    
2245                                    if (!lineBeforePreviousLine.startsWith("//")) {
2246                                            sb.setIndex(sb.index() - 1);
2247                                    }
2248                            }
2249    
2250                            if ((trimmedLine.startsWith("if (") ||
2251                                     trimmedLine.startsWith("else if (") ||
2252                                     trimmedLine.startsWith("while (")) &&
2253                                    trimmedLine.endsWith(") {")) {
2254    
2255                                    _checkIfClause(trimmedLine, fileName, lineCount);
2256                            }
2257    
2258                            if (readAttributes) {
2259                                    if (!trimmedLine.startsWith(StringPool.FORWARD_SLASH) &&
2260                                            !trimmedLine.startsWith(StringPool.GREATER_THAN)) {
2261    
2262                                            int pos = trimmedLine.indexOf(StringPool.EQUAL);
2263    
2264                                            if (pos != -1) {
2265                                                    String attribute = trimmedLine.substring(0, pos);
2266    
2267                                                    if (!trimmedLine.endsWith(StringPool.QUOTE) &&
2268                                                            !trimmedLine.endsWith(StringPool.APOSTROPHE)) {
2269    
2270                                                            _sourceFormatterHelper.printError(
2271                                                                    fileName,
2272                                                                    "attribute: " + fileName + " " + lineCount);
2273    
2274                                                            readAttributes = false;
2275                                                    }
2276                                                    else if (Validator.isNotNull(previousAttribute)) {
2277                                                            if (!_isJSPAttributName(attribute)) {
2278                                                                    _sourceFormatterHelper.printError(
2279                                                                            fileName,
2280                                                                            "attribute: " + fileName + " " + lineCount);
2281    
2282                                                                    readAttributes = false;
2283                                                            }
2284                                                            else if (Validator.isNull(
2285                                                                                    previousAttributeAndValue) &&
2286                                                                             (previousAttribute.compareTo(
2287                                                                                     attribute) > 0)) {
2288    
2289                                                                    previousAttributeAndValue = previousLine;
2290                                                                    currentAttributeAndValue = line;
2291                                                            }
2292                                                    }
2293    
2294                                                    if (!readAttributes) {
2295                                                            previousAttribute = null;
2296                                                            previousAttributeAndValue = null;
2297                                                    }
2298                                                    else {
2299                                                            previousAttribute = attribute;
2300                                                    }
2301                                            }
2302                                    }
2303                                    else {
2304                                            previousAttribute = null;
2305    
2306                                            readAttributes = false;
2307                                    }
2308                            }
2309    
2310                            if (!hasUnsortedExceptions) {
2311                                    int i = line.indexOf("<liferay-ui:error exception=\"<%=");
2312    
2313                                    if (i != -1) {
2314                                            currentException = line.substring(i + 33);
2315    
2316                                            if (Validator.isNotNull(previousException) &&
2317                                                    (previousException.compareTo(currentException) > 0)) {
2318    
2319                                                    hasUnsortedExceptions = true;
2320                                            }
2321                                    }
2322    
2323                                    if (!hasUnsortedExceptions) {
2324                                            previousException = currentException;
2325                                            currentException = null;
2326                                    }
2327                            }
2328    
2329                            if (trimmedLine.startsWith(StringPool.LESS_THAN) &&
2330                                    !trimmedLine.startsWith("<%") &&
2331                                    !trimmedLine.startsWith("<!")) {
2332    
2333                                    if (!trimmedLine.contains(StringPool.GREATER_THAN) &&
2334                                            !trimmedLine.contains(StringPool.SPACE)) {
2335    
2336                                            readAttributes = true;
2337                                    }
2338                                    else {
2339                                            line = _sortJSPAttributes(fileName, line, lineCount);
2340                                    }
2341                            }
2342    
2343                            if (!trimmedLine.contains(StringPool.DOUBLE_SLASH) &&
2344                                    !trimmedLine.startsWith(StringPool.STAR)) {
2345    
2346                                    while (trimmedLine.contains(StringPool.TAB)) {
2347                                            line = StringUtil.replaceLast(
2348                                                    line, StringPool.TAB, StringPool.SPACE);
2349    
2350                                            trimmedLine = StringUtil.replaceLast(
2351                                                    trimmedLine, StringPool.TAB, StringPool.SPACE);
2352                                    }
2353    
2354                                    while (trimmedLine.contains(StringPool.DOUBLE_SPACE) &&
2355                                               !trimmedLine.contains(
2356                                                       StringPool.QUOTE + StringPool.DOUBLE_SPACE) &&
2357                                               !fileName.endsWith(".vm")) {
2358    
2359                                            line = StringUtil.replaceLast(
2360                                                    line, StringPool.DOUBLE_SPACE, StringPool.SPACE);
2361    
2362                                            trimmedLine = StringUtil.replaceLast(
2363                                                    trimmedLine, StringPool.DOUBLE_SPACE, StringPool.SPACE);
2364                                    }
2365                            }
2366    
2367                            int x = line.indexOf("<%@ include file");
2368    
2369                            if (x != -1) {
2370                                    x = line.indexOf(StringPool.QUOTE, x);
2371    
2372                                    int y = line.indexOf(StringPool.QUOTE, x + 1);
2373    
2374                                    if (y != -1) {
2375                                            String includeFileName = line.substring(x + 1, y);
2376    
2377                                            Matcher matcher = _jspIncludeFilePattern.matcher(
2378                                                    includeFileName);
2379    
2380                                            if (!matcher.find()) {
2381                                                    _sourceFormatterHelper.printError(
2382                                                            fileName, "include: " + fileName + " " + lineCount);
2383                                            }
2384                                    }
2385                            }
2386    
2387                            line = _replacePrimitiveWrapperInstantiation(
2388                                    fileName, line, lineCount);
2389    
2390                            previousLine = line;
2391    
2392                            sb.append(line);
2393                            sb.append("\n");
2394                    }
2395    
2396                    unsyncBufferedReader.close();
2397    
2398                    content = sb.toString();
2399    
2400                    if (content.endsWith("\n")) {
2401                            content = content.substring(0, content.length() - 1);
2402                    }
2403    
2404                    content = _formatTaglibQuotes(fileName, content, StringPool.QUOTE);
2405                    content = _formatTaglibQuotes(fileName, content, StringPool.APOSTROPHE);
2406    
2407                    if (Validator.isNotNull(previousAttributeAndValue)) {
2408                            content = StringUtil.replaceFirst(
2409                                    content,
2410                                    previousAttributeAndValue + "\n" + currentAttributeAndValue,
2411                                    currentAttributeAndValue + "\n" + previousAttributeAndValue);
2412                    }
2413    
2414                    if (hasUnsortedExceptions) {
2415                            if ((StringUtil.count(content, currentException) > 1) ||
2416                                    (StringUtil.count(content, previousException) > 1)) {
2417    
2418                                    _sourceFormatterHelper.printError(
2419                                            fileName, "unsorted exceptions: " + fileName);
2420                            }
2421                            else {
2422                                    content = StringUtil.replaceFirst(
2423                                            content, previousException, currentException);
2424    
2425                                    content = StringUtil.replaceLast(
2426                                            content, currentException, previousException);
2427                            }
2428                    }
2429    
2430                    return content;
2431            }
2432    
2433            private static void _formatPortalProperties() throws IOException {
2434                    String basedir = "./";
2435    
2436                    String portalPortalProperties = null;
2437    
2438                    if (_portalSource) {
2439                            File portalPortalPropertiesFile = new File(
2440                                    basedir + "portal-impl/src/portal.properties");
2441    
2442                            portalPortalProperties = _fileUtil.read(portalPortalPropertiesFile);
2443                    }
2444                    else {
2445                            portalPortalProperties = ContentUtil.get("portal.properties");
2446                    }
2447    
2448                    DirectoryScanner directoryScanner = new DirectoryScanner();
2449    
2450                    directoryScanner.setBasedir(basedir);
2451    
2452                    if (_portalSource) {
2453                            directoryScanner.setIncludes(
2454                                    new String[] {
2455                                            "**\\portal-ext.properties",
2456                                            "**\\portal-legacy-*.properties",
2457                                    }
2458                            );
2459                    }
2460                    else {
2461                            directoryScanner.setIncludes(
2462                                    new String[] {
2463                                            "**\\portal.properties", "**\\portal-ext.properties"
2464                                    }
2465                            );
2466                    }
2467    
2468                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
2469                            directoryScanner);
2470    
2471                    for (String fileName : fileNames) {
2472                            File file = new File(basedir + fileName);
2473    
2474                            String content = _fileUtil.read(file);
2475    
2476                            _formatPortalProperties(fileName, content, portalPortalProperties);
2477                    }
2478            }
2479    
2480            private static void _formatPortalProperties(
2481                            String fileName, String content, String portalPortalProperties)
2482                    throws IOException {
2483    
2484                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
2485                            new UnsyncStringReader(content));
2486    
2487                    int lineCount = 0;
2488    
2489                    String line = null;
2490    
2491                    int previousPos = -1;
2492    
2493                    while ((line = unsyncBufferedReader.readLine()) != null) {
2494                            lineCount++;
2495    
2496                            int pos = line.indexOf(StringPool.EQUAL);
2497    
2498                            if (pos == -1) {
2499                                    continue;
2500                            }
2501    
2502                            String property = line.substring(0, pos + 1);
2503    
2504                            property = property.trim();
2505    
2506                            pos = portalPortalProperties.indexOf(
2507                                    StringPool.FOUR_SPACES + property);
2508    
2509                            if (pos == -1) {
2510                                    continue;
2511                            }
2512    
2513                            if (pos < previousPos) {
2514                                    _sourceFormatterHelper.printError(
2515                                            fileName, "sort " + fileName + " " + lineCount);
2516                            }
2517    
2518                            previousPos = pos;
2519                    }
2520            }
2521    
2522            private static void _formatPortletXML()
2523                    throws DocumentException, IOException {
2524    
2525                    String basedir = "./";
2526    
2527                    if (_portalSource) {
2528                            File file = new File(
2529                                    basedir + "portal-web/docroot/WEB-INF/portlet-custom.xml");
2530    
2531                            String content = _fileUtil.read(file);
2532    
2533                            String newContent = _formatPortletXML(content);
2534    
2535                            if ((newContent != null) && !content.equals(newContent)) {
2536                                    _fileUtil.write(file, newContent);
2537    
2538                                    _sourceFormatterHelper.printError(file.toString(), file);
2539                            }
2540                    }
2541                    else {
2542                            DirectoryScanner directoryScanner = new DirectoryScanner();
2543    
2544                            directoryScanner.setBasedir(basedir);
2545                            directoryScanner.setIncludes(new String[] {"**\\portlet.xml"});
2546    
2547                            List<String> fileNames = _sourceFormatterHelper.scanForFiles(
2548                                    directoryScanner);
2549    
2550                            for (String fileName : fileNames) {
2551                                    File file = new File(basedir + fileName);
2552    
2553                                    String content = _fileUtil.read(file);
2554    
2555                                    String newContent = _trimContent(content);
2556    
2557                                    newContent = _formatPortletXML(content);
2558    
2559                                    if ((newContent != null) && !content.equals(newContent)) {
2560                                            _fileUtil.write(file, newContent);
2561    
2562                                            _sourceFormatterHelper.printError(fileName, file);
2563                                    }
2564                            }
2565                    }
2566            }
2567    
2568            private static String _formatPortletXML(String content)
2569                    throws DocumentException, IOException {
2570    
2571                    Document document = _saxReaderUtil.read(content);
2572    
2573                    Element rootElement = document.getRootElement();
2574    
2575                    rootElement.sortAttributes(true);
2576    
2577                    List<Element> portletElements = rootElement.elements("portlet");
2578    
2579                    for (Element portletElement : portletElements) {
2580                            portletElement.sortElementsByChildElement("init-param", "name");
2581    
2582                            Element portletPreferencesElement = portletElement.element(
2583                                    "portlet-preferences");
2584    
2585                            if (portletPreferencesElement != null) {
2586                                    portletPreferencesElement.sortElementsByChildElement(
2587                                            "preference", "name");
2588                            }
2589                    }
2590    
2591                    return document.formattedString();
2592            }
2593    
2594            private static void _formatServiceXML()
2595                    throws DocumentException, IOException {
2596    
2597                    String basedir = "./";
2598    
2599                    DirectoryScanner directoryScanner = new DirectoryScanner();
2600    
2601                    directoryScanner.setBasedir(basedir);
2602                    directoryScanner.setIncludes(new String[] {"**\\service.xml"});
2603    
2604                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
2605                            directoryScanner);
2606    
2607                    for (String fileName : fileNames) {
2608                            File file = new File(basedir + fileName);
2609    
2610                            String content = _fileUtil.read(file);
2611    
2612                            String newContent = _trimContent(content);
2613    
2614                            _formatServiceXML(fileName, content);
2615    
2616                            if ((newContent != null) && !content.equals(newContent)) {
2617                                    _fileUtil.write(file, newContent);
2618    
2619                                    _sourceFormatterHelper.printError(fileName, file);
2620                            }
2621                    }
2622            }
2623    
2624            private static void _formatServiceXML(String fileName, String content)
2625                    throws DocumentException {
2626    
2627                    Document document = _saxReaderUtil.read(content);
2628    
2629                    Element rootElement = document.getRootElement();
2630    
2631                    List<Element> entityElements = rootElement.elements("entity");
2632    
2633                    String previousEntityName = StringPool.BLANK;
2634    
2635                    for (Element entityElement : entityElements) {
2636                            String entityName = entityElement.attributeValue("name");
2637    
2638                            if (Validator.isNotNull(previousEntityName) &&
2639                                    (previousEntityName.compareToIgnoreCase(entityName) > 0)) {
2640    
2641                                    _sourceFormatterHelper.printError(
2642                                            fileName, "sort: " + fileName + " " + entityName);
2643                            }
2644    
2645                            String previousReferenceEntity = StringPool.BLANK;
2646                            String previousReferencePackagePath = StringPool.BLANK;
2647    
2648                            List<Element> referenceElements = entityElement.elements(
2649                                    "reference");
2650    
2651                            for (Element referenceElement : referenceElements) {
2652                                    String referenceEntity = referenceElement.attributeValue(
2653                                            "entity");
2654                                    String referencePackagePath = referenceElement.attributeValue(
2655                                            "package-path");
2656    
2657    
2658                                    if (Validator.isNotNull(previousReferencePackagePath)) {
2659                                            if ((previousReferencePackagePath.compareToIgnoreCase(
2660                                                            referencePackagePath) > 0) ||
2661                                                    (previousReferencePackagePath.equals(
2662                                                            referencePackagePath) &&
2663                                                     (previousReferenceEntity.compareToIgnoreCase(
2664                                                             referenceEntity) > 0))) {
2665    
2666                                                    _sourceFormatterHelper.printError(
2667                                                            fileName,
2668                                                            "sort: " + fileName + " " + referencePackagePath);
2669                                            }
2670                                    }
2671    
2672                                    previousReferenceEntity = referenceEntity;
2673                                    previousReferencePackagePath = referencePackagePath;
2674                            }
2675    
2676                            previousEntityName = entityName;
2677                    }
2678    
2679                    Element exceptionsElement = rootElement.element("exceptions");
2680    
2681                    if (exceptionsElement == null) {
2682                            return;
2683                    }
2684    
2685                    List<Element> exceptionElements = exceptionsElement.elements(
2686                            "exception");
2687    
2688                    String previousException = StringPool.BLANK;
2689    
2690                    for (Element exceptionElement : exceptionElements) {
2691                            String exception = exceptionElement.getStringValue();
2692    
2693                            if (Validator.isNotNull(previousException) &&
2694                                    (previousException.compareToIgnoreCase(exception) > 0)) {
2695    
2696                                    _sourceFormatterHelper.printError(
2697                                            fileName, "sort: " + fileName + " " + exception);
2698                            }
2699    
2700                            previousException = exception;
2701                    }
2702            }
2703    
2704            private static void _formatSH() throws IOException {
2705                    _formatSH("ext/create.sh");
2706                    _formatSH("hooks/create.sh");
2707                    _formatSH("layouttpl/create.sh");
2708                    _formatSH("portlets/create.sh");
2709                    _formatSH("themes/create.sh");
2710            }
2711    
2712            private static void _formatSH(String fileName) throws IOException {
2713                    File file = new File(fileName);
2714    
2715                    if (!file.exists()) {
2716                            return;
2717                    }
2718    
2719                    String content = _fileUtil.read(new File(fileName), true);
2720    
2721                    if (content.contains("\r")) {
2722                            _sourceFormatterHelper.printError(
2723                                    fileName, "Invalid new line character");
2724    
2725                            content = StringUtil.replace(content, "\r", "");
2726    
2727                            _fileUtil.write(fileName, content);
2728                    }
2729            }
2730    
2731            private static void _formatSQL() throws IOException {
2732                    String basedir = "./";
2733    
2734                    DirectoryScanner directoryScanner = new DirectoryScanner();
2735    
2736                    directoryScanner.setBasedir(basedir);
2737                    directoryScanner.setIncludes(new String[] {"**\\sql\\*.sql"});
2738    
2739                    List<String> fileNames = _sourceFormatterHelper.scanForFiles(
2740                            directoryScanner);
2741    
2742                    for (String fileName : fileNames) {
2743                            File file = new File(basedir + fileName);
2744    
2745                            String content = _fileUtil.read(file);
2746    
2747                            String newContent = _formatSQL(content);
2748    
2749                            if ((newContent != null) && !content.equals(newContent)) {
2750                                    _fileUtil.write(file, newContent);
2751    
2752                                    _sourceFormatterHelper.printError(fileName, file);
2753                            }
2754                    }
2755            }
2756    
2757            private static String _formatSQL(String content) throws IOException {
2758                    StringBundler sb = new StringBundler();
2759    
2760                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
2761                            new UnsyncStringReader(content));
2762    
2763                    String line = null;
2764    
2765                    String previousLineSqlCommand = StringPool.BLANK;
2766    
2767                    while ((line = unsyncBufferedReader.readLine()) != null) {
2768                            line = _trimLine(line);
2769    
2770                            if (Validator.isNotNull(line) && !line.startsWith(StringPool.TAB)) {
2771                                    String sqlCommand = StringUtil.split(line, CharPool.SPACE)[0];
2772    
2773                                    if (Validator.isNotNull(previousLineSqlCommand) &&
2774                                            !previousLineSqlCommand.equals(sqlCommand)) {
2775    
2776                                            sb.append("\n");
2777                                    }
2778    
2779                                    previousLineSqlCommand = sqlCommand;
2780                            }
2781                            else {
2782                                    previousLineSqlCommand = StringPool.BLANK;
2783                            }
2784    
2785                            sb.append(line);
2786                            sb.append("\n");
2787                    }
2788    
2789                    unsyncBufferedReader.close();
2790    
2791                    content = sb.toString();
2792    
2793                    if (content.endsWith("\n")) {
2794                            content = content.substring(0, content.length() - 1);
2795                    }
2796    
2797                    return content;
2798            }
2799    
2800            private static void _formatStrutsConfigXML()
2801                    throws IOException, DocumentException {
2802    
2803                    String basedir = "./";
2804    
2805                    if (!_portalSource) {
2806                            return;
2807                    }
2808    
2809                    String fileName = "portal-web/docroot/WEB-INF/struts-config.xml";
2810    
2811                    File file = new File(basedir + fileName);
2812    
2813                    String content = _fileUtil.read(file);
2814    
2815                    String newContent = _trimContent(content);
2816    
2817                    Document document = _saxReaderUtil.read(newContent);
2818    
2819                    Element rootElement = document.getRootElement();
2820    
2821                    Element actionMappingsElement = rootElement.element("action-mappings");
2822    
2823                    List<Element> actionElements = actionMappingsElement.elements("action");
2824    
2825                    String previousPath = StringPool.BLANK;
2826    
2827                    for (Element actionElement : actionElements) {
2828                            String path = actionElement.attributeValue("path");
2829    
2830                            if (Validator.isNotNull(previousPath) &&
2831                                    (previousPath.compareTo(path) > 0) &&
2832                                    (!previousPath.startsWith("/portal/") ||
2833                                     path.startsWith("/portal/"))) {
2834    
2835                                    _sourceFormatterHelper.printError(
2836                                            fileName, "sort: " + fileName + " " + path);
2837                            }
2838    
2839                            previousPath = path;
2840                    }
2841    
2842                    if ((newContent != null) && !content.equals(newContent)) {
2843                            _fileUtil.write(file, newContent);
2844    
2845                            _sourceFormatterHelper.printError(fileName, file);
2846                    }
2847            }
2848    
2849            private static String _formatTaglibQuotes(
2850                    String fileName, String content, String quoteType) {
2851    
2852                    String quoteFix = StringPool.APOSTROPHE;
2853    
2854                    if (quoteFix.equals(quoteType)) {
2855                            quoteFix = StringPool.QUOTE;
2856                    }
2857    
2858                    Pattern pattern = Pattern.compile(_getTaglibRegex(quoteType));
2859    
2860                    Matcher matcher = pattern.matcher(content);
2861    
2862                    while (matcher.find()) {
2863                            int x = content.indexOf(quoteType + "<%=", matcher.start());
2864                            int y = content.indexOf("%>" + quoteType, x);
2865    
2866                            while ((x != -1) && (y != -1)) {
2867                                    String result = content.substring(x + 1, y + 2);
2868    
2869                                    if (result.contains(quoteType)) {
2870                                            int lineCount = 1;
2871    
2872                                            char[] contentCharArray = content.toCharArray();
2873    
2874                                            for (int i = 0; i < x; i++) {
2875                                                    if (contentCharArray[i] == CharPool.NEW_LINE) {
2876                                                            lineCount++;
2877                                                    }
2878                                            }
2879    
2880                                            if (!result.contains(quoteFix)) {
2881                                                    StringBundler sb = new StringBundler(5);
2882    
2883                                                    sb.append(content.substring(0, x));
2884                                                    sb.append(quoteFix);
2885                                                    sb.append(result);
2886                                                    sb.append(quoteFix);
2887                                                    sb.append(content.substring(y + 3, content.length()));
2888    
2889                                                    content = sb.toString();
2890                                            }
2891                                            else {
2892                                                    _sourceFormatterHelper.printError(
2893                                                            fileName, "taglib: " + fileName + " " + lineCount);
2894                                            }
2895                                    }
2896    
2897                                    x = content.indexOf(quoteType + "<%=", y);
2898    
2899                                    if (x > matcher.end()) {
2900                                            break;
2901                                    }
2902    
2903                                    y = content.indexOf("%>" + quoteType, x);
2904                            }
2905                    }
2906    
2907                    return content;
2908            }
2909    
2910            private static void _formatTilesDefsXML()
2911                    throws IOException, DocumentException {
2912    
2913                    String basedir = "./";
2914    
2915                    if (!_portalSource) {
2916                            return;
2917                    }
2918    
2919                    String fileName = "portal-web/docroot/WEB-INF/tiles-defs.xml";
2920    
2921                    File file = new File(basedir + fileName);
2922    
2923                    String content = _fileUtil.read(file);
2924    
2925                    String newContent = _trimContent(content);
2926    
2927                    Document document = _saxReaderUtil.read(newContent);
2928    
2929                    Element rootElement = document.getRootElement();
2930    
2931                    List<Element> definitionElements = rootElement.elements("definition");
2932    
2933                    String previousName = StringPool.BLANK;
2934    
2935                    for (Element definitionElement : definitionElements) {
2936                            String name = definitionElement.attributeValue("name");
2937    
2938                            if (Validator.isNotNull(previousName) &&
2939                                    (previousName.compareTo(name) > 0) &&
2940                                    !previousName.equals("portlet")) {
2941    
2942                                    _sourceFormatterHelper.printError(
2943                                            fileName, "sort: " + fileName + " " + name);
2944    
2945                            }
2946    
2947                            previousName = name;
2948                    }
2949    
2950                    if ((newContent != null) && !content.equals(newContent)) {
2951                            _fileUtil.write(file, newContent);
2952    
2953                            _sourceFormatterHelper.printError(fileName, file);
2954                    }
2955            }
2956    
2957            private static void _formatWebXML() throws IOException {
2958                    String basedir = "./";
2959    
2960                    if (_portalSource) {
2961                            Properties properties = new Properties();
2962    
2963                            String propertiesContent = _fileUtil.read(
2964                                    basedir + "portal-impl/src/portal.properties");
2965    
2966                            PropertiesUtil.load(properties, propertiesContent);
2967    
2968                            String[] locales = StringUtil.split(
2969                                    properties.getProperty(PropsKeys.LOCALES));
2970    
2971                            Arrays.sort(locales);
2972    
2973                            Set<String> urlPatterns = new TreeSet<String>();
2974    
2975                            for (String locale : locales) {
2976                                    int pos = locale.indexOf(StringPool.UNDERLINE);
2977    
2978                                    String languageCode = locale.substring(0, pos);
2979    
2980                                    urlPatterns.add(languageCode);
2981                                    urlPatterns.add(locale);
2982                            }
2983    
2984                            StringBundler sb = new StringBundler();
2985    
2986                            for (String urlPattern : urlPatterns) {
2987                                    sb.append("\t<servlet-mapping>\n");
2988                                    sb.append("\t\t<servlet-name>I18n Servlet</servlet-name>\n");
2989                                    sb.append(
2990                                            "\t\t<url-pattern>/" + urlPattern +"/*</url-pattern>\n");
2991                                    sb.append("\t</servlet-mapping>\n");
2992                            }
2993    
2994                            File file = new File(
2995                                    basedir + "portal-web/docroot/WEB-INF/web.xml");
2996    
2997                            String content = _fileUtil.read(file);
2998    
2999                            String newContent = _trimContent(content);
3000    
3001                            int x = newContent.indexOf("<servlet-mapping>");
3002    
3003                            x = newContent.indexOf(
3004                                    "<servlet-name>I18n Servlet</servlet-name>", x);
3005    
3006                            x = newContent.lastIndexOf("<servlet-mapping>", x) - 1;
3007    
3008                            int y = newContent.lastIndexOf(
3009                                    "<servlet-name>I18n Servlet</servlet-name>");
3010    
3011                            y = newContent.indexOf("</servlet-mapping>", y) + 19;
3012    
3013                            newContent =
3014                                    newContent.substring(0, x) + sb.toString() +
3015                                            newContent.substring(y);
3016    
3017                            x = newContent.indexOf("<security-constraint>");
3018    
3019                            x = newContent.indexOf(
3020                                    "<web-resource-name>/c/portal/protected</web-resource-name>",
3021                                    x);
3022    
3023                            x = newContent.indexOf("<url-pattern>", x) - 3;
3024    
3025                            y = newContent.indexOf("<http-method>", x);
3026    
3027                            y = newContent.lastIndexOf("</url-pattern>", y) + 15;
3028    
3029                            sb = new StringBundler();
3030    
3031                            sb.append("\t\t\t<url-pattern>/c/portal/protected</url-pattern>\n");
3032    
3033                            for (String urlPattern : urlPatterns) {
3034                                    sb.append(
3035                                            "\t\t\t<url-pattern>/" + urlPattern +
3036                                                    "/c/portal/protected</url-pattern>\n");
3037                            }
3038    
3039                            newContent =
3040                                    newContent.substring(0, x) + sb.toString() +
3041                                            newContent.substring(y);
3042    
3043                            if ((newContent != null) && !content.equals(newContent)) {
3044                                    _fileUtil.write(file, newContent);
3045    
3046                                    System.out.println(file);
3047                            }
3048                    }
3049                    else {
3050                            String webXML = ContentUtil.get(
3051                                    "com/liferay/portal/deploy/dependencies/web.xml");
3052    
3053                            DirectoryScanner directoryScanner = new DirectoryScanner();
3054    
3055                            directoryScanner.setBasedir(basedir);
3056                            directoryScanner.setIncludes(new String[] {"**\\web.xml"});
3057    
3058                            List<String> fileNames = _sourceFormatterHelper.scanForFiles(
3059                                    directoryScanner);
3060    
3061                            for (String fileName : fileNames) {
3062                                    String content = _fileUtil.read(basedir + fileName);
3063    
3064                                    if (content.equals(webXML)) {
3065                                            _sourceFormatterHelper.printError(fileName, fileName);
3066                                    }
3067                            }
3068                    }
3069            }
3070    
3071            private static String _getClassName(String line) {
3072                    int pos = line.indexOf(" implements ");
3073    
3074                    if (pos == -1) {
3075                            pos = line.indexOf(" extends ");
3076                    }
3077    
3078                    if (pos == -1) {
3079                            pos = line.indexOf(StringPool.OPEN_CURLY_BRACE);
3080                    }
3081    
3082                    if (pos != -1) {
3083                            line = line.substring(0, pos);
3084                    }
3085    
3086                    line = line.trim();
3087    
3088                    pos = line.lastIndexOf(StringPool.SPACE);
3089    
3090                    return line.substring(pos + 1);
3091            }
3092    
3093            private static Tuple _getCombinedLines(
3094                    String line, String previousLine, int lineTabCount,
3095                    int previousLineTabCount) {
3096    
3097                    if (Validator.isNull(line) || Validator.isNull(previousLine)) {
3098                            return null;
3099                    }
3100    
3101                    String trimmedPreviousLine = StringUtil.trimLeading(previousLine);
3102    
3103                    if (line.startsWith("// ") || trimmedPreviousLine.startsWith("// ")) {
3104                            return null;
3105                    }
3106    
3107                    if (line.startsWith("+ ") || line.startsWith("- ") ||
3108                            line.startsWith("|| ") || line.startsWith("&& ")) {
3109    
3110                            int pos = line.indexOf(StringPool.SPACE);
3111    
3112                            String linePart = line.substring(0, pos);
3113    
3114                            return new Tuple(previousLine + StringPool.SPACE, linePart, true);
3115                    }
3116    
3117                    int previousLineLength = _getLineLength(previousLine);
3118    
3119                    if ((line.length() + previousLineLength) < 80) {
3120                            if (trimmedPreviousLine.startsWith("for ") &&
3121                                    previousLine.endsWith(StringPool.COLON) &&
3122                                    line.endsWith(StringPool.OPEN_CURLY_BRACE)) {
3123    
3124                                    return new Tuple(previousLine + StringPool.SPACE + line);
3125                            }
3126    
3127                            if ((previousLine.endsWith(StringPool.EQUAL) ||
3128                                     previousLine.endsWith(StringPool.PERIOD) ||
3129                                     trimmedPreviousLine.equals("return")) &&
3130                                    line.endsWith(StringPool.SEMICOLON)) {
3131    
3132                                    return new Tuple(previousLine + StringPool.SPACE + line);
3133                            }
3134    
3135                            if ((trimmedPreviousLine.startsWith("if ") ||
3136                                     trimmedPreviousLine.startsWith("else ")) &&
3137                                    (previousLine.endsWith("||") || previousLine.endsWith("&&")) &&
3138                                    line.endsWith(StringPool.OPEN_CURLY_BRACE)) {
3139    
3140                                    return new Tuple(previousLine + StringPool.SPACE + line);
3141                            }
3142    
3143                            if ((line.startsWith("extends ") ||
3144                                     line.startsWith("implements ") ||
3145                                     line.startsWith("throws")) &&
3146                                    line.endsWith(StringPool.OPEN_CURLY_BRACE) &&
3147                                    (lineTabCount == (previousLineTabCount + 1))) {
3148    
3149                                    return new Tuple(previousLine + StringPool.SPACE + line);
3150                            }
3151                    }
3152    
3153                    if (previousLine.endsWith(StringPool.EQUAL) &&
3154                            line.endsWith(StringPool.SEMICOLON)) {
3155    
3156                            String tempLine = line;
3157    
3158                            for (int pos = 0;;) {
3159                                    pos = tempLine.indexOf(StringPool.DASH);
3160    
3161                                    if (pos == -1) {
3162                                            pos = tempLine.indexOf(StringPool.PLUS);
3163                                    }
3164    
3165                                    if (pos == -1) {
3166                                            pos = tempLine.indexOf(StringPool.SLASH);
3167                                    }
3168    
3169                                    if (pos == -1) {
3170                                            pos = tempLine.indexOf(StringPool.STAR);
3171                                    }
3172    
3173                                    if (pos == -1) {
3174                                            break;
3175                                    }
3176    
3177                                    String linePart = tempLine.substring(0, pos);
3178    
3179                                    int openParenthesisCount = StringUtil.count(
3180                                            linePart, StringPool.OPEN_PARENTHESIS);
3181                                    int closeParenthesisCount = StringUtil.count(
3182                                            linePart, StringPool.CLOSE_PARENTHESIS);
3183    
3184                                    if (openParenthesisCount == closeParenthesisCount) {
3185                                            return null;
3186                                    }
3187    
3188                                    tempLine =
3189                                            tempLine.substring(0, pos) + tempLine.substring(pos + 1);
3190                            }
3191    
3192                            int x = line.indexOf(StringPool.OPEN_PARENTHESIS);
3193    
3194                            if (x == 0) {
3195                                    x = line.indexOf(StringPool.OPEN_PARENTHESIS, 1);
3196                            }
3197    
3198                            if (x != -1) {
3199                                    int y = line.indexOf(StringPool.CLOSE_PARENTHESIS, x);
3200                                    int z = line.indexOf(StringPool.QUOTE);
3201    
3202                                    if (((x + 1) != y) && ((z == -1) || (z > x))) {
3203                                            char previousChar = line.charAt(x - 1);
3204    
3205                                            if ((previousChar != CharPool.CLOSE_PARENTHESIS) &&
3206                                                    (previousChar != CharPool.OPEN_PARENTHESIS) &&
3207                                                    (previousChar != CharPool.SPACE) &&
3208                                                    (previousLineLength + 1 + x) < 80) {
3209    
3210                                                    String linePart = line.substring(0, x + 1);
3211    
3212                                                    if (linePart.contains(StringPool.SPACE) ||
3213                                                            (linePart.startsWith(StringPool.OPEN_PARENTHESIS) &&
3214                                                             !linePart.contains(
3215                                                                     StringPool.CLOSE_PARENTHESIS))) {
3216    
3217                                                            return null;
3218                                                    }
3219    
3220                                                    return new Tuple(
3221                                                            previousLine + StringPool.SPACE, linePart, true);
3222                                            }
3223                                    }
3224                            }
3225                    }
3226    
3227                    if (previousLine.endsWith(StringPool.COMMA) &&
3228                            (previousLineTabCount == lineTabCount) &&
3229                            !previousLine.contains(StringPool.CLOSE_CURLY_BRACE)) {
3230    
3231                            int x = line.indexOf(StringPool.COMMA);
3232    
3233                            if (x != -1) {
3234                                    while ((previousLineLength + 1 + x) < 80) {
3235                                            String linePart = line.substring(0, x + 1);
3236    
3237                                            if (_isValidJavaParameter(linePart)) {
3238                                                    if (line.equals(linePart)) {
3239                                                            return new Tuple(
3240                                                                    previousLine + StringPool.SPACE + linePart);
3241                                                    }
3242                                                    else {
3243                                                            return new Tuple(
3244                                                                    previousLine + StringPool.SPACE,
3245                                                                    linePart + StringPool.SPACE, true);
3246                                                    }
3247                                            }
3248    
3249                                            String partAfterComma = line.substring(x + 1);
3250    
3251                                            int pos = partAfterComma.indexOf(StringPool.COMMA);
3252    
3253                                            if (pos == -1) {
3254                                                    break;
3255                                            }
3256    
3257                                            x = x + pos + 1;
3258                                    }
3259                            }
3260                            else if (!line.endsWith(StringPool.OPEN_PARENTHESIS) &&
3261                                             !line.endsWith(StringPool.PLUS) &&
3262                                             !line.endsWith(StringPool.PERIOD) &&
3263                                             (!line.startsWith("new ") ||
3264                                              !line.endsWith(StringPool.OPEN_CURLY_BRACE)) &&
3265                                             ((line.length() + previousLineLength) < 80)) {
3266    
3267                                    return new Tuple(previousLine + StringPool.SPACE + line);
3268                            }
3269                    }
3270    
3271                    if (!previousLine.endsWith(StringPool.OPEN_PARENTHESIS)) {
3272                            return null;
3273                    }
3274    
3275                    if (StringUtil.count(previousLine, StringPool.OPEN_PARENTHESIS) > 1) {
3276                            int pos = trimmedPreviousLine.lastIndexOf(
3277                                    StringPool.OPEN_PARENTHESIS, trimmedPreviousLine.length() - 2);
3278    
3279                            if ((pos > 0) &&
3280                                    Character.isLetterOrDigit(
3281                                            trimmedPreviousLine.charAt(pos -1 ))) {
3282    
3283                                    String filePart = trimmedPreviousLine.substring(pos + 1);
3284    
3285                                    if (!filePart.contains(StringPool.CLOSE_PARENTHESIS) &&
3286                                            !filePart.contains(StringPool.QUOTE)) {
3287    
3288                                            return new Tuple(previousLine, filePart, false);
3289                                    }
3290                            }
3291                    }
3292    
3293                    if ((line.length() + previousLineLength) > 80) {
3294                            return null;
3295                    }
3296    
3297                    if (line.endsWith(StringPool.SEMICOLON)) {
3298                            return new Tuple(previousLine + line);
3299                    }
3300    
3301                    if (((line.endsWith(StringPool.OPEN_CURLY_BRACE) &&
3302                              !line.startsWith("new ")) ||
3303                             line.endsWith(StringPool.CLOSE_PARENTHESIS)) &&
3304                            (trimmedPreviousLine.startsWith("else ") ||
3305                             trimmedPreviousLine.startsWith("if ") ||
3306                             trimmedPreviousLine.startsWith("private ") ||
3307                             trimmedPreviousLine.startsWith("protected ") ||
3308                             trimmedPreviousLine.startsWith("public "))) {
3309    
3310                            return new Tuple(previousLine + line);
3311                    }
3312    
3313                    return null;
3314            }
3315    
3316            private static String _getConstructorOrMethodName(String line, int pos) {
3317                    line = line.substring(0, pos);
3318    
3319                    int x = line.lastIndexOf(StringPool.SPACE);
3320    
3321                    return line.substring(x + 1);
3322            }
3323    
3324            private static String _getCopyright() throws IOException {
3325                    String copyright = _fileUtil.read("copyright.txt");
3326    
3327                    if (Validator.isNull(copyright)) {
3328                            copyright = _fileUtil.read("../copyright.txt");
3329                    }
3330    
3331                    if (Validator.isNull(copyright)) {
3332                            copyright = _fileUtil.read("../../copyright.txt");
3333                    }
3334    
3335                    return copyright;
3336            }
3337    
3338            private static String _getCustomCopyright(File file)
3339                    throws IOException {
3340    
3341                    String absolutePath = _fileUtil.getAbsolutePath(file);
3342    
3343                    for (int x = absolutePath.length();;) {
3344                            x = absolutePath.lastIndexOf(StringPool.SLASH, x);
3345    
3346                            if (x == -1) {
3347                                    break;
3348                            }
3349    
3350                            String copyright = _fileUtil.read(
3351                                    absolutePath.substring(0, x + 1) + "copyright.txt");
3352    
3353                            if (Validator.isNotNull(copyright)) {
3354                                    return copyright;
3355                            }
3356    
3357                            x = x - 1;
3358                    }
3359    
3360                    return null;
3361            }
3362    
3363            private static Tuple _getJavaTermTuple(String line) {
3364                    int pos = line.indexOf(StringPool.OPEN_PARENTHESIS);
3365    
3366                    if (line.startsWith(StringPool.TAB + "public static final ") &&
3367                            (line.contains(StringPool.EQUAL) ||
3368                            (line.endsWith(StringPool.SEMICOLON) && (pos == -1)))) {
3369    
3370                            return new Tuple(
3371                                    _getVariableName(line), _TYPE_VARIABLE_PUBLIC_STATIC_FINAL);
3372                    }
3373                    else if (line.startsWith(StringPool.TAB + "public static ")) {
3374                            if (line.contains(StringPool.EQUAL) ||
3375                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3376    
3377                                    return new Tuple(
3378                                            _getVariableName(line), _TYPE_VARIABLE_PUBLIC_STATIC);
3379                            }
3380    
3381                            if (pos != -1) {
3382                                    return new Tuple(
3383                                            _getConstructorOrMethodName(line, pos),
3384                                            _TYPE_METHOD_PUBLIC_STATIC);
3385                            }
3386    
3387                            if (line.startsWith(StringPool.TAB + "public static class ")) {
3388                                    return new Tuple(
3389                                            _getClassName(line), _TYPE_CLASS_PUBLIC_STATIC);
3390                            }
3391                    }
3392                    else if (line.startsWith(StringPool.TAB + "public ")) {
3393                            if (line.contains(StringPool.EQUAL) ||
3394                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3395    
3396                                    return new Tuple(_getVariableName(line), _TYPE_VARIABLE_PUBLIC);
3397                            }
3398    
3399                            if (pos != -1) {
3400                                    int spaceCount = StringUtil.count(
3401                                            line.substring(0, pos), StringPool.SPACE);
3402    
3403                                    if (spaceCount == 1) {
3404                                            return new Tuple(
3405                                                    _getConstructorOrMethodName(line, pos),
3406                                                    _TYPE_CONSTRUCTOR_PUBLIC);
3407                                    }
3408    
3409                                    if (spaceCount > 1) {
3410                                            return new Tuple(
3411                                                    _getConstructorOrMethodName(line, pos),
3412                                                    _TYPE_METHOD_PUBLIC);
3413                                    }
3414                            }
3415                            else if (line.startsWith(StringPool.TAB + "public class ")) {
3416                                    return new Tuple(_getClassName(line), _TYPE_CLASS_PUBLIC);
3417                            }
3418                    }
3419                    else if (line.startsWith(StringPool.TAB + "protected static final ")) {
3420                            if (line.contains(StringPool.EQUAL) ||
3421                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3422    
3423                                    return new Tuple(
3424                                            _getVariableName(line),
3425                                            _TYPE_VARIABLE_PROTECTED_STATIC_FINAL);
3426                            }
3427                    }
3428                    else if (line.startsWith(StringPool.TAB + "protected static ")) {
3429                            if (line.contains(StringPool.EQUAL) ||
3430                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3431    
3432                                    return new Tuple(
3433                                            _getVariableName(line), _TYPE_VARIABLE_PROTECTED_STATIC);
3434                            }
3435    
3436                            if (pos != -1) {
3437                                    return new Tuple(
3438                                            _getConstructorOrMethodName(line, pos),
3439                                            _TYPE_METHOD_PROTECTED_STATIC);
3440                            }
3441    
3442                            if (line.startsWith(StringPool.TAB + "protected static class ")) {
3443                                    return new Tuple(
3444                                            _getClassName(line), _TYPE_CLASS_PROTECTED_STATIC);
3445                            }
3446                    }
3447                    else if (line.startsWith(StringPool.TAB + "protected ")) {
3448                            if (pos != -1) {
3449                                    if (!line.contains(StringPool.EQUAL)) {
3450                                            int spaceCount = StringUtil.count(
3451                                                    line.substring(0, pos), StringPool.SPACE);
3452    
3453                                            if (spaceCount == 1) {
3454                                                    return new Tuple(
3455                                                            _getConstructorOrMethodName(line, pos),
3456                                                            _TYPE_CONSTRUCTOR_PROTECTED);
3457                                            }
3458    
3459                                            if (spaceCount > 1) {
3460                                                    return new Tuple(
3461                                                            _getConstructorOrMethodName(line, pos),
3462                                                            _TYPE_METHOD_PROTECTED);
3463                                            }
3464                                    }
3465                            }
3466                            else if (line.startsWith(StringPool.TAB + "protected class ")) {
3467                                    return new Tuple(_getClassName(line), _TYPE_CLASS_PROTECTED);
3468                            }
3469    
3470                            return new Tuple(_getVariableName(line), _TYPE_VARIABLE_PROTECTED);
3471                    }
3472                    else if (line.startsWith(StringPool.TAB + "private static final ")) {
3473                            if (line.contains(StringPool.EQUAL) ||
3474                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3475    
3476                                    return new Tuple(
3477                                            _getVariableName(line),
3478                                            _TYPE_VARIABLE_PRIVATE_STATIC_FINAL);
3479                            }
3480                    }
3481                    else if (line.startsWith(StringPool.TAB + "private static ")) {
3482                            if (line.contains(StringPool.EQUAL) ||
3483                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3484    
3485                                    return new Tuple(
3486                                            _getVariableName(line), _TYPE_VARIABLE_PRIVATE_STATIC);
3487                            }
3488    
3489                            if (pos != -1) {
3490                                    return new Tuple(
3491                                            _getConstructorOrMethodName(line, pos),
3492                                            _TYPE_METHOD_PRIVATE_STATIC);
3493                            }
3494    
3495                            if (line.startsWith(StringPool.TAB + "private static class ")) {
3496                                    return new Tuple(
3497                                            _getClassName(line), _TYPE_CLASS_PRIVATE_STATIC);
3498                            }
3499                    }
3500                    else if (line.startsWith(StringPool.TAB + "private ")) {
3501                            if (line.contains(StringPool.EQUAL) ||
3502                                    (line.endsWith(StringPool.SEMICOLON) && (pos == -1))) {
3503    
3504                                    return new Tuple(
3505                                            _getVariableName(line), _TYPE_VARIABLE_PRIVATE);
3506                            }
3507    
3508                            if (pos != -1) {
3509                                    int spaceCount = StringUtil.count(
3510                                            line.substring(0, pos), StringPool.SPACE);
3511    
3512                                    if (spaceCount == 1) {
3513                                            return new Tuple(
3514                                                    _getConstructorOrMethodName(line, pos),
3515                                                    _TYPE_CONSTRUCTOR_PRIVATE);
3516                                    }
3517    
3518                                    if (spaceCount > 1) {
3519                                            return new Tuple(
3520                                                    _getConstructorOrMethodName(line, pos),
3521                                                    _TYPE_METHOD_PRIVATE);
3522                                    }
3523                            }
3524                            else if (line.startsWith(StringPool.TAB + "private class ")) {
3525                                    return new Tuple(_getClassName(line), _TYPE_CLASS_PRIVATE);
3526                            }
3527                    }
3528    
3529                    return null;
3530            }
3531    
3532            private static List<String> _getJSPDuplicateImports(
3533                    String fileName, String content, List<String> importLines) {
3534    
3535                    List<String> duplicateImports = new ArrayList<String>();
3536    
3537                    for (String importLine : importLines) {
3538                            int x = content.indexOf("<%@ include file=");
3539    
3540                            if (x == -1) {
3541                                    continue;
3542                            }
3543    
3544                            int y = content.indexOf("<%@ page import=");
3545    
3546                            if (y == -1) {
3547                                    continue;
3548                            }
3549    
3550                            if ((x < y) && _isJSPDuplicateImport(fileName, importLine, false)) {
3551                                    duplicateImports.add(importLine);
3552                            }
3553                    }
3554    
3555                    return duplicateImports;
3556            }
3557    
3558            private static int _getLineLength(String line) {
3559                    int lineLength = 0;
3560    
3561                    int tabLength = 4;
3562    
3563                    for (char c : line.toCharArray()) {
3564                            if (c == CharPool.TAB) {
3565                                    for (int i = 0; i < tabLength; i++) {
3566                                            lineLength++;
3567                                    }
3568    
3569                                    tabLength = 4;
3570                            }
3571                            else {
3572                                    lineLength++;
3573    
3574                                    tabLength--;
3575    
3576                                    if (tabLength <= 0) {
3577                                            tabLength = 4;
3578                                    }
3579                            }
3580                    }
3581    
3582                    return lineLength;
3583            }
3584    
3585            private static String _getOldCopyright() throws IOException {
3586                    String copyright = _fileUtil.read("old-copyright.txt");
3587    
3588                    if (Validator.isNull(copyright)) {
3589                            copyright = _fileUtil.read("../old-copyright.txt");
3590                    }
3591    
3592                    if (Validator.isNull(copyright)) {
3593                            copyright = _fileUtil.read("../../old-copyright.txt");
3594                    }
3595    
3596                    return copyright;
3597            }
3598    
3599            private static Properties _getPluginExclusionsProperties(String fileName)
3600                    throws IOException {
3601    
3602                    FileInputStream fileInputStream = null;
3603    
3604                    int level = 0;
3605    
3606                    try {
3607                            fileInputStream = new FileInputStream(fileName);
3608                    }
3609                    catch (FileNotFoundException fnfe) {
3610                    }
3611    
3612                    if (fileInputStream == null) {
3613                            try {
3614                                    fileInputStream = new FileInputStream("../" + fileName);
3615    
3616                                    level = 1;
3617                            }
3618                            catch (FileNotFoundException fnfe) {
3619                            }
3620                    }
3621    
3622                    if (fileInputStream == null) {
3623                            try {
3624                                    fileInputStream = new FileInputStream("../../" + fileName);
3625    
3626                                    level = 2;
3627                            }
3628                            catch (FileNotFoundException fnfe) {
3629                                    return null;
3630                            }
3631                    }
3632    
3633                    Properties properties = new Properties();
3634    
3635                    properties.load(fileInputStream);
3636    
3637                    if (level > 0) {
3638                            properties = _stripTopLevelDirectories(properties, level);
3639                    }
3640    
3641                    return properties;
3642            }
3643    
3644            private static Collection<String> _getPluginJavaFiles() {
3645                    String basedir = "./";
3646    
3647                    Collection<String> fileNames = new TreeSet<String>();
3648    
3649                    DirectoryScanner directoryScanner = new DirectoryScanner();
3650    
3651                    directoryScanner.setBasedir(basedir);
3652    
3653                    String[] excludes = {
3654                            "**\\bin\\**", "**\\model\\*Clp.java",
3655                            "**\\model\\impl\\*BaseImpl.java", "**\\model\\impl\\*Model.java",
3656                            "**\\model\\impl\\*ModelImpl.java",
3657                            "**\\service\\**\\model\\*Model.java",
3658                            "**\\service\\**\\model\\*Soap.java",
3659                            "**\\service\\**\\model\\*Wrapper.java",
3660                            "**\\service\\**\\service\\*Service.java",
3661                            "**\\service\\**\\service\\*ServiceClp.java",
3662                            "**\\service\\**\\service\\*ServiceFactory.java",
3663                            "**\\service\\**\\service\\*ServiceUtil.java",
3664                            "**\\service\\**\\service\\*ServiceWrapper.java",
3665                            "**\\service\\**\\service\\ClpSerializer.java",
3666                            "**\\service\\**\\service\\messaging\\*ClpMessageListener.java",
3667                            "**\\service\\**\\service\\persistence\\*Finder.java",
3668                            "**\\service\\**\\service\\persistence\\*Persistence.java",
3669                            "**\\service\\**\\service\\persistence\\*Util.java",
3670                            "**\\service\\base\\*ServiceBaseImpl.java",
3671                            "**\\service\\base\\*ServiceClpInvoker.java",
3672                            "**\\service\\http\\*JSONSerializer.java",
3673                            "**\\service\\http\\*ServiceHttp.java",
3674                            "**\\service\\http\\*ServiceJSON.java",
3675                            "**\\service\\http\\*ServiceSoap.java",
3676                            "**\\service\\persistence\\*PersistenceImpl.java", "**\\tmp\\**"
3677                    };
3678    
3679                    excludes = ArrayUtil.append(excludes, _excludes);
3680    
3681                    directoryScanner.setExcludes(excludes);
3682    
3683                    directoryScanner.setIncludes(new String[] {"**\\*.java"});
3684    
3685                    fileNames.addAll(_sourceFormatterHelper.scanForFiles(directoryScanner));
3686    
3687                    return fileNames;
3688            }
3689    
3690            private static Properties _getPortalExclusionsProperties(String fileName)
3691                    throws IOException {
3692    
3693                    Properties properties = new Properties();
3694    
3695                    ClassLoader classLoader = SourceFormatter.class.getClassLoader();
3696    
3697                    String sourceFormatterExclusions = System.getProperty(
3698                            "source-formatter-exclusions",
3699                            "com/liferay/portal/tools/dependencies/" + fileName);
3700    
3701                    URL url = classLoader.getResource(sourceFormatterExclusions);
3702    
3703                    if (url == null) {
3704                            return null;
3705                    }
3706    
3707                    InputStream inputStream = url.openStream();
3708    
3709                    properties.load(inputStream);
3710    
3711                    inputStream.close();
3712    
3713                    return properties;
3714            }
3715    
3716            private static Collection<String> _getPortalJavaFiles() {
3717                    String basedir = "./";
3718    
3719                    Collection<String> fileNames = new TreeSet<String>();
3720    
3721                    DirectoryScanner directoryScanner = new DirectoryScanner();
3722    
3723                    directoryScanner.setBasedir(basedir);
3724    
3725                    String[] excludes = {
3726                            "**\\*_IW.java", "**\\PropsValues.java", "**\\bin\\**",
3727                            "**\\classes\\*", "**\\counter\\service\\**", "**\\jsp\\*",
3728                            "**\\model\\impl\\*BaseImpl.java", "**\\model\\impl\\*Model.java",
3729                            "**\\model\\impl\\*ModelImpl.java", "**\\portal\\service\\**",
3730                            "**\\portal-client\\**",
3731                            "**\\portal-service\\**\\model\\*Model.java",
3732                            "**\\portal-service\\**\\model\\*Soap.java",
3733                            "**\\portal-service\\**\\model\\*Wrapper.java",
3734                            "**\\portal-web\\classes\\**\\*.java",
3735                            "**\\portal-web\\test\\**\\*Test.java",
3736                            "**\\portal-web\\test\\**\\*Tests.java",
3737                            "**\\portlet\\**\\service\\**", "**\\tmp\\**", "**\\tools\\tck\\**"
3738                    };
3739    
3740                    excludes = ArrayUtil.append(excludes, _excludes);
3741    
3742                    directoryScanner.setExcludes(excludes);
3743    
3744                    directoryScanner.setIncludes(new String[] {"**\\*.java"});
3745    
3746                    fileNames.addAll(_sourceFormatterHelper.scanForFiles(directoryScanner));
3747    
3748                    directoryScanner = new DirectoryScanner();
3749    
3750                    directoryScanner.setBasedir(basedir);
3751    
3752                    excludes = new String[] {
3753                            "**\\bin\\**", "**\\portal-client\\**", "**\\tools\\ext_tmpl\\**",
3754                            "**\\*_IW.java", "**\\test\\**\\*PersistenceTest.java"
3755                    };
3756    
3757                    excludes = ArrayUtil.append(excludes, _excludes);
3758    
3759                    directoryScanner.setExcludes(excludes);
3760    
3761                    directoryScanner.setIncludes(
3762                            new String[] {
3763                                    "**\\com\\liferay\\portal\\service\\ServiceContext*.java",
3764                                    "**\\model\\BaseModel.java",
3765                                    "**\\model\\impl\\BaseModelImpl.java",
3766                                    "**\\service\\Base*.java",
3767                                    "**\\service\\PersistedModelLocalService*.java",
3768                                    "**\\service\\base\\PrincipalBean.java",
3769                                    "**\\service\\http\\*HttpTest.java",
3770                                    "**\\service\\http\\*SoapTest.java",
3771                                    "**\\service\\http\\TunnelUtil.java",
3772                                    "**\\service\\impl\\*.java", "**\\service\\jms\\*.java",
3773                                    "**\\service\\permission\\*.java",
3774                                    "**\\service\\persistence\\BasePersistence.java",
3775                                    "**\\service\\persistence\\BatchSession*.java",
3776                                    "**\\service\\persistence\\*FinderImpl.java",
3777                                    "**\\service\\persistence\\*Query.java",
3778                                    "**\\service\\persistence\\impl\\BasePersistenceImpl.java",
3779                                    "**\\portal-impl\\test\\**\\*.java",
3780                                    "**\\portal-service\\**\\liferay\\documentlibrary\\**.java",
3781                                    "**\\portal-service\\**\\liferay\\lock\\**.java",
3782                                    "**\\portal-service\\**\\liferay\\mail\\**.java",
3783                                    "**\\util-bridges\\**\\*.java"
3784                            });
3785    
3786                    fileNames.addAll(_sourceFormatterHelper.scanForFiles(directoryScanner));
3787    
3788                    return fileNames;
3789            }
3790    
3791            private static String _getTaglibRegex(String quoteType) {
3792                    StringBuilder sb = new StringBuilder();
3793    
3794                    sb.append("<(");
3795    
3796                    for (int i = 0; i < _TAG_LIBRARIES.length; i++) {
3797                            sb.append(_TAG_LIBRARIES[i]);
3798                            sb.append(StringPool.PIPE);
3799                    }
3800    
3801                    sb.deleteCharAt(sb.length() - 1);
3802                    sb.append("):([^>]|%>)*");
3803                    sb.append(quoteType);
3804                    sb.append("<%=.*");
3805                    sb.append(quoteType);
3806                    sb.append(".*%>");
3807                    sb.append(quoteType);
3808                    sb.append("([^>]|%>)*>");
3809    
3810                    return sb.toString();
3811            }
3812    
3813            private static String _getVariableName(String line) {
3814                    int x = line.indexOf(StringPool.EQUAL);
3815                    int y = line.lastIndexOf(StringPool.SPACE);
3816    
3817                    if (x != -1) {
3818                            line = line.substring(0, x);
3819                            line = StringUtil.trim(line);
3820    
3821                            y = line.lastIndexOf(StringPool.SPACE);
3822    
3823                            return line.substring(y + 1);
3824                    }
3825    
3826                    if (line.endsWith(StringPool.SEMICOLON)) {
3827                            return line.substring(y + 1, line.length() - 1);
3828                    }
3829    
3830                    return StringPool.BLANK;
3831            }
3832    
3833            private static boolean _isGenerated(String content) {
3834                    if (content.contains("* @generated") || content.contains("$ANTLR")) {
3835                            return true;
3836                    }
3837                    else {
3838                            return false;
3839                    }
3840            }
3841    
3842            private static boolean _isInJavaTermTypeGroup(
3843                    int javaTermType, int[] javaTermTypeGroup) {
3844    
3845                    for (int type : javaTermTypeGroup) {
3846                            if (javaTermType == type) {
3847                                    return true;
3848                            }
3849                    }
3850    
3851                    return false;
3852            }
3853    
3854            private static boolean _isJSPAttributName(String attributeName) {
3855                    if (Validator.isNull(attributeName)) {
3856                            return false;
3857                    }
3858    
3859                    Matcher matcher = _jspAttributeNamePattern.matcher(attributeName);
3860    
3861                    return matcher.matches();
3862            }
3863    
3864            private static boolean _isJSPDuplicateImport(
3865                    String fileName, String importLine, boolean checkFile) {
3866    
3867                    String content = _jspContents.get(fileName);
3868    
3869                    if (Validator.isNull(content)) {
3870                            return false;
3871                    }
3872    
3873                    int x = importLine.indexOf("page");
3874    
3875                    if (x == -1) {
3876                            return false;
3877                    }
3878    
3879                    if (checkFile && content.contains(importLine.substring(x))) {
3880                            return true;
3881                    }
3882    
3883                    int y = content.indexOf("<%@ include file=");
3884    
3885                    if (y == -1) {
3886                            return false;
3887                    }
3888    
3889                    y = content.indexOf(StringPool.QUOTE, y);
3890    
3891                    if (y == -1) {
3892                            return false;
3893                    }
3894    
3895                    int z = content.indexOf(StringPool.QUOTE, y + 1);
3896    
3897                    if (z == -1) {
3898                            return false;
3899                    }
3900    
3901                    String includeFileName = content.substring(y + 1, z);
3902    
3903                    String docrootPath = fileName.substring(
3904                            0, fileName.indexOf("docroot") + 7);
3905    
3906                    includeFileName = docrootPath + includeFileName;
3907    
3908                    return _isJSPDuplicateImport(includeFileName, importLine, true);
3909            }
3910    
3911            private static boolean _isJSPImportRequired(
3912                    String fileName, String className, Set<String> includeFileNames,
3913                    Set<String> checkedFileNames) {
3914    
3915                    if (checkedFileNames.contains(fileName)) {
3916                            return false;
3917                    }
3918    
3919                    checkedFileNames.add(fileName);
3920    
3921                    String content = _jspContents.get(fileName);
3922    
3923                    if (Validator.isNull(content)) {
3924                            return false;
3925                    }
3926    
3927                    Pattern pattern = Pattern.compile(
3928                            "[^A-Za-z0-9_]" + className + "[^A-Za-z0-9_\"]");
3929    
3930                    Matcher matcher = pattern.matcher(content);
3931    
3932                    if (matcher.find()) {
3933                            return true;
3934                    }
3935    
3936                    _addJSPIncludeFileNames(fileName, includeFileNames);
3937    
3938                    String docrootPath = fileName.substring(
3939                            0, fileName.indexOf("docroot") + 7);
3940    
3941                    fileName = fileName.replaceFirst(docrootPath, StringPool.BLANK);
3942    
3943                    if (fileName.endsWith("init.jsp") ||
3944                            fileName.contains("init-ext.jsp")) {
3945    
3946                            _addJSPReferenceFileNames(fileName, includeFileNames);
3947                    }
3948    
3949                    String[] includeFileNamesArray = includeFileNames.toArray(
3950                            new String[includeFileNames.size()]);
3951    
3952                    for (String includeFileName : includeFileNamesArray) {
3953                            if (!checkedFileNames.contains(includeFileName) &&
3954                                    _isJSPImportRequired(
3955                                            includeFileName, className, includeFileNames,
3956                                            checkedFileNames)) {
3957    
3958                                    return true;
3959                            }
3960                    }
3961    
3962                    return false;
3963            }
3964    
3965            private static boolean _isPortalSource() {
3966                    String basedir = "./";
3967    
3968                    if (_fileUtil.exists(basedir + "portal-impl")) {
3969                            return true;
3970                    }
3971                    else {
3972                            return false;
3973                    }
3974            }
3975    
3976            private static boolean _isValidJavaParameter(String javaParameter) {
3977                    int quoteCount = StringUtil.count(javaParameter, StringPool.QUOTE);
3978    
3979                    if ((quoteCount % 2) == 1) {
3980                            return false;
3981                    }
3982    
3983                    javaParameter = _stripQuotes(javaParameter);
3984    
3985                    int openParenthesisCount = StringUtil.count(
3986                            javaParameter, StringPool.OPEN_PARENTHESIS);
3987                    int closeParenthesisCount = StringUtil.count(
3988                            javaParameter, StringPool.CLOSE_PARENTHESIS);
3989                    int lessThanCount = StringUtil.count(
3990                            javaParameter, StringPool.LESS_THAN);
3991                    int greaterThanCount = StringUtil.count(
3992                            javaParameter, StringPool.GREATER_THAN);
3993                    int openCurlyBraceCount = StringUtil.count(
3994                            javaParameter, StringPool.OPEN_CURLY_BRACE);
3995                    int closeCurlyBraceCount = StringUtil.count(
3996                            javaParameter, StringPool.CLOSE_CURLY_BRACE);
3997    
3998                    if ((openParenthesisCount == closeParenthesisCount) &&
3999                            (lessThanCount == greaterThanCount) &&
4000                            (openCurlyBraceCount == closeCurlyBraceCount)) {
4001    
4002                            return true;
4003                    }
4004    
4005                    return false;
4006            }
4007    
4008            private static String _replacePrimitiveWrapperInstantiation(
4009                    String fileName, String line, int lineCount) {
4010    
4011                    if (true) {
4012                            return line;
4013                    }
4014    
4015                    String newLine = StringUtil.replace(
4016                            line,
4017                            new String[] {
4018                                    "new Boolean(", "new Byte(", "new Character(", "new Integer(",
4019                                    "new Long(", "new Short("
4020                            },
4021                            new String[] {
4022                                    "Boolean.valueOf(", "Byte.valueOf(", "Character.valueOf(",
4023                                    "Integer.valueOf(", "Long.valueOf(", "Short.valueOf("
4024                            });
4025    
4026                    if (!line.equals(newLine)) {
4027                            _sourceFormatterHelper.printError(
4028                                    fileName, "> new Primitive(: " + fileName + " " + lineCount);
4029                    }
4030    
4031                    return newLine;
4032            }
4033    
4034            private static String _sortExceptions(String line) {
4035                    if (!line.endsWith(StringPool.OPEN_CURLY_BRACE) &&
4036                            !line.endsWith(StringPool.SEMICOLON)) {
4037    
4038                            return line;
4039                    }
4040    
4041                    int x = line.indexOf("throws ");
4042    
4043                    if (x == -1) {
4044                            return line;
4045                    }
4046    
4047                    String previousException = StringPool.BLANK;
4048    
4049                    String[] exceptions = StringUtil.split(
4050                            line.substring(x), CharPool.SPACE);
4051    
4052                    for (int i = 1; i < exceptions.length; i++) {
4053                            String exception = exceptions[i];
4054    
4055                            if (exception.equals(StringPool.OPEN_CURLY_BRACE)) {
4056                                    break;
4057                            }
4058    
4059                            if (exception.endsWith(StringPool.COMMA) ||
4060                                    exception.endsWith(StringPool.SEMICOLON)) {
4061    
4062                                    exception = exception.substring(0, exception.length() - 1);
4063                            }
4064    
4065                            if (Validator.isNotNull(previousException) &&
4066                                    (previousException.compareToIgnoreCase(exception) > 0)) {
4067    
4068                                    return StringUtil.replace(
4069                                            line, previousException + ", " + exception,
4070                                            exception + ", " + previousException);
4071                            }
4072    
4073                            previousException = exception;
4074                    }
4075    
4076                    return line;
4077            }
4078    
4079            private static String _sortJSPAttributes(
4080                    String fileName, String line, int lineCount) {
4081    
4082                    String s = line;
4083    
4084                    int x = s.indexOf(StringPool.SPACE);
4085    
4086                    if (x == -1) {
4087                            return line;
4088                    }
4089    
4090                    s = s.substring(x + 1);
4091    
4092                    String previousAttribute = null;
4093                    String previousAttributeAndValue = null;
4094    
4095                    boolean wrongOrder = false;
4096    
4097                    for (x = 0;;) {
4098                            x = s.indexOf(StringPool.EQUAL);
4099    
4100                            if ((x == -1) || (s.length() <= (x + 1))) {
4101                                    return line;
4102                            }
4103    
4104                            String attribute = s.substring(0, x);
4105    
4106                            if (!_isJSPAttributName(attribute)) {
4107                                    return line;
4108                            }
4109    
4110                            if (Validator.isNotNull(previousAttribute) &&
4111                                    (previousAttribute.compareTo(attribute) > 0)) {
4112    
4113                                    wrongOrder = true;
4114                            }
4115    
4116                            s = s.substring(x + 1);
4117    
4118                            char delimeter = s.charAt(0);
4119    
4120                            if ((delimeter != CharPool.APOSTROPHE) &&
4121                                    (delimeter != CharPool.QUOTE)) {
4122    
4123                                    _sourceFormatterHelper.printError(
4124                                            fileName, "delimeter: " + fileName + " " + lineCount);
4125    
4126                                    return line;
4127                            }
4128    
4129                            s = s.substring(1);
4130    
4131                            int y = s.indexOf(delimeter);
4132    
4133                            if ((y == -1) || (s.length() <= (y + 1))) {
4134                                    return line;
4135                            }
4136    
4137                            String value = s.substring(0, y);
4138    
4139                            if ((delimeter == CharPool.APOSTROPHE) &&
4140                                    !value.contains(StringPool.QUOTE)) {
4141    
4142                                    return StringUtil.replace(
4143                                            line, StringPool.APOSTROPHE + value + StringPool.APOSTROPHE,
4144                                            StringPool.QUOTE + value + StringPool.QUOTE);
4145                            }
4146    
4147                            if (value.contains("<%") && !value.contains("%>")) {
4148                                    int z = s.indexOf("%>");
4149    
4150                                    if (z == -1) {
4151                                            return line;
4152                                    }
4153    
4154                                    y = s.substring(z).indexOf(delimeter);
4155    
4156                                    value = s.substring(0, y + z);
4157                            }
4158    
4159                            StringBundler sb = new StringBundler(5);
4160    
4161                            sb.append(attribute);
4162                            sb.append(StringPool.EQUAL);
4163                            sb.append(delimeter);
4164                            sb.append(value);
4165                            sb.append(delimeter);
4166    
4167                            String currentAttributeAndValue = sb.toString();
4168    
4169                            if (wrongOrder) {
4170                                    if (line.contains(currentAttributeAndValue) &&
4171                                            line.contains(previousAttributeAndValue)) {
4172    
4173                                            line = StringUtil.replaceFirst(
4174                                                    line, previousAttributeAndValue,
4175                                                    currentAttributeAndValue);
4176    
4177                                            line = StringUtil.replaceLast(
4178                                                    line, currentAttributeAndValue,
4179                                                    previousAttributeAndValue);
4180                                    }
4181    
4182                                    return line;
4183                            }
4184    
4185                            s = s.substring(y + 1);
4186    
4187                            s = StringUtil.trimLeading(s);
4188    
4189                            previousAttribute = attribute;
4190                            previousAttributeAndValue = currentAttributeAndValue;
4191                    }
4192            }
4193    
4194            private static String _stripJSPImports(String fileName, String content)
4195                    throws IOException {
4196    
4197                    fileName = fileName.replace(
4198                            CharPool.BACK_SLASH, CharPool.FORWARD_SLASH);
4199    
4200                    if (!fileName.contains("docroot") ||
4201                            fileName.endsWith("init-ext.jsp")) {
4202    
4203                            return content;
4204                    }
4205    
4206                    Matcher matcher = _jspImportPattern.matcher(content);
4207    
4208                    if (!matcher.find()) {
4209                            return content;
4210                    }
4211    
4212                    String imports = matcher.group();
4213    
4214                    imports = StringUtil.replace(
4215                            imports, new String[] {"%><%@\r\n", "%><%@\n"},
4216                            new String[] {"%>\r\n<%@ ", "%>\n<%@ "});
4217    
4218                    if (!fileName.endsWith("html/common/init.jsp") &&
4219                            !fileName.endsWith("html/portal/init.jsp")) {
4220    
4221                            List<String> importLines = new ArrayList<String>();
4222    
4223                            UnsyncBufferedReader unsyncBufferedReader =
4224                                    new UnsyncBufferedReader(new UnsyncStringReader(imports));
4225    
4226                            String line = null;
4227    
4228                            while ((line = unsyncBufferedReader.readLine()) != null) {
4229                                    if (line.contains("import=")) {
4230                                            importLines.add(line);
4231                                    }
4232                            }
4233    
4234                            List<String> unneededImports = _getJSPDuplicateImports(
4235                                    fileName, content, importLines);
4236    
4237                            _addJSPUnusedImports(fileName, importLines, unneededImports);
4238    
4239                            for (String unneededImport : unneededImports) {
4240                                    imports = StringUtil.replace(
4241                                            imports, unneededImport, StringPool.BLANK);
4242                            }
4243                    }
4244    
4245                    imports = _formatImports(imports, 17);
4246    
4247                    String beforeImports = content.substring(0, matcher.start());
4248    
4249                    if (Validator.isNull(imports)) {
4250                            beforeImports = StringUtil.replaceLast(
4251                                    beforeImports, "\n", StringPool.BLANK);
4252                    }
4253    
4254                    String afterImports = content.substring(matcher.end());
4255    
4256                    if (Validator.isNull(afterImports)) {
4257                            imports = StringUtil.replaceLast(imports, "\n", StringPool.BLANK);
4258    
4259                            content = beforeImports + imports;
4260    
4261                            return content;
4262                    }
4263    
4264                    content = beforeImports + imports + "\n" + afterImports;
4265    
4266                    return content;
4267            }
4268    
4269            private static String _stripRedundantParentheses(String s) {
4270                    for (int x = 0;;) {
4271                            x = s.indexOf(StringPool.OPEN_PARENTHESIS, x + 1);
4272                            int y = s.indexOf(StringPool.CLOSE_PARENTHESIS, x);
4273    
4274                            if ((x == -1) || (y == -1)) {
4275                                    return s;
4276                            }
4277    
4278                            String linePart = s.substring(x + 1, y);
4279    
4280                            linePart = StringUtil.replace(
4281                                    linePart, StringPool.COMMA, StringPool.BLANK);
4282    
4283                            if (Validator.isAlphanumericName(linePart) ||
4284                                    Validator.isNull(linePart)) {
4285    
4286                                    s = s.substring(0, x) + s.substring(y + 1);
4287                            }
4288                    }
4289            }
4290    
4291            private static String _stripQuotes(String s) {
4292                    String[] parts = StringUtil.split(s, CharPool.QUOTE);
4293    
4294                    int i = 1;
4295    
4296                    while (i < parts.length) {
4297                            s = StringUtil.replaceFirst(
4298                                    s, StringPool.QUOTE + parts[i] + StringPool.QUOTE,
4299                                    StringPool.BLANK);
4300    
4301                            i = i + 2;
4302                    }
4303    
4304                    return s;
4305            }
4306    
4307            private static Properties _stripTopLevelDirectories(
4308                            Properties properties, int level)
4309                    throws IOException {
4310    
4311                    File dir = new File(".");
4312    
4313                    String dirName = dir.getCanonicalPath();
4314    
4315                    dirName = StringUtil.replace(
4316                            dirName, StringPool.BACK_SLASH, StringPool.SLASH);
4317    
4318                    int pos = dirName.length();
4319    
4320                    for (int i = 0; i < level; i++) {
4321                            pos = dirName.lastIndexOf(StringPool.SLASH, pos - 1);
4322                    }
4323    
4324                    String topLevelDirNames = dirName.substring(pos + 1) + StringPool.SLASH;
4325    
4326                    Properties newProperties = new Properties();
4327    
4328                    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
4329                            String key = (String)entry.getKey();
4330    
4331                            if (!key.startsWith(topLevelDirNames)) {
4332                                    continue;
4333                            }
4334    
4335                            key = StringUtil.replaceFirst(
4336                                    key, topLevelDirNames, StringPool.BLANK);
4337    
4338                            String value = (String)entry.getValue();
4339    
4340                            newProperties.setProperty(key, value);
4341                    }
4342    
4343                    return newProperties;
4344            }
4345    
4346            private static String _trimContent(String content) throws IOException {
4347                    StringBundler sb = new StringBundler();
4348    
4349                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
4350                            new UnsyncStringReader(content));
4351    
4352                    String line = null;
4353    
4354                    while ((line = unsyncBufferedReader.readLine()) != null) {
4355                            sb.append(_trimLine(line));
4356                            sb.append("\n");
4357                    }
4358    
4359                    unsyncBufferedReader.close();
4360    
4361                    content = sb.toString();
4362    
4363                    if (content.endsWith("\n")) {
4364                            content = content.substring(0, content.length() - 1);
4365                    }
4366    
4367                    return content;
4368            }
4369    
4370            private static String _trimLine(String line) {
4371                    if (line.trim().length() == 0) {
4372                            return StringPool.BLANK;
4373                    }
4374    
4375                    line = StringUtil.trimTrailing(line);
4376    
4377                    if (!line.startsWith(StringPool.SPACE) || line.startsWith(" *")) {
4378                            return line;
4379                    }
4380    
4381                    if (!line.startsWith(StringPool.FOUR_SPACES)) {
4382                            while (line.startsWith(StringPool.SPACE)) {
4383                                    line = StringUtil.replaceFirst(
4384                                            line, StringPool.SPACE, StringPool.BLANK);
4385                            }
4386                    }
4387                    else {
4388                            int pos = 0;
4389    
4390                            String temp = line;
4391    
4392                            while (temp.startsWith(StringPool.FOUR_SPACES)) {
4393                                    line = StringUtil.replaceFirst(
4394                                            line, StringPool.FOUR_SPACES, StringPool.TAB);
4395    
4396                                    pos++;
4397    
4398                                    temp = line.substring(pos);
4399                            }
4400                    }
4401    
4402                    return line;
4403            }
4404    
4405            private static final String[] _TAG_LIBRARIES = new String[] {
4406                    "aui", "c", "html", "jsp", "liferay-portlet", "liferay-security",
4407                    "liferay-theme", "liferay-ui", "liferay-util", "portlet", "struts",
4408                    "tiles"
4409            };
4410    
4411            private static final int _TYPE_CLASS_PRIVATE = 24;
4412    
4413            private static final int _TYPE_CLASS_PRIVATE_STATIC = 23;
4414    
4415            private static final int _TYPE_CLASS_PROTECTED = 16;
4416    
4417            private static final int _TYPE_CLASS_PROTECTED_STATIC = 15;
4418    
4419            private static final int _TYPE_CLASS_PUBLIC = 8;
4420    
4421            private static final int _TYPE_CLASS_PUBLIC_STATIC = 7;
4422    
4423            private static final int[] _TYPE_CONSTRUCTOR = {
4424                    SourceFormatter._TYPE_CONSTRUCTOR_PRIVATE,
4425                    SourceFormatter._TYPE_CONSTRUCTOR_PROTECTED,
4426                    SourceFormatter._TYPE_CONSTRUCTOR_PUBLIC
4427            };
4428    
4429            private static final int _TYPE_CONSTRUCTOR_PRIVATE = 18;
4430    
4431            private static final int _TYPE_CONSTRUCTOR_PROTECTED = 10;
4432    
4433            private static final int _TYPE_CONSTRUCTOR_PUBLIC = 4;
4434    
4435            private static final int[] _TYPE_METHOD = {
4436                    SourceFormatter._TYPE_METHOD_PRIVATE,
4437                    SourceFormatter._TYPE_METHOD_PRIVATE_STATIC,
4438                    SourceFormatter._TYPE_METHOD_PROTECTED,
4439                    SourceFormatter._TYPE_METHOD_PROTECTED_STATIC,
4440                    SourceFormatter._TYPE_METHOD_PUBLIC,
4441                    SourceFormatter._TYPE_METHOD_PUBLIC_STATIC
4442            };
4443    
4444            private static final int _TYPE_METHOD_PRIVATE = 19;
4445    
4446            private static final int _TYPE_METHOD_PRIVATE_STATIC = 17;
4447    
4448            private static final int _TYPE_METHOD_PROTECTED = 11;
4449    
4450            private static final int _TYPE_METHOD_PROTECTED_STATIC = 9;
4451    
4452            private static final int _TYPE_METHOD_PUBLIC = 5;
4453    
4454            private static final int _TYPE_METHOD_PUBLIC_STATIC = 3;
4455    
4456            private static final int[] _TYPE_VARIABLE_NOT_FINAL = {
4457                    SourceFormatter._TYPE_VARIABLE_PRIVATE,
4458                    SourceFormatter._TYPE_VARIABLE_PRIVATE_STATIC,
4459                    SourceFormatter._TYPE_VARIABLE_PROTECTED,
4460                    SourceFormatter._TYPE_VARIABLE_PROTECTED_STATIC,
4461                    SourceFormatter._TYPE_VARIABLE_PUBLIC,
4462                    SourceFormatter._TYPE_VARIABLE_PUBLIC_STATIC
4463            };
4464    
4465            private static final int _TYPE_VARIABLE_PRIVATE = 22;
4466    
4467            private static final int _TYPE_VARIABLE_PRIVATE_STATIC = 21;
4468    
4469            private static final int _TYPE_VARIABLE_PRIVATE_STATIC_FINAL = 20;
4470    
4471            private static final int _TYPE_VARIABLE_PROTECTED = 14;
4472    
4473            private static final int _TYPE_VARIABLE_PROTECTED_STATIC = 13;
4474    
4475            private static final int _TYPE_VARIABLE_PROTECTED_STATIC_FINAL = 12;
4476    
4477            private static final int _TYPE_VARIABLE_PUBLIC = 6;
4478    
4479            private static final int _TYPE_VARIABLE_PUBLIC_STATIC = 2;
4480    
4481            private static final int _TYPE_VARIABLE_PUBLIC_STATIC_FINAL = 1;
4482    
4483            private static String[] _excludes;
4484            private static FileImpl _fileUtil = FileImpl.getInstance();
4485            private static Pattern _javaImportPattern = Pattern.compile(
4486                    "(^[ \t]*import\\s+.*;\n+)+", Pattern.MULTILINE);
4487            private static Properties _javaTermAlphabetizeExclusionsProperties;
4488            private static Pattern _jspAttributeNamePattern = Pattern.compile(
4489                    "[a-z]+[-_a-zA-Z0-9]*");
4490            private static Map<String, String> _jspContents =
4491                    new HashMap<String, String>();
4492            private static Pattern _jspImportPattern = Pattern.compile(
4493                    "(<.*\n*page.import=\".*>\n*)+", Pattern.MULTILINE);
4494            private static Pattern _jspIncludeFilePattern = Pattern.compile(
4495                    "/.*[.]jsp[f]?");
4496            private static Properties _lineLengthExclusionsProperties;
4497            private static boolean _portalSource;
4498            private static SAXReaderImpl _saxReaderUtil = SAXReaderImpl.getInstance();
4499            private static SourceFormatterHelper _sourceFormatterHelper;
4500            private static Pattern _xssPattern = Pattern.compile(
4501                    "String\\s+([^\\s]+)\\s*=\\s*(Bean)?ParamUtil\\.getString\\(");
4502    
4503    }