1 /*
2 * Copyright 2008 University Corporation for Advanced Internet Development, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package edu.internet2.middleware.ant.util;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.FileReader;
22 import java.io.IOException;
23
24 import org.apache.tools.ant.BuildException;
25 import org.apache.tools.ant.Task;
26
27 /**
28 * Ant task that makes the contents of a file available as a property.
29 *
30 * This ant task requires two attributes:
31 * <ul>
32 * <li><strong>input</strong> - the path to the input file</li>
33 * <li><strong>addProperty</strong> - name of the property that will receive the file contents as a string</li>
34 * <ul>
35 */
36 public class StringFromFile extends Task {
37
38 /** The input file. */
39 private File input;
40
41 /** Property name to which the file contents are added. */
42 private String addProperty;
43
44 /** {@inheritDoc} */
45 public void execute() throws BuildException {
46 try {
47 StringBuilder fileData = new StringBuilder(1000);
48 BufferedReader reader = new BufferedReader(new FileReader(input));
49 char[] buf = new char[1024];
50 int numRead = 0;
51 while ((numRead = reader.read(buf)) != -1) {
52 fileData.append(buf, 0, numRead);
53 }
54 reader.close();
55 getProject().setProperty(addProperty, fileData.toString());
56 } catch (IOException e) {
57 throw new BuildException("Unable to read file " + input.getAbsolutePath(), e);
58 }
59 }
60
61 /**
62 * Sets the file from which the data will be read.
63 *
64 * @param input file from which the data will be read
65 */
66 public void setInput(File input) {
67 this.input = input;
68 }
69
70 /**
71 * Sets the property name to which the file contents are added.
72 *
73 * @param addProperty property name to which the file contents are added.
74 */
75 public void setAddProperty(String addProperty) {
76 this.addProperty = addProperty;
77 }
78 }