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