]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/jsch/ScpTo.java
2a6da62de8048b60607c7aee17d0994999151036
[gpl/argeo-slc.git] / runtime / org.argeo.slc.support.simple / src / main / java / org / argeo / slc / jsch / ScpTo.java
1 package org.argeo.slc.jsch;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileNotFoundException;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.util.ArrayList;
12 import java.util.List;
13
14 import org.apache.commons.io.IOUtils;
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17 import org.argeo.slc.SlcException;
18 import org.springframework.core.io.Resource;
19 import org.springframework.util.AntPathMatcher;
20 import org.springframework.util.PathMatcher;
21 import org.springframework.util.StringUtils;
22
23 import com.jcraft.jsch.Channel;
24 import com.jcraft.jsch.ChannelExec;
25 import com.jcraft.jsch.Session;
26
27 public class ScpTo extends AbstractJschTask {
28 private final static Log log = LogFactory.getLog(ScpTo.class);
29
30 private Resource localResource;
31 private String remotePath;
32
33 private String dir;
34 private String remoteDir;
35 private List<String> includes = new ArrayList<String>();
36
37 private List<String> excludes = new ArrayList<String>();
38
39 private PathMatcher pathMatcher;
40
41 public void run(Session session) {
42 if (StringUtils.hasText(dir)) {
43 if (!StringUtils.hasText(remoteDir))
44 throw new SlcException("Remote dir has to be specified.");
45
46 String dirOs = dir.replace('/', File.separatorChar);
47 if (dirOs.charAt(dir.length() - 1) != File.separatorChar) {
48 dirOs = dirOs + File.separator;
49 }
50
51 if (pathMatcher == null)
52 pathMatcher = new AntPathMatcher();
53
54 log.info("Start multiple scp based on " + dirOs);
55 scanDir(session, dirOs, "", includes, excludes);
56 }
57
58 if (localResource != null) {
59 uploadResource(session, localResource, remoteDir);
60 }
61 }
62
63 protected void scanDir(Session session, String dir, String currentRelPath,
64 List<String> includes, List<String> excludes) {
65 File[] files = new File(dir).listFiles();
66 for (File file : files) {
67 if (!file.isDirectory()) {
68 String relPath = currentRelPath.concat(file.getName());
69 if (match(relPath, includes, excludes, false)) {
70 uploadFile(session, file, remoteDir + '/' + relPath);
71 }
72 } else {
73 String relPath = currentRelPath.concat(file.getName()).concat(
74 "/");
75 if (match(relPath, includes, excludes, true)) {
76 String nextDir = dir.concat(file.getName()).concat(
77 File.separator);
78 scanDir(session, nextDir, relPath, includes, excludes);
79 }
80 }
81 }
82 }
83
84 protected Boolean match(String path, List<String> includes,
85 List<String> excludes, boolean matchStart) {
86 for (String patternIn : includes) {
87 boolean matchIn = matchStart ? pathMatcher.matchStart(patternIn,
88 path) : pathMatcher.match(patternIn, path);
89 if (matchIn) {
90 // Could be included, check excludes
91 boolean excluded = false;
92 ex: for (String patternEx : excludes) {
93 boolean matchEx = matchStart ? pathMatcher.matchStart(
94 patternEx, path) : pathMatcher.match(patternEx,
95 path);
96
97 if (matchEx) {
98 excluded = true;
99 break ex;
100 }
101 }
102 if (!excluded)
103 return true;
104 }
105 }
106 return false;
107 }
108
109 protected void uploadFile(Session session, File file, String remoteFile) {
110 try {
111 uploadFile(session, new FileInputStream(file), file.length(), file
112 .getPath(), file.toString(), remoteFile);
113 } catch (FileNotFoundException e) {
114 throw new SlcException("Cannot upload " + file, e);
115 }
116 }
117
118 protected void uploadResource(Session session, Resource resource,
119 String remoteFile) {
120 try {
121 File lFile = resource.getFile();
122 uploadFile(session, lFile, remotePath);
123 } catch (IOException e) {
124 // no underlying file found
125 // load the resource in memory before transferring it
126 InputStream in = null;
127 try {
128 in = resource.getInputStream();
129 ByteArrayOutputStream out = new ByteArrayOutputStream();
130 IOUtils.copy(in, out);
131 byte[] arr = out.toByteArray();
132 ByteArrayInputStream content = new ByteArrayInputStream(arr);
133 uploadFile(session, content, arr.length, resource.getURL()
134 .getPath(), resource.toString(), remotePath);
135 arr = null;
136 } catch (IOException e1) {
137 throw new SlcException("Can neither interpret resource "
138 + localResource
139 + " as file, nor create a temporary file", e1);
140 } finally {
141 IOUtils.closeQuietly(in);
142 // no need to close byte arrays streams
143 }
144 }
145 }
146
147 protected void uploadFile(Session session, InputStream in, long size,
148 String path, String sourceDesc, String remoteFile) {
149 OutputStream channelOut;
150 InputStream channelIn;
151 try {
152
153 // exec 'scp -t rfile' remotely
154 String command = "scp -p -t " + remoteFile;
155 Channel channel = session.openChannel("exec");
156 ((ChannelExec) channel).setCommand(command);
157
158 // get I/O streams for remote scp
159 channelOut = channel.getOutputStream();
160 channelIn = channel.getInputStream();
161
162 channel.connect();
163 checkAck(channelIn);
164
165 // send "C0644 filesize filename", where filename should not include
166 // '/'
167 long filesize = size;
168 command = "C0644 " + filesize + " ";
169 int index = path.lastIndexOf('/');
170 if (index > 0) {
171 command += path.substring(index + 1);
172 } else {
173 command += path;
174 }
175 command += "\n";
176
177 channelOut.write(command.getBytes());
178 channelOut.flush();
179 checkAck(channelIn);
180
181 if (log.isTraceEnabled())
182 log.debug("Start copy of " + sourceDesc + " to " + remoteFile
183 + " on " + getSshTarget() + "...");
184
185 final long oneMB = 1024l;// in KB
186 final long tenMB = 10 * oneMB;// in KB
187
188 // send a content of lfile
189 byte[] buf = new byte[1024];
190 long cycleCount = 0;
191 long nbrOfBytes = 0;
192 while (true) {
193 int len = in.read(buf, 0, buf.length);
194 if (len <= 0)
195 break;
196 channelOut.write(buf, 0, len); // out.flush();
197 nbrOfBytes = nbrOfBytes + len;
198 if (((cycleCount % oneMB) == 0) && cycleCount != 0)// each 1 MB
199 System.out.print('#');
200 if (((cycleCount % (tenMB)) == 0) && cycleCount != 0)// each 10
201 // MB
202 System.out.print(" - " + cycleCount / tenMB + "0 MB\n");
203 cycleCount++;
204 }
205 // send '\0'
206 buf[0] = 0;
207 channelOut.write(buf, 0, 1);
208 channelOut.flush();
209 checkAck(channelIn);
210
211 if (log.isDebugEnabled())
212 log.debug("Transferred to " + remoteFile + " ("
213 + sizeDesc(nbrOfBytes) + ") on " + getSshTarget()
214 + " from " + sourceDesc);
215
216 IOUtils.closeQuietly(channelOut);
217
218 channel.disconnect();
219 } catch (Exception e) {
220 throw new SlcException("Cannot copy " + path + " to " + remoteFile,
221 e);
222 } finally {
223 IOUtils.closeQuietly(in);
224 }
225 }
226
227 protected String sizeDesc(Long nbrOfBytes) {
228 if (nbrOfBytes < 1024)
229 return nbrOfBytes + " B";
230 else if (nbrOfBytes < 1024 * 1024)
231 return (nbrOfBytes / 1024) + " KB";
232 else
233 return nbrOfBytes / (1024 * 1024) + " MB";
234 }
235
236 public void setLocalResource(Resource localFile) {
237 this.localResource = localFile;
238 }
239
240 public void setRemotePath(String remoteFile) {
241 this.remotePath = remoteFile;
242 }
243
244 public void setDir(String dir) {
245 this.dir = dir;
246 }
247
248 public void setRemoteDir(String remoteDir) {
249 this.remoteDir = remoteDir;
250 }
251
252 public void setIncludes(List<String> includes) {
253 this.includes = includes;
254 }
255
256 public void setExcludes(List<String> excludes) {
257 this.excludes = excludes;
258 }
259
260 public void setPathMatcher(PathMatcher pathMatcher) {
261 this.pathMatcher = pathMatcher;
262 }
263
264 }