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 31 kB

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