View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
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 org.gwe.p2elv2.functions;
18  
19  import java.io.InputStream;
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.gwe.p2elv2.PFunction;
26  import org.gwe.p2elv2.PStatementContext;
27  import org.gwe.p2elv2.PVarValue;
28  import org.gwe.p2elv2.PVarValueSpace;
29  import org.gwe.utils.IOUtils;
30  
31  
32  /**
33   * @author Marco Ruiz
34   * @since Aug 11, 2008
35   */
36  public class PFLines extends PFunction {
37  
38  	private static Log log = LogFactory.getLog(PFLines.class);
39  
40  	public PFLines() { super("lines"); }
41  
42      public PVarValueSpace calculateValues(List<String> params, PStatementContext ctx) {
43          PVarValueSpace result = new PVarValueSpace();
44          String source = params.get(0);
45  
46  		try {
47  			String content = readSource(source, ctx);
48  			for (String line : content.split("\n")) result.add(new PVarValue(line));
49  			if (result.size() == 0) result.add(new PVarValue(""));
50          } catch (Exception e) {
51          	e.printStackTrace();
52          	log.warn(e);
53          }
54  		
55      	return result;
56      }
57      
58      private String readSource(String source, PStatementContext ctx) {
59      	try {
60  	        InputStream is = ctx.getKeys().createFileLink(source).createHandle().getInputStream();
61  			return IOUtils.readStream(is);
62          } catch (Exception e) {
63          	return source;
64          }
65      }
66      
67      public static void main(String[] args) {
68      	List<String> params = new ArrayList<String>();
69  //    	params.add("/Users/admin/work/eclipse-ws/gwe-core/src/temp/test.txt");
70      	params.add("Marco,12,0.5\nAntonio,24,0.1\nRuiz,36,0.7\nHuapaya,48,1.9");
71      	
72      	PFLines function = new PFLines();
73  		PVarValueSpace result = function.calculateValues(params, null);
74  		System.out.println(result);
75  		
76  		for (PVarValue varValue : result) System.out.println(varValue);
77      }
78  }
79