1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.gwe.p2elv2.functions;
18
19 import java.net.URISyntaxException;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.gwe.drivers.HandleOperationException;
28 import org.gwe.drivers.fileSystems.FileHandle;
29 import org.gwe.drivers.fileSystems.GridFileSystemUtils;
30 import org.gwe.p2elv2.PFunction;
31 import org.gwe.p2elv2.PStatementContext;
32 import org.gwe.p2elv2.PVarValueSpace;
33 import org.gwe.utils.IOUtils;
34 import org.gwe.utils.security.KeyStore;
35
36
37
38
39
40 public class PFDir extends PFunction {
41
42 private static Log log = LogFactory.getLog(PFDir.class);
43
44 public PFDir() { super("dir"); }
45
46 public PVarValueSpace calculateValues(List<String> params, PStatementContext ctx) {
47 List<String> branchPatterns = new ArrayList<String>(params);
48 String path = branchPatterns.remove(0);
49
50 List<String> matchingPaths = new ArrayList<String>();
51 matchingPaths.add(path);
52 for (String pattern : branchPatterns)
53 matchingPaths = findChildrenMatchingPatternNoException(matchingPaths, pattern, ctx.getKeys());
54
55 return new PVarValueSpace(matchingPaths);
56 }
57
58 private List<String> findChildrenMatchingPatternNoException(List<String> paths, String pattern, KeyStore keys) {
59 try {
60 return findChildrenMatchingPattern(paths, pattern, keys);
61 } catch (Exception e) {
62 log.info(e);
63 }
64 return new ArrayList<String>();
65 }
66
67 private List<String> findChildrenMatchingPattern(List<String> paths, String pattern, KeyStore keys) throws URISyntaxException, HandleOperationException {
68 List<String> result = new ArrayList<String>();
69 Pattern patternObj = Pattern.compile(pattern);
70 for (String path : paths) {
71 for (String child : listChildren(path, keys)) {
72 Matcher matcher = patternObj.matcher(child);
73 if (matcher.matches())
74 result.add(IOUtils.concatenatePaths(path, child));
75 }
76 }
77
78 return result;
79 }
80
81 public List<String> listChildren(String path, KeyStore keys) throws URISyntaxException, HandleOperationException {
82 List<String> result = new ArrayList<String>();
83 FileHandle root = keys.createFileLink(path).createHandle();
84 if (root.isDirectory()) {
85 for (FileHandle handle : root.getChildren()) {
86 result.add(IOUtils.getFileName(handle.getPath()));
87 GridFileSystemUtils.cleanUpHandle(handle);
88 }
89 }
90 return result;
91 }
92 }
93