1 20 package com.puppycrawl.tools.checkstyle.checks; 21 22 import java.io.FileReader ; 23 import java.io.IOException ; 24 import java.io.LineNumberReader ; 25 import java.io.Reader ; 26 import java.io.StringReader ; 27 import java.util.ArrayList ; 28 29 import com.puppycrawl.tools.checkstyle.api.Check; 30 import com.puppycrawl.tools.checkstyle.api.CheckstyleException; 31 32 import org.apache.commons.beanutils.ConversionException; 33 34 39 public abstract class AbstractHeaderCheck extends Check 40 { 41 42 private String [] mHeaderLines; 43 44 48 protected String [] getHeaderLines() 49 { 50 return mHeaderLines; 51 } 52 53 58 public void setHeaderFile(String aFileName) 59 throws ConversionException 60 { 61 if ((aFileName == null) || (aFileName.trim().length() == 0)) { 63 return; 64 } 65 66 checkHeaderNotInitialized(); 67 68 Reader headerReader = null; 70 try { 71 headerReader = new FileReader (aFileName); 72 loadHeader(headerReader); 73 } 74 catch (final IOException ex) { 75 throw new ConversionException( 76 "unable to load header file " + aFileName, ex); 77 } 78 finally { 79 if (headerReader != null) { 80 try { 81 headerReader.close(); 82 } 83 catch (final IOException ex) { 84 throw new ConversionException( 85 "unable to close header file " + aFileName, ex); 86 } 87 } 88 } 89 } 90 91 97 public void setHeader(String aHeader) 98 { 99 if ((aHeader == null) || (aHeader.trim().length() == 0)) { 100 return; 101 } 102 103 checkHeaderNotInitialized(); 104 105 final String headerExpandedNewLines = aHeader.replaceAll("\\\\n", "\n"); 106 107 final Reader headerReader = new StringReader (headerExpandedNewLines); 108 try { 109 loadHeader(headerReader); 110 } 111 catch (final IOException ex) { 112 throw new ConversionException( 113 "unable to load header", ex); 114 } 115 finally { 116 try { 117 headerReader.close(); 118 } 119 catch (final IOException ex) { 120 throw new ConversionException( 122 "unable to close header", ex); 123 } 124 } 125 126 } 127 128 132 private void checkHeaderNotInitialized() 133 { 134 if (mHeaderLines != null) { 135 throw new ConversionException( 136 "header has already been set - " 137 + "set either header or headerFile, not both"); 138 } 139 } 140 141 146 private void loadHeader(final Reader aHeaderReader) throws IOException 147 { 148 final LineNumberReader lnr = new LineNumberReader (aHeaderReader); 149 final ArrayList lines = new ArrayList (); 150 while (true) { 151 final String l = lnr.readLine(); 152 if (l == null) { 153 break; 154 } 155 lines.add(l); 156 } 157 mHeaderLines = (String []) lines.toArray(new String [0]); 158 } 159 160 165 protected final void finishLocalSetup() throws CheckstyleException 166 { 167 if (mHeaderLines == null) { 168 throw new CheckstyleException( 169 "property 'headerFile' is missing or invalid in module " 170 + getConfiguration().getName()); 171 } 172 } 173 174 175 public final int[] getDefaultTokens() 176 { 177 return new int[0]; 178 } 179 } 180 | Popular Tags |