1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
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.portal.PortalException")) {
478                 newContent = StringUtil.replace(
479                     newContent, "com.liferay.portal.PortalException",
480                     "com.liferay.portal.kernel.exception.PortalException");
481             }
482 
483             if (newContent.contains("com.liferay.portal.SystemException")) {
484                 newContent = StringUtil.replace(
485                     newContent, "com.liferay.portal.SystemException",
486                     "com.liferay.portal.kernel.exception.SystemException");
487             }
488 
489             newContent = stripImports(newContent, packagePath, className);
490 
491             if (newContent.indexOf(";\n/**") != -1) {
492                 newContent = StringUtil.replace(
493                     newContent,
494                     ";\n/**",
495                     ";\n\n/**");
496             }
497 
498             if (newContent.indexOf("\t/*\n\t *") != -1) {
499                 newContent = StringUtil.replace(
500                     newContent,
501                     "\t/*\n\t *",
502                     "\t/**\n\t *");
503             }
504 
505             if (newContent.indexOf("if(") != -1) {
506                 newContent = StringUtil.replace(
507                     newContent,
508                     "if(",
509                     "if (");
510             }
511 
512             if (newContent.indexOf("while(") != -1) {
513                 newContent = StringUtil.replace(
514                     newContent,
515                     "while(",
516                     "while (");
517             }
518 
519             if (newContent.indexOf("\n\n\n") != -1) {
520                 newContent = StringUtil.replace(
521                     newContent,
522                     "\n\n\n",
523                     "\n\n");
524             }
525 
526             if (newContent.indexOf("*/\npackage ") != -1) {
527                 System.out.println("package: " + files[i]);
528             }
529 
530             if (newContent.indexOf("    ") != -1) {
531                 if (!files[i].endsWith("StringPool.java")) {
532                     System.out.println("tab: " + files[i]);
533                 }
534             }
535 
536             if (newContent.indexOf("  {") != -1) {
537                 System.out.println("{:" + files[i]);
538             }
539 
540             if (!newContent.endsWith("\n\n}") &&
541                 !newContent.endsWith("{\n}")) {
542 
543                 System.out.println("}: " + files[i]);
544             }
545 
546             if (portalJavaFiles && className.endsWith("ServiceImpl") &&
547                 (newContent.indexOf("ServiceUtil.") != -1)) {
548 
549                 System.out.println("ServiceUtil: " + files[i]);
550             }
551 
552             if ((newContent != null) && !content.equals(newContent)) {
553                 _fileUtil.write(file, newContent);
554 
555                 System.out.println(file);
556             }
557         }
558     }
559 
560     private static String _formatJavaContent(
561             String fileName, String className, String content)
562         throws IOException {
563 
564         boolean longLogFactoryUtil = false;
565 
566         StringBuilder sb = new StringBuilder();
567 
568         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
569             new UnsyncStringReader(content));
570 
571         int lineCount = 0;
572 
573         String line = null;
574 
575         while ((line = unsyncBufferedReader.readLine()) != null) {
576             lineCount++;
577 
578             if (line.trim().length() == 0) {
579                 line = StringPool.BLANK;
580             }
581 
582             line = StringUtil.trimTrailing(line);
583 
584             line = StringUtil.replace(
585                 line,
586                 new String[] {
587                     "* Copyright (c) 2000-2009 Liferay, Inc."
588                 },
589                 new String[] {
590                     "* Copyright (c) 2000-2010 Liferay, Inc."
591                 });
592 
593             sb.append(line);
594             sb.append("\n");
595 
596             StringBuilder lineSB = new StringBuilder();
597 
598             int spacesPerTab = 4;
599 
600             for (char c : line.toCharArray()) {
601                 if (c == CharPool.TAB) {
602                     for (int i = 0; i < spacesPerTab; i++) {
603                         lineSB.append(CharPool.SPACE);
604                     }
605 
606                     spacesPerTab = 4;
607                 }
608                 else {
609                     lineSB.append(c);
610 
611                     spacesPerTab--;
612 
613                     if (spacesPerTab <= 0) {
614                         spacesPerTab = 4;
615                     }
616                 }
617             }
618 
619             line = lineSB.toString();
620 
621             if (line.endsWith("private static Log _log =")) {
622                 longLogFactoryUtil = true;
623             }
624 
625             String excluded = _exclusions.getProperty(
626                 StringUtil.replace(fileName, "\\", "/") + StringPool.AT +
627                     lineCount);
628 
629             if (excluded == null) {
630                 excluded = _exclusions.getProperty(
631                     StringUtil.replace(fileName, "\\", "/"));
632             }
633 
634             if ((excluded == null) && (line.length() > 80) &&
635                 !line.startsWith("import ") && !line.startsWith("package ")) {
636 
637                 if (fileName.endsWith("Table.java") &&
638                     line.contains("String TABLE_SQL_CREATE = ")) {
639                 }
640                 else {
641                     System.out.println("> 80: " + fileName + " " + lineCount);
642                 }
643             }
644         }
645 
646         unsyncBufferedReader.close();
647 
648         String newContent = sb.toString();
649 
650         if (newContent.endsWith("\n")) {
651             newContent = newContent.substring(0, newContent.length() -1);
652         }
653 
654         if (longLogFactoryUtil) {
655             newContent = StringUtil.replace(
656                 newContent,
657                 "private static Log _log =\n\t\tLogFactoryUtil.getLog(",
658                 "private static Log _log = LogFactoryUtil.getLog(\n\t\t");
659         }
660 
661         return newContent;
662     }
663 
664     private static void _formatJSP() throws IOException {
665         String basedir = "./";
666 
667         List<String> list = new ArrayList<String>();
668 
669         DirectoryScanner ds = new DirectoryScanner();
670 
671         ds.setBasedir(basedir);
672         ds.setExcludes(
673             new String[] {
674                 "**\\portal\\aui\\**", "**\\bin\\**", "**\\null.jsp",
675                 "**\\tmp\\**", "**\\tools\\tck\\**"
676             });
677         ds.setIncludes(new String[] {"**\\*.jsp", "**\\*.jspf", "**\\*.vm"});
678 
679         ds.scan();
680 
681         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
682 
683         String copyright = _getCopyright();
684         String oldCopyright = _getOldCopyright();
685 
686         String[] files = list.toArray(new String[list.size()]);
687 
688         for (int i = 0; i < files.length; i++) {
689             File file = new File(basedir + files[i]);
690 
691             String content = _fileUtil.read(file);
692             String newContent = _formatJSPContent(files[i], content);
693 
694             newContent = StringUtil.replace(
695                 newContent,
696                 new String[] {
697                     "<br/>", "\"/>", "\" >", "@page import", "\"%>", ")%>",
698                     "javascript: "
699                 },
700                 new String[] {
701                     "<br />", "\" />", "\">", "@ page import", "\" %>", ") %>",
702                     "javascript:"
703                 });
704 
705             newContent = StringUtil.replace(
706                 newContent,
707                 new String[] {
708                     "* Copyright (c) 2000-2009 Liferay, Inc."
709                 },
710                 new String[] {
711                     "* Copyright (c) 2000-2010 Liferay, Inc."
712                 });
713 
714             if (files[i].endsWith(".jsp") || files[i].endsWith(".jspf")) {
715                 if ((oldCopyright != null) &&
716                     newContent.contains(oldCopyright)) {
717 
718                     newContent = StringUtil.replace(
719                         newContent, oldCopyright, copyright);
720 
721                     System.out.println("old (c): " + files[i]);
722                 }
723 
724                 if (newContent.indexOf(copyright) == -1) {
725                     System.out.println("(c): " + files[i]);
726                 }
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("alert(\"<%= LanguageUtil.") != -1) {
736                 newContent = StringUtil.replace(newContent,
737                     "alert(\"<%= LanguageUtil.",
738                     "alert(\"<%= 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("confirm(\"<%= LanguageUtil.") != -1) {
748                 newContent = StringUtil.replace(newContent,
749                     "confirm(\"<%= LanguageUtil.",
750                     "confirm(\"<%= UnicodeLanguageUtil.");
751             }
752 
753             if (newContent.indexOf("    ") != -1) {
754                 if (!files[i].endsWith("template.vm")) {
755                     System.out.println("tab: " + files[i]);
756                 }
757             }
758 
759             _checkXSS(files[i], content);
760 
761             if ((newContent != null) && !content.equals(newContent)) {
762                 _fileUtil.write(file, newContent);
763 
764                 System.out.println(file);
765             }
766         }
767     }
768 
769     private static String _formatJSPContent(String fileName, String content)
770         throws IOException {
771 
772         StringBuilder sb = new StringBuilder();
773 
774         UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
775             new UnsyncStringReader(content));
776 
777         String line = null;
778 
779         while ((line = unsyncBufferedReader.readLine()) != null) {
780             if (line.trim().length() == 0) {
781                 line = StringPool.BLANK;
782             }
783 
784             line = StringUtil.trimTrailing(line);
785 
786             sb.append(line);
787             sb.append("\n");
788         }
789 
790         unsyncBufferedReader.close();
791 
792         content = sb.toString();
793 
794         if (content.endsWith("\n")) {
795             content = content.substring(0, content.length() -1);
796         }
797 
798         content = _formatTaglibQuotes(fileName, content, StringPool.QUOTE);
799         content = _formatTaglibQuotes(fileName, content, StringPool.APOSTROPHE);
800 
801         return content;
802     }
803 
804     private static String _formatTaglibQuotes(
805         String fileName, String content, String quoteType) {
806 
807         String quoteFix = StringPool.APOSTROPHE;
808 
809         if (quoteFix.equals(quoteType)) {
810             quoteFix = StringPool.QUOTE;
811         }
812 
813         Pattern pattern = Pattern.compile(_getTaglibRegex(quoteType));
814 
815         Matcher matcher = pattern.matcher(content);
816 
817         while (matcher.find()) {
818             int x = content.indexOf(quoteType + "<%=", matcher.start());
819             int y = content.indexOf("%>" + quoteType, x);
820 
821             while ((x != -1) && (y != -1)) {
822                 String result = content.substring(x + 1, y + 2);
823 
824                 if (result.indexOf(quoteType) != -1) {
825                     int lineCount = 1;
826 
827                     char contentCharArray[] = content.toCharArray();
828 
829                     for (int i = 0; i < x; i++) {
830                         if (contentCharArray[i] == CharPool.NEW_LINE) {
831                             lineCount++;
832                         }
833                     }
834 
835                     if (result.indexOf(quoteFix) == -1) {
836                         StringBuilder sb = new StringBuilder();
837 
838                         sb.append(content.substring(0, x));
839                         sb.append(quoteFix);
840                         sb.append(result);
841                         sb.append(quoteFix);
842                         sb.append(content.substring(y + 3, content.length()));
843 
844                         content = sb.toString();
845                     }
846                     else {
847                         System.out.println(
848                             "taglib: " + fileName + " " + lineCount);
849                     }
850                 }
851 
852                 x = content.indexOf(quoteType + "<%=", y);
853 
854                 if (x > matcher.end()) {
855                     break;
856                 }
857 
858                 y = content.indexOf("%>" + quoteType, x);
859             }
860         }
861 
862         return content;
863     }
864 
865     private static String _getCopyright() throws IOException {
866         try {
867             return _fileUtil.read("copyright.txt");
868         }
869         catch (Exception e1) {
870             try {
871                 return _fileUtil.read("../copyright.txt");
872             }
873             catch (Exception e2) {
874                 return _fileUtil.read("../../copyright.txt");
875             }
876         }
877     }
878 
879     private static String _getOldCopyright() {
880         try {
881             return _fileUtil.read("old-copyright.txt");
882         }
883         catch (Exception e1) {
884             try {
885                 return _fileUtil.read("../old-copyright.txt");
886             }
887             catch (Exception e2) {
888                 try {
889                     return _fileUtil.read("../../old-copyright.txt");
890                 }
891                 catch (Exception e3) {
892                     return null;
893                 }
894             }
895         }
896     }
897 
898     private static String[] _getPluginJavaFiles() {
899         String basedir = "./";
900 
901         List<String> list = new ArrayList<String>();
902 
903         DirectoryScanner ds = new DirectoryScanner();
904 
905         ds.setBasedir(basedir);
906         ds.setExcludes(
907             new String[] {
908                 "**\\bin\\**", "**\\model\\*Clp.java",
909                 "**\\model\\impl\\*ModelImpl.java",
910                 "**\\service\\**\\model\\*Model.java",
911                 "**\\service\\**\\model\\*Soap.java",
912                 "**\\service\\**\\model\\*Wrapper.java",
913                 "**\\service\\**\\service\\*Service.java",
914                 "**\\service\\**\\service\\*ServiceClp.java",
915                 "**\\service\\**\\service\\*ServiceFactory.java",
916                 "**\\service\\**\\service\\*ServiceUtil.java",
917                 "**\\service\\**\\service\\*ServiceWrapper.java",
918                 "**\\service\\**\\service\\ClpSerializer.java",
919                 "**\\service\\**\\service\\messaging\\*ClpMessageListener.java",
920                 "**\\service\\**\\service\\persistence\\*Finder.java",
921                 "**\\service\\**\\service\\persistence\\*Persistence.java",
922                 "**\\service\\**\\service\\persistence\\*Util.java",
923                 "**\\service\\base\\*ServiceBaseImpl.java",
924                 "**\\service\\http\\*JSONSerializer.java",
925                 "**\\service\\http\\*ServiceHttp.java",
926                 "**\\service\\http\\*ServiceJSON.java",
927                 "**\\service\\http\\*ServiceSoap.java",
928                 "**\\service\\persistence\\*PersistenceImpl.java",
929                 "**\\tmp\\**"
930             });
931         ds.setIncludes(new String[] {"**\\*.java"});
932 
933         ds.scan();
934 
935         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
936 
937         return list.toArray(new String[list.size()]);
938     }
939 
940     private static String[] _getPortalJavaFiles() {
941         String basedir = "./";
942 
943         List<String> list = new ArrayList<String>();
944 
945         DirectoryScanner ds = new DirectoryScanner();
946 
947         ds.setBasedir(basedir);
948         ds.setExcludes(
949             new String[] {
950                 "**\\bin\\**", "**\\classes\\*", "**\\jsp\\*", "**\\tmp\\**",
951                 "**\\PropsKeys.java", "**\\InstanceWrapperBuilder.java",
952                 "**\\ServiceBuilder.java", "**\\SourceFormatter.java",
953                 "**\\UserAttributes.java", "**\\WebKeys.java",
954                 "**\\*_IW.java", "**\\portal-service\\**\\model\\*Model.java",
955                 "**\\portal-service\\**\\model\\*Soap.java",
956                 "**\\portal-service\\**\\model\\*Wrapper.java",
957                 "**\\model\\impl\\*ModelImpl.java",
958                 "**\\portal\\service\\**", "**\\portal-client\\**",
959                 "**\\portal-web\\classes\\**\\*.java",
960                 "**\\portal-web\\test\\**\\*Test.java",
961                 "**\\portlet\\**\\service\\**", "**\\tools\\ext_tmpl\\**",
962                 "**\\tools\\tck\\**"
963             });
964         ds.setIncludes(new String[] {"**\\*.java"});
965 
966         ds.scan();
967 
968         list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
969 
970         ds = new DirectoryScanner();
971 
972         ds.setBasedir(basedir);
973         ds.setExcludes(
974             new String[] {
975                 "**\\bin\\**", "**\\portal-client\\**",
976                 "**\\tools\\ext_tmpl\\**", "**\\*_IW.java",
977                 "**\\test\\**\\*PersistenceTest.java"
978             });
979         ds.setIncludes(
980             new String[] {
981                 "**\\com\\liferay\\portal\\service\\ServiceContext*.java",
982                 "**\\model\\BaseModel.java",
983                 "**\\model\\impl\\BaseModelImpl.java",
984                 "**\\service\\base\\PrincipalBean.java",
985                 "**\\service\\http\\*HttpTest.java",
986                 "**\\service\\http\\*SoapTest.java",
987                 "**\\service\\http\\TunnelUtil.java",
988                 "**\\service\\impl\\*.java", "**\\service\\jms\\*.java",
989                 "**\\service\\permission\\*.java",
990                 "**\\service\\persistence\\BasePersistence.java",
991                 "**\\service\\persistence\\BatchSession*.java",
992                 "**\\service\\persistence\\*FinderImpl.java",
993                 "**\\service\\persistence\\*Query.java",
994                 "**\\service\\persistence\\impl\\BasePersistenceImpl.java",
995                 "**\\portal-impl\\test\\**\\*.java",
996                 "**\\portal-service\\**\\liferay\\counter\\**.java",
997                 "**\\portal-service\\**\\liferay\\documentlibrary\\**.java",
998                 "**\\portal-service\\**\\liferay\\lock\\**.java",
999                 "**\\portal-service\\**\\liferay\\mail\\**.java",
1000                "**\\util-bridges\\**\\*.java"
1001            });
1002
1003        ds.scan();
1004
1005        list.addAll(ListUtil.fromArray(ds.getIncludedFiles()));
1006
1007        return list.toArray(new String[list.size()]);
1008    }
1009
1010    private static String _getTaglibRegex(String quoteType) {
1011        StringBuilder sb = new StringBuilder();
1012
1013        sb.append("<(");
1014
1015        for (int i = 0; i < _TAG_LIBRARIES.length; i++) {
1016            sb.append(_TAG_LIBRARIES[i]);
1017            sb.append(StringPool.PIPE);
1018        }
1019
1020        sb.deleteCharAt(sb.length() - 1);
1021        sb.append("):([^>]|%>)*");
1022        sb.append(quoteType);
1023        sb.append("<%=.*");
1024        sb.append(quoteType);
1025        sb.append(".*%>");
1026        sb.append(quoteType);
1027        sb.append("([^>]|%>)*>");
1028
1029        return sb.toString();
1030    }
1031
1032    private static void _readExclusions() throws IOException {
1033        _exclusions = new Properties();
1034
1035        ClassLoader classLoader = SourceFormatter.class.getClassLoader();
1036
1037        String sourceFormatterExclusions = System.getProperty(
1038            "source-formatter-exclusions",
1039            "com/liferay/portal/tools/dependencies/" +
1040                "source_formatter_exclusions.properties");
1041
1042        URL url = classLoader.getResource(sourceFormatterExclusions);
1043
1044        if (url == null) {
1045            return;
1046        }
1047
1048        InputStream is = url.openStream();
1049
1050        _exclusions.load(is);
1051
1052        is.close();
1053    }
1054
1055    private static final String[] _TAG_LIBRARIES = new String[] {
1056        "aui", "c", "html", "jsp", "liferay-portlet", "liferay-security",
1057        "liferay-theme", "liferay-ui", "liferay-util", "portlet", "struts",
1058        "tiles"
1059    };
1060
1061    private static FileImpl _fileUtil = FileImpl.getInstance();
1062    private static Properties _exclusions;
1063    private static Pattern _xssPattern = Pattern.compile(
1064        "String\\s+([^\\s]+)\\s*=\\s*ParamUtil\\.getString\\(");
1065
1066}