View Javadoc
1   /*
2    * (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and contributors.
3    *
4    * All rights reserved. This program and the accompanying materials
5    * are made available under the terms of the GNU Lesser General Public License
6    * (LGPL) version 2.1 which accompanies this distribution, and is available at
7    * http://www.gnu.org/licenses/lgpl-2.1.html
8    *
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12   * Lesser General Public License for more details.
13   *
14   * Contributors:
15   *     Nuxeo - initial API and implementation
16   *
17   */
18  
19  package org.nuxeo.build.ant;
20  
21  import java.io.BufferedReader;
22  import java.io.FileReader;
23  import java.io.IOException;
24  import java.util.regex.Matcher;
25  import java.util.regex.Pattern;
26  
27  import org.apache.tools.ant.Project;
28  import org.apache.tools.ant.Task;
29  
30  /**
31   * TODO NXBT-258
32   */
33  public class PropertyRegexp extends Task {
34  
35      String property;
36  
37      String pattern;
38  
39      String input;
40  
41      int select = 0;
42  
43      public void setProperty(String property) {
44          this.property = property;
45      }
46  
47      public void setPattern(String pattern) {
48          this.pattern = pattern;
49      }
50  
51      /**
52       * @param input file path
53       */
54      public void setInput(String input) {
55          this.input = input;
56      }
57  
58      public void setSelect(int select) {
59          this.select = select;
60      }
61  
62      @Override
63      public void execute() {
64          try {
65              String inputString = readFileAsString(input);
66              Pattern p = Pattern.compile(pattern);
67              Matcher m = p.matcher(inputString);
68              String findString = "";
69              if (m.find()) {
70                  findString = m.group(select);
71              }
72              getProject().setProperty(property, findString);
73          } catch (IOException e) {
74              AntClient.getInstance().log("Couldn't read " + input, e,
75                      Project.MSG_ERR);
76          }
77      }
78  
79      private static String readFileAsString(String filePath) throws IOException {
80          StringBuffer fileData = new StringBuffer(1000);
81          BufferedReader reader = new BufferedReader(new FileReader(filePath));
82          char[] buf = new char[1024];
83          int numRead = 0;
84          while ((numRead = reader.read(buf)) != -1) {
85              fileData.append(buf, 0, numRead);
86          }
87          reader.close();
88          return fileData.toString();
89      }
90  
91  }