You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Concat.java 30 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import java.io.File;
  20. import java.io.Reader;
  21. import java.io.Writer;
  22. import java.io.FileReader;
  23. import java.io.InputStream;
  24. import java.io.IOException;
  25. import java.io.PrintWriter;
  26. import java.io.OutputStream;
  27. import java.io.StringReader;
  28. import java.io.BufferedReader;
  29. import java.io.BufferedWriter;
  30. import java.io.FileInputStream;
  31. import java.io.FileOutputStream;
  32. import java.io.InputStreamReader;
  33. import java.io.OutputStreamWriter;
  34. import java.util.Arrays;
  35. import java.util.Vector;
  36. import java.util.Iterator;
  37. import org.apache.tools.ant.Task;
  38. import org.apache.tools.ant.Project;
  39. import org.apache.tools.ant.BuildException;
  40. import org.apache.tools.ant.ProjectComponent;
  41. import org.apache.tools.ant.filters.util.ChainReaderHelper;
  42. import org.apache.tools.ant.types.Path;
  43. import org.apache.tools.ant.types.FileSet;
  44. import org.apache.tools.ant.types.FileList;
  45. import org.apache.tools.ant.types.FilterChain;
  46. import org.apache.tools.ant.types.Resource;
  47. import org.apache.tools.ant.types.ResourceCollection;
  48. import org.apache.tools.ant.types.resources.Restrict;
  49. import org.apache.tools.ant.types.resources.Resources;
  50. import org.apache.tools.ant.types.resources.FileResource;
  51. import org.apache.tools.ant.types.resources.StringResource;
  52. import org.apache.tools.ant.types.resources.selectors.Not;
  53. import org.apache.tools.ant.types.resources.selectors.Exists;
  54. import org.apache.tools.ant.types.resources.selectors.ResourceSelector;
  55. import org.apache.tools.ant.util.FileUtils;
  56. import org.apache.tools.ant.util.ConcatResourceInputStream;
  57. /**
  58. * This class contains the 'concat' task, used to concatenate a series
  59. * of files into a single stream. The destination of this stream may
  60. * be the system console, or a file. The following is a sample
  61. * invocation:
  62. *
  63. * <pre>
  64. * &lt;concat destfile=&quot;${build.dir}/index.xml&quot;
  65. * append=&quot;false&quot;&gt;
  66. *
  67. * &lt;fileset dir=&quot;${xml.root.dir}&quot;
  68. * includes=&quot;*.xml&quot; /&gt;
  69. *
  70. * &lt;/concat&gt;
  71. * </pre>
  72. *
  73. */
  74. public class Concat extends Task {
  75. // The size of buffers to be used
  76. private static final int BUFFER_SIZE = 8192;
  77. private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
  78. private static final ResourceSelector EXISTS = new Exists();
  79. private static final ResourceSelector NOT_EXISTS = new Not(EXISTS);
  80. // Attributes.
  81. /**
  82. * The destination of the stream. If <code>null</code>, the system
  83. * console is used.
  84. */
  85. private File destinationFile;
  86. /**
  87. * Whether or not the stream should be appended if the destination file
  88. * exists.
  89. * Defaults to <code>false</code>.
  90. */
  91. private boolean append;
  92. /**
  93. * Stores the input file encoding.
  94. */
  95. private String encoding;
  96. /** Stores the output file encoding. */
  97. private String outputEncoding;
  98. /** Stores the binary attribute */
  99. private boolean binary;
  100. // Child elements.
  101. /**
  102. * This buffer stores the text within the 'concat' element.
  103. */
  104. private StringBuffer textBuffer;
  105. /**
  106. * Stores a collection of file sets and/or file lists, used to
  107. * select multiple files for concatenation.
  108. */
  109. private Resources rc;
  110. /** for filtering the concatenated */
  111. private Vector filterChains;
  112. /** ignore dates on input files */
  113. private boolean forceOverwrite = true;
  114. /** String to place at the start of the concatented stream */
  115. private TextElement footer;
  116. /** String to place at the end of the concatented stream */
  117. private TextElement header;
  118. /** add missing line.separator to files **/
  119. private boolean fixLastLine = false;
  120. /** endofline for fixlast line */
  121. private String eolString;
  122. /** outputwriter */
  123. private Writer outputWriter = null;
  124. /**
  125. * Construct a new Concat task.
  126. */
  127. public Concat() {
  128. reset();
  129. }
  130. /**
  131. * Reset state to default.
  132. */
  133. public void reset() {
  134. append = false;
  135. forceOverwrite = true;
  136. destinationFile = null;
  137. encoding = null;
  138. outputEncoding = null;
  139. fixLastLine = false;
  140. filterChains = null;
  141. footer = null;
  142. header = null;
  143. binary = false;
  144. outputWriter = null;
  145. textBuffer = null;
  146. eolString = System.getProperty("line.separator");
  147. rc = null;
  148. }
  149. // Attribute setters.
  150. /**
  151. * Sets the destination file, or uses the console if not specified.
  152. * @param destinationFile the destination file
  153. */
  154. public void setDestfile(File destinationFile) {
  155. this.destinationFile = destinationFile;
  156. }
  157. /**
  158. * Sets the behavior when the destination file exists. If set to
  159. * <code>true</code> the stream data will be appended to the
  160. * existing file, otherwise the existing file will be
  161. * overwritten. Defaults to <code>false</code>.
  162. * @param append if true append to the file.
  163. */
  164. public void setAppend(boolean append) {
  165. this.append = append;
  166. }
  167. /**
  168. * Sets the character encoding
  169. * @param encoding the encoding of the input stream and unless
  170. * outputencoding is set, the outputstream.
  171. */
  172. public void setEncoding(String encoding) {
  173. this.encoding = encoding;
  174. if (outputEncoding == null) {
  175. outputEncoding = encoding;
  176. }
  177. }
  178. /**
  179. * Sets the character encoding for outputting
  180. * @param outputEncoding the encoding for the output file
  181. * @since Ant 1.6
  182. */
  183. public void setOutputEncoding(String outputEncoding) {
  184. this.outputEncoding = outputEncoding;
  185. }
  186. /**
  187. * Force overwrite existing destination file
  188. * @param force if true always overwrite, otherwise only overwrite
  189. * if the output file is older any of the input files.
  190. * @since Ant 1.6
  191. */
  192. public void setForce(boolean force) {
  193. this.forceOverwrite = force;
  194. }
  195. // Nested element creators.
  196. /**
  197. * Path of files to concatenate.
  198. * @return the path used for concatenating
  199. * @since Ant 1.6
  200. */
  201. public Path createPath() {
  202. Path path = new Path(getProject());
  203. add(path);
  204. return path;
  205. }
  206. /**
  207. * Set of files to concatenate.
  208. * @param set the set of files
  209. */
  210. public void addFileset(FileSet set) {
  211. add(set);
  212. }
  213. /**
  214. * List of files to concatenate.
  215. * @param list the list of files
  216. */
  217. public void addFilelist(FileList list) {
  218. add(list);
  219. }
  220. /**
  221. * Add an arbitrary ResourceCollection.
  222. * @param c the ResourceCollection to add.
  223. * @since Ant 1.7
  224. */
  225. public void add(ResourceCollection c) {
  226. rc = rc == null ? new Resources() : rc;
  227. rc.add(c);
  228. }
  229. /**
  230. * Adds a FilterChain.
  231. * @param filterChain a filterchain to filter the concatenated input
  232. * @since Ant 1.6
  233. */
  234. public void addFilterChain(FilterChain filterChain) {
  235. if (filterChains == null) {
  236. filterChains = new Vector();
  237. }
  238. filterChains.addElement(filterChain);
  239. }
  240. /**
  241. * This method adds text which appears in the 'concat' element.
  242. * @param text the text to be concated.
  243. */
  244. public void addText(String text) {
  245. if (textBuffer == null) {
  246. // Initialize to the size of the first text fragment, with
  247. // the hopes that it's the only one.
  248. textBuffer = new StringBuffer(text.length());
  249. }
  250. // Append the fragment -- we defer property replacement until
  251. // later just in case we get a partial property in a fragment.
  252. textBuffer.append(text);
  253. }
  254. /**
  255. * Add a header to the concatenated output
  256. * @param headerToAdd the header
  257. * @since Ant 1.6
  258. */
  259. public void addHeader(TextElement headerToAdd) {
  260. this.header = headerToAdd;
  261. }
  262. /**
  263. * Add a footer to the concatenated output
  264. * @param footerToAdd the footer
  265. * @since Ant 1.6
  266. */
  267. public void addFooter(TextElement footerToAdd) {
  268. this.footer = footerToAdd;
  269. }
  270. /**
  271. * Append line.separator to files that do not end
  272. * with a line.separator, default false.
  273. * @param fixLastLine if true make sure each input file has
  274. * new line on the concatenated stream
  275. * @since Ant 1.6
  276. */
  277. public void setFixLastLine(boolean fixLastLine) {
  278. this.fixLastLine = fixLastLine;
  279. }
  280. /**
  281. * Specify the end of line to find and to add if
  282. * not present at end of each input file. This attribute
  283. * is used in conjunction with fixlastline.
  284. * @param crlf the type of new line to add -
  285. * cr, mac, lf, unix, crlf, or dos
  286. * @since Ant 1.6
  287. */
  288. public void setEol(FixCRLF.CrLf crlf) {
  289. String s = crlf.getValue();
  290. if (s.equals("cr") || s.equals("mac")) {
  291. eolString = "\r";
  292. } else if (s.equals("lf") || s.equals("unix")) {
  293. eolString = "\n";
  294. } else if (s.equals("crlf") || s.equals("dos")) {
  295. eolString = "\r\n";
  296. }
  297. }
  298. /**
  299. * Set the output writer. This is to allow
  300. * concat to be used as a nested element.
  301. * @param outputWriter the output writer.
  302. * @since Ant 1.6
  303. */
  304. public void setWriter(Writer outputWriter) {
  305. this.outputWriter = outputWriter;
  306. }
  307. /**
  308. * Set the binary attribute. If true, concat will concatenate the files
  309. * byte for byte. This mode does not allow any filtering or other
  310. * modifications to the input streams. The default value is false.
  311. * @since Ant 1.6.2
  312. * @param binary if true, enable binary mode.
  313. */
  314. public void setBinary(boolean binary) {
  315. this.binary = binary;
  316. }
  317. /**
  318. * Validate configuration options.
  319. */
  320. private ResourceCollection validate() {
  321. // treat empty nested text as no text
  322. sanitizeText();
  323. // if binary check if incompatible attributes are used
  324. if (binary) {
  325. if (destinationFile == null) {
  326. throw new BuildException(
  327. "destfile attribute is required for binary concatenation");
  328. }
  329. if (textBuffer != null) {
  330. throw new BuildException(
  331. "Nested text is incompatible with binary concatenation");
  332. }
  333. if (encoding != null || outputEncoding != null) {
  334. throw new BuildException(
  335. "Seting input or output encoding is incompatible with binary"
  336. + " concatenation");
  337. }
  338. if (filterChains != null) {
  339. throw new BuildException(
  340. "Setting filters is incompatible with binary concatenation");
  341. }
  342. if (fixLastLine) {
  343. throw new BuildException(
  344. "Setting fixlastline is incompatible with binary concatenation");
  345. }
  346. if (header != null || footer != null) {
  347. throw new BuildException(
  348. "Nested header or footer is incompatible with binary concatenation");
  349. }
  350. }
  351. if (destinationFile != null && outputWriter != null) {
  352. throw new BuildException(
  353. "Cannot specify both a destination file and an output writer");
  354. }
  355. // Sanity check our inputs.
  356. if (rc == null && textBuffer == null) {
  357. // Nothing to concatenate!
  358. throw new BuildException(
  359. "At least one resource must be provided, or some text.");
  360. }
  361. if (rc != null) {
  362. // If using resources, disallow inline text. This is similar to
  363. // using GNU 'cat' with file arguments -- stdin is simply
  364. // ignored.
  365. if (textBuffer != null) {
  366. throw new BuildException(
  367. "Cannot include inline text when using resources.");
  368. }
  369. Restrict noexistRc = new Restrict();
  370. noexistRc.add(NOT_EXISTS);
  371. noexistRc.add(rc);
  372. for (Iterator i = noexistRc.iterator(); i.hasNext();) {
  373. log(i.next() + " does not exist.", Project.MSG_ERR);
  374. }
  375. if (destinationFile != null) {
  376. for (Iterator i = rc.iterator(); i.hasNext();) {
  377. Object o = i.next();
  378. if (o instanceof FileResource) {
  379. File f = ((FileResource) o).getFile();
  380. if (FILE_UTILS.fileNameEquals(f, destinationFile)) {
  381. throw new BuildException("Input file \""
  382. + f + "\" is the same as the output file.");
  383. }
  384. }
  385. }
  386. }
  387. Restrict existRc = new Restrict();
  388. existRc.add(EXISTS);
  389. existRc.add(rc);
  390. boolean outofdate = destinationFile == null || forceOverwrite;
  391. if (!outofdate) {
  392. for (Iterator i = existRc.iterator(); !outofdate && i.hasNext();) {
  393. Resource r = (Resource) i.next();
  394. outofdate =
  395. (r.getLastModified() == 0L
  396. || r.getLastModified() > destinationFile.lastModified());
  397. }
  398. }
  399. if (!outofdate) {
  400. log(destinationFile + " is up-to-date.", Project.MSG_VERBOSE);
  401. return null; // no need to do anything
  402. }
  403. return existRc;
  404. } else {
  405. StringResource s = new StringResource();
  406. s.setProject(getProject());
  407. s.setValue(textBuffer.toString());
  408. return s;
  409. }
  410. }
  411. /**
  412. * Execute the concat task.
  413. */
  414. public void execute() {
  415. ResourceCollection c = validate();
  416. if (c == null) {
  417. return;
  418. }
  419. // Do nothing if no resources (including nested text)
  420. if (c.size() < 1 && header == null && footer == null) {
  421. log("No existing resources and no nested text, doing nothing",
  422. Project.MSG_INFO);
  423. return;
  424. }
  425. if (binary) {
  426. binaryCat(c);
  427. } else {
  428. cat(c);
  429. }
  430. }
  431. /** perform the binary concatenation */
  432. private void binaryCat(ResourceCollection c) {
  433. log("Binary concatenation of " + c.size()
  434. + " resources to " + destinationFile);
  435. FileOutputStream out = null;
  436. InputStream in = null;
  437. try {
  438. try {
  439. out = new FileOutputStream(destinationFile.getPath(), append); // JDK 1.2 compatibility
  440. } catch (Exception t) {
  441. throw new BuildException("Unable to open "
  442. + destinationFile + " for writing", t);
  443. }
  444. in = new ConcatResourceInputStream(c);
  445. ((ConcatResourceInputStream) in).setManagingComponent(this);
  446. Thread t = new Thread(new StreamPumper(in, out));
  447. t.start();
  448. try {
  449. t.join();
  450. } catch (InterruptedException e) {
  451. try {
  452. t.join();
  453. } catch (InterruptedException ee) {
  454. // Empty
  455. }
  456. }
  457. } finally {
  458. FileUtils.close(in);
  459. if (out != null) {
  460. try {
  461. out.close();
  462. } catch (Exception ex) {
  463. throw new BuildException(
  464. "Unable to close " + destinationFile, ex);
  465. }
  466. }
  467. }
  468. }
  469. /** perform the concatenation */
  470. private void cat(ResourceCollection c) {
  471. OutputStream os = null;
  472. char[] buffer = new char[BUFFER_SIZE];
  473. try {
  474. PrintWriter writer = null;
  475. if (outputWriter != null) {
  476. writer = new PrintWriter(outputWriter);
  477. } else {
  478. if (destinationFile == null) {
  479. // Log using WARN so it displays in 'quiet' mode.
  480. os = new LogOutputStream(this, Project.MSG_WARN);
  481. } else {
  482. // ensure that the parent dir of dest file exists
  483. File parent = destinationFile.getParentFile();
  484. if (!parent.exists()) {
  485. parent.mkdirs();
  486. }
  487. os = new FileOutputStream(destinationFile.getAbsolutePath(),
  488. append);
  489. }
  490. if (outputEncoding == null) {
  491. writer = new PrintWriter(
  492. new BufferedWriter(
  493. new OutputStreamWriter(os)));
  494. } else {
  495. writer = new PrintWriter(
  496. new BufferedWriter(
  497. new OutputStreamWriter(os, outputEncoding)));
  498. }
  499. }
  500. if (header != null) {
  501. if (header.getFiltering()) {
  502. concatenate(
  503. buffer, writer, new StringReader(header.getValue()));
  504. } else {
  505. writer.print(header.getValue());
  506. }
  507. }
  508. if (c.size() > 0) {
  509. concatenate(buffer, writer, new MultiReader(c));
  510. }
  511. if (footer != null) {
  512. if (footer.getFiltering()) {
  513. concatenate(
  514. buffer, writer, new StringReader(footer.getValue()));
  515. } else {
  516. writer.print(footer.getValue());
  517. }
  518. }
  519. writer.flush();
  520. if (os != null) {
  521. os.flush();
  522. }
  523. } catch (IOException ioex) {
  524. throw new BuildException("Error while concatenating: "
  525. + ioex.getMessage(), ioex);
  526. } finally {
  527. FileUtils.close(os);
  528. }
  529. }
  530. /** Concatenate a single reader to the writer using buffer */
  531. private void concatenate(char[] buffer, Writer writer, Reader in)
  532. throws IOException {
  533. if (filterChains != null) {
  534. ChainReaderHelper helper = new ChainReaderHelper();
  535. helper.setBufferSize(BUFFER_SIZE);
  536. helper.setPrimaryReader(in);
  537. helper.setFilterChains(filterChains);
  538. helper.setProject(getProject());
  539. in = new BufferedReader(helper.getAssembledReader());
  540. }
  541. while (true) {
  542. int nRead = in.read(buffer, 0, buffer.length);
  543. if (nRead == -1) {
  544. break;
  545. }
  546. writer.write(buffer, 0, nRead);
  547. }
  548. writer.flush();
  549. }
  550. /**
  551. * Treat empty nested text as no text.
  552. *
  553. * <p>Depending on the XML parser, addText may have been called
  554. * for &quot;ignorable whitespace&quot; as well.</p>
  555. */
  556. private void sanitizeText() {
  557. if (textBuffer != null) {
  558. if (textBuffer.substring(0).trim().length() == 0) {
  559. textBuffer = null;
  560. }
  561. }
  562. }
  563. /**
  564. * sub element points to a file or contains text
  565. */
  566. public static class TextElement extends ProjectComponent {
  567. private String value = "";
  568. private boolean trimLeading = false;
  569. private boolean trim = false;
  570. private boolean filtering = true;
  571. private String encoding = null;
  572. /**
  573. * whether to filter the text in this element
  574. * or not.
  575. *
  576. * @param filtering true if the text should be filtered.
  577. * the default value is true.
  578. */
  579. public void setFiltering(boolean filtering) {
  580. this.filtering = filtering;
  581. }
  582. /** return the filtering attribute */
  583. private boolean getFiltering() {
  584. return filtering;
  585. }
  586. /**
  587. * The encoding of the text element
  588. *
  589. * @param encoding the name of the charset used to encode
  590. */
  591. public void setEncoding(String encoding) {
  592. this.encoding = encoding;
  593. }
  594. /**
  595. * set the text using a file
  596. * @param file the file to use
  597. * @throws BuildException if the file does not exist, or cannot be
  598. * read
  599. */
  600. public void setFile(File file) throws BuildException {
  601. // non-existing files are not allowed
  602. if (!file.exists()) {
  603. throw new BuildException("File " + file + " does not exist.");
  604. }
  605. BufferedReader reader = null;
  606. try {
  607. if (this.encoding == null) {
  608. reader = new BufferedReader(new FileReader(file));
  609. } else {
  610. reader = new BufferedReader(
  611. new InputStreamReader(new FileInputStream(file),
  612. this.encoding));
  613. }
  614. value = FileUtils.readFully(reader);
  615. } catch (IOException ex) {
  616. throw new BuildException(ex);
  617. } finally {
  618. FileUtils.close(reader);
  619. }
  620. }
  621. /**
  622. * set the text using inline
  623. * @param value the text to place inline
  624. */
  625. public void addText(String value) {
  626. this.value += getProject().replaceProperties(value);
  627. }
  628. /**
  629. * s:^\s*:: on each line of input
  630. * @param strip if true do the trim
  631. */
  632. public void setTrimLeading(boolean strip) {
  633. this.trimLeading = strip;
  634. }
  635. /**
  636. * whether to call text.trim()
  637. * @param trim if true trim the text
  638. */
  639. public void setTrim(boolean trim) {
  640. this.trim = trim;
  641. }
  642. /**
  643. * @return the text, after possible trimming
  644. */
  645. public String getValue() {
  646. if (value == null) {
  647. value = "";
  648. }
  649. if (value.trim().length() == 0) {
  650. value = "";
  651. }
  652. if (trimLeading) {
  653. char[] current = value.toCharArray();
  654. StringBuffer b = new StringBuffer(current.length);
  655. boolean startOfLine = true;
  656. int pos = 0;
  657. while (pos < current.length) {
  658. char ch = current[pos++];
  659. if (startOfLine) {
  660. if (ch == ' ' || ch == '\t') {
  661. continue;
  662. }
  663. startOfLine = false;
  664. }
  665. b.append(ch);
  666. if (ch == '\n' || ch == '\r') {
  667. startOfLine = true;
  668. }
  669. }
  670. value = b.toString();
  671. }
  672. if (trim) {
  673. value = value.trim();
  674. }
  675. return value;
  676. }
  677. }
  678. /**
  679. * This class reads from each of the source files in turn.
  680. * The concatentated result can then be filtered as
  681. * a single stream.
  682. */
  683. private class MultiReader extends Reader {
  684. private Reader reader = null;
  685. private int lastPos = 0;
  686. private char[] lastChars = new char[eolString.length()];
  687. private boolean needAddSeparator = false;
  688. private Iterator i;
  689. private MultiReader(ResourceCollection c) {
  690. i = c.iterator();
  691. }
  692. private Reader getReader() throws IOException {
  693. if (reader == null && i.hasNext()) {
  694. Resource r = (Resource) i.next();
  695. log("Concating " + r.toLongString(), Project.MSG_VERBOSE);
  696. InputStream is = r.getInputStream();
  697. reader = new BufferedReader(encoding == null
  698. ? new InputStreamReader(is)
  699. : new InputStreamReader(is, encoding));
  700. Arrays.fill(lastChars, (char) 0);
  701. }
  702. return reader;
  703. }
  704. private void nextReader() throws IOException {
  705. close();
  706. reader = null;
  707. }
  708. /**
  709. * Read a character from the current reader object. Advance
  710. * to the next if the reader is finished.
  711. * @return the character read, -1 for EOF on the last reader.
  712. * @exception IOException - possibly thrown by the read for a reader
  713. * object.
  714. */
  715. public int read() throws IOException {
  716. if (needAddSeparator) {
  717. int ret = eolString.charAt(lastPos++);
  718. if (lastPos >= eolString.length()) {
  719. lastPos = 0;
  720. needAddSeparator = false;
  721. }
  722. return ret;
  723. }
  724. while (getReader() != null) {
  725. int ch = getReader().read();
  726. if (ch == -1) {
  727. nextReader();
  728. if (fixLastLine && isMissingEndOfLine()) {
  729. needAddSeparator = true;
  730. lastPos = 0;
  731. }
  732. } else {
  733. addLastChar((char) ch);
  734. return ch;
  735. }
  736. }
  737. return -1;
  738. }
  739. /**
  740. * Read into the buffer <code>cbuf</code>.
  741. * @param cbuf The array to be read into.
  742. * @param off The offset.
  743. * @param len The length to read.
  744. * @exception IOException - possibly thrown by the reads to the
  745. * reader objects.
  746. */
  747. public int read(char[] cbuf, int off, int len)
  748. throws IOException {
  749. int amountRead = 0;
  750. while (getReader() != null || needAddSeparator) {
  751. if (needAddSeparator) {
  752. cbuf[off] = eolString.charAt(lastPos++);
  753. if (lastPos >= eolString.length()) {
  754. lastPos = 0;
  755. needAddSeparator = false;
  756. }
  757. len--;
  758. off++;
  759. amountRead++;
  760. if (len == 0) {
  761. return amountRead;
  762. }
  763. continue;
  764. }
  765. int nRead = getReader().read(cbuf, off, len);
  766. if (nRead == -1 || nRead == 0) {
  767. nextReader();
  768. if (fixLastLine && isMissingEndOfLine()) {
  769. needAddSeparator = true;
  770. lastPos = 0;
  771. }
  772. } else {
  773. if (fixLastLine) {
  774. for (int i = nRead;
  775. i > (nRead - lastChars.length);
  776. --i) {
  777. if (i <= 0) {
  778. break;
  779. }
  780. addLastChar(cbuf[off + i - 1]);
  781. }
  782. }
  783. len -= nRead;
  784. off += nRead;
  785. amountRead += nRead;
  786. if (len == 0) {
  787. return amountRead;
  788. }
  789. }
  790. }
  791. if (amountRead == 0) {
  792. return -1;
  793. } else {
  794. return amountRead;
  795. }
  796. }
  797. /**
  798. * Close the current reader
  799. */
  800. public void close() throws IOException {
  801. if (reader != null) {
  802. reader.close();
  803. }
  804. }
  805. /**
  806. * if checking for end of line at end of file
  807. * add a character to the lastchars buffer
  808. */
  809. private void addLastChar(char ch) {
  810. for (int i = lastChars.length - 2; i >= 0; --i) {
  811. lastChars[i] = lastChars[i + 1];
  812. }
  813. lastChars[lastChars.length - 1] = ch;
  814. }
  815. /**
  816. * return true if the lastchars buffer does
  817. * not contain the lineseparator
  818. */
  819. private boolean isMissingEndOfLine() {
  820. for (int i = 0; i < lastChars.length; ++i) {
  821. if (lastChars[i] != eolString.charAt(i)) {
  822. return true;
  823. }
  824. }
  825. return false;
  826. }
  827. }
  828. }