1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   * 
13   */
14  
15  package com.liferay.portal.tools;
16  
17  import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
18  import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
19  import com.liferay.portal.kernel.util.CharPool;
20  import com.liferay.portal.kernel.util.ClassUtil;
21  import com.liferay.portal.kernel.util.ListUtil;
22  import com.liferay.portal.kernel.util.StringPool;
23  import com.liferay.portal.kernel.util.StringUtil;
24  import com.liferay.portal.util.ContentUtil;
25  import com.liferay.portal.util.FileImpl;
26  import com.liferay.portal.util.PropsValues;
27  
28  import java.io.File;
29  import java.io.InputStream;
30  import java.io.IOException;
31  import java.net.URL;
32  import java.util.ArrayList;
33  import java.util.Arrays;
34  import java.util.HashSet;
35  import java.util.List;
36  import java.util.Properties;
37  import java.util.Set;
38  import java.util.TreeSet;
39  import java.util.regex.Matcher;
40  import java.util.regex.Pattern;
41  
42  import org.apache.tools.ant.DirectoryScanner;
43  
44  /**
45   * <a href="SourceFormatter.java.html"><b><i>View Source</i></b></a>
46   *
47   * @author Brian Wing Shun Chan
48   */
49  public class SourceFormatter {
50  
51      public static void main(String[] args) {
52          try {
53              _readExclusions();
54  
55              Thread thread1 = new Thread () {
56                  public void run() {
57                      try {
58                          _checkPersistenceTestSuite();
59                          _checkWebXML();
60                          _formatJSP();
61                      }
62                      catch (Exception e) {
63                          e.printStackTrace();
64                      }
65                  }
66              };
67  
68              Thread thread2 = new Thread () {
69                  public void run() {
70                      try {
71                          _formatJava();
72                      }
73                      catch (Exception e) {
74                          e.printStackTrace();
75                      }
76                  }
77              };
78  
79              thread1.start();
80              thread2.start();
81  
82              thread1.join();
83              thread2.join();
84          }
85          catch (Exception e) {
86              e.printStackTrace();
87          }
88      }
89  
90      public static String stripImports(
91              String content, String packageDir, String className)
92          throws IOException {
93  
94          int x = content.indexOf("import ");
95  
96          if (x == -1) {
97              return content;
98          }
99  
100         int y = content.indexOf("{", x);
101 
102         y = content.substring(0, y).lastIndexOf(";") + 1;
103 
104         String imports = _formatImports(content.substring(x, y));
105 
106         content =
107             content.substring(0, x) + imports +
108                 content.substring(y + 1, content.length());
109 
110         Set<String> classes = ClassUtil.getClasses(
111             new UnsyncStringReader(content), className);
112 
113         x = content.indexOf("import ");
114 
115         y = content.indexOf("{", x);
116 
117         y = content.substring(0, y).lastIndexOf(";") + 1;
118 
119         imports = content.substring(x, y);
120 
121         StringBuilder sb = new StringBuilder();
122 
123         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
124             new UnsyncStringReader(imports));
125 
126         String line = null;
127 
128         while ((line = unsyncBufferedReader.readLine()) != null) {
129             if (line.indexOf("import ") != -1) {
130                 int importX = line.indexOf(" ");
131                 int importY = line.lastIndexOf(".");
132 
133                 String importPackage = line.substring(importX + 1, importY);
134                 String importClass = line.substring(
135                     importY + 1, line.length() - 1);
136 
137                 if (!packageDir.equals(importPackage)) {
138                     if (!importClass.equals("*")) {
139                         if (classes.contains(importClass)) {
140                             sb.append(line);
141                             sb.append("\n");
142                         }
143                     }
144                     else {
145                         sb.append(line);
146                         sb.append("\n");
147                     }
148                 }
149             }
150         }
151 
152         imports = _formatImports(sb.toString());
153 
154         content =
155             content.substring(0, x) + imports +
156                 content.substring(y + 1, content.length());
157 
158         return content;
159     }
160 
161     public static void _checkPersistenceTestSuite() throws IOException {
162         String basedir = "./portal-impl/test";
163 
164         if (!_fileUtil.exists(basedir)) {
165             return;
166         }
167 
168         DirectoryScanner ds = new DirectoryScanner();
169 
170         ds.setBasedir(basedir);
171         ds.setIncludes(new String[] {"**\\*PersistenceTest.java"});
172 
173         ds.scan();
174 
175         String[] files = ds.getIncludedFiles();
176 
177         Set<String> persistenceTests = new HashSet<String>();
178 
179         for (String file : files) {
180             String persistenceTest = file.substring(0, file.length() - 5);
181 
182             persistenceTest = persistenceTest.substring(
183                 persistenceTest.lastIndexOf(File.separator) + 1,
184                 persistenceTest.length());
185 
186             persistenceTests.add(persistenceTest);
187         }
188 
189         String persistenceTestSuite = _fileUtil.read(
190             basedir + "/com/liferay/portal/service/persistence/" +
191                 "PersistenceTestSuite.java");
192 
193         for (String persistenceTest : persistenceTests) {
194             if (persistenceTestSuite.indexOf(persistenceTest) == -1) {
195                 System.out.println("PersistenceTestSuite: " + persistenceTest);
196             }
197         }
198     }
199 
200     private static void _checkWebXML() throws IOException {
201         String basedir = "./";
202 
203         if (_fileUtil.exists(basedir + "portal-impl")) {
204             String[] locales = PropsValues.LOCALES.clone();
205 
206             Arrays.sort(locales);
207 
208             Set<String> urlPatterns = new TreeSet<String>();
209 
210             for (String locale : locales) {
211                 int pos = locale.indexOf(StringPool.UNDERLINE);
212 
213                 String languageCode = locale.substring(0, pos);
214 
215                 urlPatterns.add(languageCode);
216                 urlPatterns.add(locale);
217             }
218 
219             StringBuilder sb = new StringBuilder();
220 
221             for (String urlPattern : urlPatterns) {
222                 sb.append("\t<servlet-mapping>\n");
223                 sb.append("\t\t<servlet-name>I18n Servlet</servlet-name>\n");
224                 sb.append(
225                     "\t\t<url-pattern>/" + urlPattern +"/*</url-pattern>\n");
226                 sb.append("\t</servlet-mapping>\n");
227             }
228 
229             File file = new File(
230                 basedir + "portal-web/docroot/WEB-INF/web.xml");
231 
232             String content = _fileUtil.read(file);
233 
234             int x = content.indexOf("<servlet-mapping>");
235 
236             x = content.indexOf("<servlet-name>I18n Servlet</servlet-name>", x);
237 
238             x = content.lastIndexOf("<servlet-mapping>", x) - 1;
239 
240             int y = content.lastIndexOf(
241                 "<servlet-name>I18n Servlet</servlet-name>");
242 
243             y = content.indexOf("</servlet-mapping>", y) + 19;
244 
245             String newContent =
246                 content.substring(0, x) + sb.toString() + content.substring(y);
247 
248             if ((newContent != null) && !content.equals(newContent)) {
249                 _fileUtil.write(file, newContent);
250 
251                 System.out.println(file);
252             }
253         }
254         else {
255             String webXML = ContentUtil.get(
256                 "com/liferay/portal/deploy/dependencies/web.xml");
257 
258             DirectoryScanner ds = new DirectoryScanner();
259 
260             ds.setBasedir(basedir);
261             ds.setIncludes(new String[] {"**\\web.xml"});
262 
263             ds.scan();
264 
265             String[] files = ds.getIncludedFiles();
266 
267             for (String file : files) {
268                 String content = _fileUtil.read(basedir + file);
269 
270                 if (content.equals(webXML)) {
271                     System.out.println(file);
272                 }
273             }
274         }
275     }
276 
277     private static void _checkXSS(String fileName, String jspContent) {
278         Matcher matcher = _xssPattern.matcher(jspContent);
279 
280         while (matcher.find()) {
281             boolean xssVulnerable = false;
282 
283             String jspVariable = matcher.group(1);
284 
285             String inputVulnerability =
286                 "<input[^>]* value=\"<%= " + jspVariable + " %>";
287 
288             Pattern inputVulnerabilityPattern =
289                 Pattern.compile(inputVulnerability, Pattern.CASE_INSENSITIVE);
290 
291             Matcher inputVulnerabilityMatcher =
292                 inputVulnerabilityPattern.matcher(jspContent);
293 
294             if (inputVulnerabilityMatcher.find()) {
295                 xssVulnerable = true;
296             }
297 
298             String anchorVulnerability = " href=\"<%= " + jspVariable + " %>";
299 
300             if (jspContent.indexOf(anchorVulnerability) != -1) {
301                 xssVulnerable = true;
302             }
303 
304             String inlineStringVulnerability1 = "'<%= " + jspVariable + " %>";
305 
306             if (jspContent.indexOf(inlineStringVulnerability1) != -1) {
307                 xssVulnerable = true;
308             }
309 
310             String inlineStringVulnerability2 = "(\"<%= " + jspVariable + " %>";
311 
312             if (jspContent.indexOf(inlineStringVulnerability2) != -1) {
313                 xssVulnerable = true;
314             }
315 
316             String inlineStringVulnerability3 = " \"<%= " + jspVariable + " %>";
317 
318             if (jspContent.indexOf(inlineStringVulnerability3) != -1) {
319                 xssVulnerable = true;
320             }
321 
322             String documentIdVulnerability = ".<%= " + jspVariable + " %>";
323 
324             if (jspContent.indexOf(documentIdVulnerability) != -1) {
325                 xssVulnerable = true;
326             }
327 
328             if (xssVulnerable) {
329                 System.out.println(
330                     "(xss): " + fileName + " (" + jspVariable + ")");
331             }
332         }
333     }
334 
335     public static String _formatImports(String imports) throws IOException {
336         if ((imports.indexOf("/*") != -1) ||
337             (imports.indexOf("*/") != -1) ||
338             (imports.indexOf("//") != -1)) {
339 
340             return imports + "\n";
341         }
342 
343         List<String> importsList = new ArrayList<String>();
344 
345         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
346             new UnsyncStringReader(imports));
347 
348         String line = null;
349 
350         while ((line = unsyncBufferedReader.readLine()) != null) {
351             if (line.indexOf("import ") != -1) {
352                 if (!importsList.contains(line)) {
353                     importsList.add(line);
354                 }
355             }
356         }
357 
358         importsList = ListUtil.sort(importsList);
359 
360         StringBuilder sb = new StringBuilder();
361 
362         String temp = null;
363 
364         for (int i = 0; i < importsList.size(); i++) {
365             String s = importsList.get(i);
366 
367             int pos = s.indexOf(".");
368 
369             pos = s.indexOf(".", pos + 1);
370 
371             if (pos == -1) {
372                 pos = s.indexOf(".");
373             }
374 
375             String packageLevel = s.substring(7, pos);
376 
377             if ((i != 0) && (!packageLevel.equals(temp))) {
378                 sb.append("\n");
379             }
380 
381             temp = packageLevel;
382 
383             sb.append(s);
384             sb.append("\n");
385         }
386 
387         return sb.toString();
388     }
389 
390     private static void _formatJava() throws IOException {
391         String basedir = "./";
392 
393         String copyright = _getCopyright();
394         String oldCopyright = _getOldCopyright();
395 
396         boolean portalJavaFiles = true;
397 
398         String[] files = null;
399 
400         if (_fileUtil.exists(basedir + "portal-impl")) {
401             files = _getPortalJavaFiles();
402         }
403         else {
404             portalJavaFiles = false;
405 
406             files = _getPluginJavaFiles();
407         }
408 
409         for (int i = 0; i < files.length; i++) {
410             File file = new File(basedir + files[i]);
411 
412             String content = _fileUtil.read(file);
413 
414             String className = file.getName();
415 
416             className = className.substring(0, className.length() - 5);
417 
418             String packagePath = files[i];
419 
420             int packagePathX = packagePath.indexOf(
421                 File.separator + "src" + File.separator);
422             int packagePathY = packagePath.lastIndexOf(File.separator);
423 
424             if ((packagePathX + 5) >= packagePathY) {
425                 packagePath = StringPool.BLANK;
426             }
427             else {
428                 packagePath = packagePath.substring(
429                     packagePathX + 5, packagePathY);
430             }
431 
432             packagePath = StringUtil.replace(
433                 packagePath, File.separator, StringPool.PERIOD);
434 
435             if (packagePath.endsWith(".model")) {
436                 if (content.indexOf(
437                         "extends " + className + "Model {") != -1) {
438 
439                     continue;
440                 }
441             }
442 
443             String newContent = _formatJavaContent(
444                 files[i], className, content);
445 
446             if (newContent.indexOf("$\n */") != -1) {
447                 System.out.println("*: " + files[i]);
448 
449                 newContent = StringUtil.replace(
450                     newContent, "$\n */", "$\n *\n */");
451             }
452 
453             if ((oldCopyright != null) && newContent.contains(oldCopyright)) {
454                 newContent = StringUtil.replace(
455                     newContent, oldCopyright, copyright);
456 
457                 System.out.println("old (c): " + files[i]);
458             }
459 
460             if (newContent.indexOf(copyright) == -1) {
461                 System.out.println("(c): " + files[i]);
462             }
463 
464             if (newContent.indexOf(className + ".java.html") == -1) {
465                 System.out.println("Java2HTML: " + files[i]);
466             }
467 
468             if (newContent.contains(" * @author Raymond Aug") && 
469                 !newContent.contains(" * @author Raymond Aug\u00e9")) {
470 
471                 newContent = newContent.replaceFirst(
472                     "Raymond Aug.++", "Raymond Aug\u00e9");
473 
474                 System.out.println("UTF-8: " + files[i]);
475             }
476 
477             if (newContent.contains("com.liferay.util.LocalizationUtil")) {
478                 newContent = StringUtil.replace(
479                     newContent, "com.liferay.util.LocalizationUtil",
480                     "com.liferay.portal.kernel.util.LocalizationUtil");
481             }
482 
483             newContent = stripImports(newContent, packagePath, className);
484 
485             if (newContent.indexOf(";\n/**") != -1) {
486                 newContent = StringUtil.replace(
487                     newContent,
488                     ";\n/**",
489                     ";\n\n/**");
490             }
491 
492             if (newContent.indexOf("\t/*\n\t *") != -1) {
493                 newContent = StringUtil.replace(
494                     newContent,
495                     "\t/*\n\t *",
496                     "\t/**\n\t *");
497             }
498 
499             if (newContent.indexOf("if(") != -1) {
500                 newContent = StringUtil.replace(
501                     newContent,
502                     "if(",
503                     "if (");
504             }
505 
506             if (newContent.indexOf("while(") != -1) {
507                 newContent = StringUtil.replace(
508                     newContent,
509                     "while(",
510                     "while (");
511             }
512 
513             if (newContent.indexOf("\n\n\n") != -1) {
514                 newContent = StringUtil.replace(
515                     newContent,
516                     "\n\n\n",
517                     "\n\n");
518             }
519 
520             if (newContent.indexOf("*/\npackage ") != -1) {
521                 System.out.println("package: " + files[i]);
522             }
523 
524             if (newContent.indexOf("    ") != -1) {
525                 if (!files[i].endsWith("StringPool.java")) {
526                     System.out.println("tab: " + files[i]);
527                 }
528             }
529 
530             if (newContent.indexOf("  {") != -1) {
531                 System.out.println("{:" + files[i]);
532             }
533 
534             if (!newContent.endsWith("\n\n}") &&
535                 !newContent.endsWith("{\n}")) {
536 
537                 System.out.println("}: " + files[i]);
538             }
539 
540             if (portalJavaFiles && className.endsWith("ServiceImpl") &&
541                 (newContent.indexOf("ServiceUtil.") != -1)) {
542 
543                 System.out.println("ServiceUtil: " + files[i]);
544             }
545 
546             if ((newContent != null) && !content.equals(newContent)) {
547                 _fileUtil.write(file, newContent);
548 
549                 System.out.println(file);
550             }
551         }
552     }
553 
554     private static String _formatJavaContent(
555             String fileName, String className, String content)
556         throws IOException {
557 
558         boolean longLogFactoryUtil = false;
559 
560         StringBuilder sb = new StringBuilder();
561 
562         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
563             new UnsyncStringReader(content));
564 
565         int lineCount = 0;
566 
567         String line = null;
568 
569         while ((line = unsyncBufferedReader.readLine()) != null) {
570             lineCount++;
571 
572             if (line.trim().length() == 0) {
573                 line = StringPool.BLANK;
574             }
575 
576             line = StringUtil.trimTrailing(line);
577 
578             line = StringUtil.replace(
579                 line,
580                 new String[] {
581                     "* Copyright (c) 2000-2009 Liferay, Inc."
582                 },
583                 new String[] {
584                     "* Copyright (c) 2000-2010 Liferay, Inc."
585                 });
586 
587             sb.append(line);
588             sb.append("\n");
589 
590             StringBuilder lineSB = new StringBuilder();
591 
592             int spacesPerTab = 4;
593 
594             for (char c : line.toCharArray()) {
595                 if (c == CharPool.TAB) {
596                     for (int i = 0; i < spacesPerTab; i++) {
597                         lineSB.append(CharPool.SPACE);
598                     }
599 
600                     spacesPerTab = 4;
601                 }
602                 else {
603                     lineSB.append(c);
604 
605                     spacesPerTab--;
606 
607                     if (spacesPerTab <= 0) {
608                         spacesPerTab = 4;
609                     }
610                 }
611             }
612 
613             line = lineSB.toString();
614 
615             if (line.endsWith("private static Log _log =")) {
616                 longLogFactoryUtil = true;
617             }
618 
619             String excluded = _exclusions.getProperty(
620                 StringUtil.replace(fileName, "\\", "/") + StringPool.AT +
621                     lineCount);
622 
623             if (excluded == null) {
624                 excluded = _exclusions.getProperty(
625                     StringUtil.replace(fileName, "\\", "/"));
626             }
627 
628             if ((excluded == null) && (line.length() > 80) &&
629                 !line.startsWith("import ") && !line.startsWith("package ")) {
630 
631                 if (fileName.endsWith("Table.java") &&
632                     line.contains("String TABLE_SQL_CREATE = ")) {
633                 }
634                 else {
635                     System.out.println("> 80: " + fileName + " " + lineCount);
636                 }
637             }
638         }
639 
640         unsyncBufferedReader.close();
641 
642         String newContent = sb.toString();
643 
644         if (newContent.endsWith("\n")) {
645             newContent = newContent.substring(0, newContent.length() -1);
646         }
647 
648         if (longLogFactoryUtil) {
649             newContent = StringUtil.replace(
650                 newContent,
651                 "private static Log _log =\n\t\tLogFactoryUtil.getLog(",
652                 "private static Log _log = LogFactoryUtil.getLog(\n\t\t");
653         }
654 
655         return newContent;
656     }
657 
658     private static void _formatJSP() throws IOException {
659         String basedir = "./";
660 
661         List<String> list = new ArrayList<String>();
662 
663         DirectoryScanner ds = new DirectoryScanner();
664 
665         ds.setBasedir(basedir);
666         ds.setExcludes(
667             new String[] {
668                 "**\\bin\\**", "**\\null.jsp", "**\\tmp\\**",
669                 "**\\tools\\tck\\**"
670             });
671         ds.setIncludes(new String[] {"**\\*.jsp", "**\\*.jspf", "**\\*.vm"});
672 
673         ds.scan();
674 
675         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
676 
677         String copyright = _getCopyright();
678         String oldCopyright = _getOldCopyright();
679 
680         String[] files = list.toArray(new String[list.size()]);
681 
682         for (int i = 0; i < files.length; i++) {
683             File file = new File(basedir + files[i]);
684 
685             String content = _fileUtil.read(file);
686             String newContent = _formatJSPContent(files[i], content);
687 
688             newContent = StringUtil.replace(
689                 newContent,
690                 new String[] {
691                     "<br/>", "\"/>", "\" >", "@page import", "\"%>", ")%>",
692                     "javascript: "
693                 },
694                 new String[] {
695                     "<br />", "\" />", "\">", "@ page import", "\" %>", ") %>",
696                     "javascript:"
697                 });
698 
699             newContent = StringUtil.replace(
700                 newContent,
701                 new String[] {
702                     "* Copyright (c) 2000-2009 Liferay, Inc."
703                 },
704                 new String[] {
705                     "* Copyright (c) 2000-2010 Liferay, Inc."
706                 });
707 
708             if (files[i].endsWith(".jsp") || files[i].endsWith(".jspf")) {
709                 if ((oldCopyright != null) &&
710                     newContent.contains(oldCopyright)) {
711 
712                     newContent = StringUtil.replace(
713                         newContent, oldCopyright, copyright);
714 
715                     System.out.println("old (c): " + files[i]);
716                 }
717 
718                 if (newContent.indexOf(copyright) == -1) {
719                     System.out.println("(c): " + files[i]);
720                 }
721             }
722 
723             if (newContent.indexOf("alert('<%= LanguageUtil.") != -1) {
724                 newContent = StringUtil.replace(newContent,
725                     "alert('<%= LanguageUtil.",
726                     "alert('<%= UnicodeLanguageUtil.");
727             }
728 
729             if (newContent.indexOf("alert(\"<%= LanguageUtil.") != -1) {
730                 newContent = StringUtil.replace(newContent,
731                     "alert(\"<%= LanguageUtil.",
732                     "alert(\"<%= UnicodeLanguageUtil.");
733             }
734 
735             if (newContent.indexOf("confirm('<%= LanguageUtil.") != -1) {
736                 newContent = StringUtil.replace(newContent,
737                     "confirm('<%= LanguageUtil.",
738                     "confirm('<%= UnicodeLanguageUtil.");
739             }
740 
741             if (newContent.indexOf("confirm(\"<%= LanguageUtil.") != -1) {
742                 newContent = StringUtil.replace(newContent,
743                     "confirm(\"<%= LanguageUtil.",
744                     "confirm(\"<%= UnicodeLanguageUtil.");
745             }
746 
747             if (newContent.indexOf("    ") != -1) {
748                 if (!files[i].endsWith("template.vm")) {
749                     System.out.println("tab: " + files[i]);
750                 }
751             }
752 
753             _checkXSS(files[i], content);
754 
755             if ((newContent != null) && !content.equals(newContent)) {
756                 _fileUtil.write(file, newContent);
757 
758                 System.out.println(file);
759             }
760         }
761     }
762 
763     private static String _formatJSPContent(String fileName, String content)
764         throws IOException {
765 
766         StringBuilder sb = new StringBuilder();
767 
768         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
769             new UnsyncStringReader(content));
770 
771         String line = null;
772 
773         while ((line = unsyncBufferedReader.readLine()) != null) {
774             if (line.trim().length() == 0) {
775                 line = StringPool.BLANK;
776             }
777 
778             line = StringUtil.trimTrailing(line);
779 
780             sb.append(line);
781             sb.append("\n");
782         }
783 
784         unsyncBufferedReader.close();
785 
786         content = sb.toString();
787 
788         if (content.endsWith("\n")) {
789             content = content.substring(0, content.length() -1);
790         }
791 
792         content = _formatTaglibQuotes(fileName, content, StringPool.QUOTE);
793         content = _formatTaglibQuotes(fileName, content, StringPool.APOSTROPHE);
794 
795         return content;
796     }
797 
798     private static String _formatTaglibQuotes(
799         String fileName, String content, String quoteType) {
800 
801         String quoteFix = StringPool.APOSTROPHE;
802 
803         if (quoteFix.equals(quoteType)) {
804             quoteFix = StringPool.QUOTE;
805         }
806 
807         Pattern pattern = Pattern.compile(_getTaglibRegex(quoteType));
808 
809         Matcher matcher = pattern.matcher(content);
810 
811         while (matcher.find()) {
812             int x = content.indexOf(quoteType + "<%=", matcher.start());
813             int y = content.indexOf("%>" + quoteType, x);
814 
815             while ((x != -1) && (y != -1)) {
816                 String result = content.substring(x + 1, y + 2);
817 
818                 if (result.indexOf(quoteType) != -1) {
819                     int lineCount = 1;
820 
821                     char contentCharArray[] = content.toCharArray();
822 
823                     for (int i = 0; i < x; i++) {
824                         if (contentCharArray[i] == CharPool.NEW_LINE) {
825                             lineCount++;
826                         }
827                     }
828 
829                     if (result.indexOf(quoteFix) == -1) {
830                         StringBuilder sb = new StringBuilder();
831 
832                         sb.append(content.substring(0, x));
833                         sb.append(quoteFix);
834                         sb.append(result);
835                         sb.append(quoteFix);
836                         sb.append(content.substring(y + 3, content.length()));
837 
838                         content = sb.toString();
839                     }
840                     else {
841                         System.out.println(
842                             "taglib: " + fileName + " " + lineCount);
843                     }
844                 }
845 
846                 x = content.indexOf(quoteType + "<%=", y);
847 
848                 if (x > matcher.end()) {
849                     break;
850                 }
851 
852                 y = content.indexOf("%>" + quoteType, x);
853             }
854         }
855 
856         return content;
857     }
858 
859     private static String _getCopyright() throws IOException {
860         try {
861             return _fileUtil.read("copyright.txt");
862         }
863         catch (Exception e1) {
864             try {
865                 return _fileUtil.read("../copyright.txt");
866             }
867             catch (Exception e2) {
868                 return _fileUtil.read("../../copyright.txt");
869             }
870         }
871     }
872 
873     private static String _getOldCopyright() {
874         try {
875             return _fileUtil.read("old-copyright.txt");
876         }
877         catch (Exception e1) {
878             try {
879                 return _fileUtil.read("../old-copyright.txt");
880             }
881             catch (Exception e2) {
882                 try {
883                     return _fileUtil.read("../../old-copyright.txt");
884                 }
885                 catch (Exception e3) {
886                     return null;
887                 }
888             }
889         }
890     }
891 
892     private static String[] _getPluginJavaFiles() {
893         String basedir = "./";
894 
895         List<String> list = new ArrayList<String>();
896 
897         DirectoryScanner ds = new DirectoryScanner();
898 
899         ds.setBasedir(basedir);
900         ds.setExcludes(
901             new String[] {
902                 "**\\bin\\**", "**\\model\\*Clp.java",
903                 "**\\model\\impl\\*ModelImpl.java",
904                 "**\\service\\**\\model\\*Model.java",
905                 "**\\service\\**\\model\\*Soap.java",
906                 "**\\service\\**\\model\\*Wrapper.java",
907                 "**\\service\\**\\service\\*Service.java",
908                 "**\\service\\**\\service\\*ServiceClp.java",
909                 "**\\service\\**\\service\\*ServiceFactory.java",
910                 "**\\service\\**\\service\\*ServiceUtil.java",
911                 "**\\service\\**\\service\\*ServiceWrapper.java",
912                 "**\\service\\**\\service\\ClpSerializer.java",
913                 "**\\service\\**\\service\\messaging\\*ClpMessageListener.java",
914                 "**\\service\\**\\service\\persistence\\*Finder.java",
915                 "**\\service\\**\\service\\persistence\\*Persistence.java",
916                 "**\\service\\**\\service\\persistence\\*Util.java",
917                 "**\\service\\base\\*ServiceBaseImpl.java",
918                 "**\\service\\http\\*JSONSerializer.java",
919                 "**\\service\\http\\*ServiceHttp.java",
920                 "**\\service\\http\\*ServiceJSON.java",
921                 "**\\service\\http\\*ServiceSoap.java",
922                 "**\\service\\persistence\\*PersistenceImpl.java",
923                 "**\\tmp\\**"
924             });
925         ds.setIncludes(new String[] {"**\\*.java"});
926 
927         ds.scan();
928 
929         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
930 
931         return list.toArray(new String[list.size()]);
932     }
933 
934     private static String[] _getPortalJavaFiles() {
935         String basedir = "./";
936 
937         List<String> list = new ArrayList<String>();
938 
939         DirectoryScanner ds = new DirectoryScanner();
940 
941         ds.setBasedir(basedir);
942         ds.setExcludes(
943             new String[] {
944                 "**\\bin\\**", "**\\classes\\*", "**\\jsp\\*", "**\\tmp\\**",
945                 "**\\PropsKeys.java", "**\\InstanceWrapperBuilder.java",
946                 "**\\ServiceBuilder.java", "**\\SourceFormatter.java",
947                 "**\\UserAttributes.java", "**\\WebKeys.java",
948                 "**\\*_IW.java", "**\\portal-service\\**\\model\\*Model.java",
949                 "**\\portal-service\\**\\model\\*Soap.java",
950                 "**\\portal-service\\**\\model\\*Wrapper.java",
951                 "**\\model\\impl\\*ModelImpl.java",
952                 "**\\portal\\service\\**", "**\\portal-client\\**",
953                 "**\\portal-web\\classes\\**\\*.java",
954                 "**\\portal-web\\test\\**\\*Test.java",
955                 "**\\portlet\\**\\service\\**", "**\\tools\\ext_tmpl\\**",
956                 "**\\tools\\tck\\**"
957             });
958         ds.setIncludes(new String[] {"**\\*.java"});
959 
960         ds.scan();
961 
962         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
963 
964         ds = new DirectoryScanner();
965 
966         ds.setBasedir(basedir);
967         ds.setExcludes(
968             new String[] {
969                 "**\\bin\\**", "**\\portal-client\\**",
970                 "**\\tools\\ext_tmpl\\**", "**\\*_IW.java",
971                 "**\\test\\**\\*PersistenceTest.java"
972             });
973         ds.setIncludes(
974             new String[] {
975                 "**\\com\\liferay\\portal\\service\\ServiceContext*.java",
976                 "**\\model\\BaseModel.java",
977                 "**\\model\\impl\\BaseModelImpl.java",
978                 "**\\service\\base\\PrincipalBean.java",
979                 "**\\service\\http\\*HttpTest.java",
980                 "**\\service\\http\\*SoapTest.java",
981                 "**\\service\\http\\TunnelUtil.java",
982                 "**\\service\\impl\\*.java", "**\\service\\jms\\*.java",
983                 "**\\service\\permission\\*.java",
984                 "**\\service\\persistence\\BasePersistence.java",
985                 "**\\service\\persistence\\BatchSession*.java",
986                 "**\\service\\persistence\\*FinderImpl.java",
987                 "**\\service\\persistence\\*Query.java",
988                 "**\\service\\persistence\\impl\\BasePersistenceImpl.java",
989                 "**\\portal-impl\\test\\**\\*.java",
990                 "**\\portal-service\\**\\liferay\\counter\\**.java",
991                 "**\\portal-service\\**\\liferay\\documentlibrary\\**.java",
992                 "**\\portal-service\\**\\liferay\\lock\\**.java",
993                 "**\\portal-service\\**\\liferay\\mail\\**.java",
994                 "**\\util-bridges\\**\\*.java"
995             });
996 
997         ds.scan();
998 
999         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
1000
1001        return list.toArray(new String[list.size()]);
1002    }
1003
1004    private static String _getTaglibRegex(String quoteType) {
1005        StringBuilder sb = new StringBuilder();
1006
1007        sb.append("<(");
1008
1009        for (int i = 0; i < _TAG_LIBRARIES.length; i++) {
1010            sb.append(_TAG_LIBRARIES[i]);
1011            sb.append(StringPool.PIPE);
1012        }
1013
1014        sb.deleteCharAt(sb.length() - 1);
1015        sb.append("):([^>]|%>)*");
1016        sb.append(quoteType);
1017        sb.append("<%=.*");
1018        sb.append(quoteType);
1019        sb.append(".*%>");
1020        sb.append(quoteType);
1021        sb.append("([^>]|%>)*>");
1022
1023        return sb.toString();
1024    }
1025
1026    private static void _readExclusions() throws IOException {
1027        _exclusions = new Properties();
1028
1029        ClassLoader classLoader = SourceFormatter.class.getClassLoader();
1030
1031        String sourceFormatterExclusions = System.getProperty(
1032            "source-formatter-exclusions",
1033            "com/liferay/portal/tools/dependencies/" +
1034                "source_formatter_exclusions.properties");
1035
1036        URL url = classLoader.getResource(sourceFormatterExclusions);
1037
1038        if (url == null) {
1039            return;
1040        }
1041
1042        InputStream is = url.openStream();
1043
1044        _exclusions.load(is);
1045
1046        is.close();
1047    }
1048
1049    private static final String[] _TAG_LIBRARIES = new String[] {
1050        "c", "html", "jsp", "liferay-portlet", "liferay-security",
1051        "liferay-theme", "liferay-ui", "liferay-util", "portlet", "struts",
1052        "tiles"
1053    };
1054
1055    private static FileImpl _fileUtil = FileImpl.getInstance();
1056    private static Properties _exclusions;
1057    private static Pattern _xssPattern = Pattern.compile(
1058        "String\\s+([^\\s]+)\\s*=\\s*ParamUtil\\.getString\\(");
1059
1060}