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