aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/optional/ssh/ScpFromMessageBySftp.java
blob: 04f72d235622f6f832b575e41f4a758c2a486808 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.tools.ant.taskdefs.optional.ssh;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.util.FileUtils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;

/**
 * A helper object representing an scp download.
 */
public class ScpFromMessageBySftp extends ScpFromMessage {

    private static final int HUNDRED_KILOBYTES = 102400;

    private String remoteFile;
    private final File localFile;
    private boolean isRecursive = false;
    private boolean verbose = false;

    /**
     * Constructor for ScpFromMessageBySftp.
     * @param verbose if true log extra information
     * @param session the Scp session to use
     * @param aRemoteFile the remote file name
     * @param aLocalFile  the local file
     * @param recursive   if true use recursion
     * @since Ant 1.7
     */
    public ScpFromMessageBySftp(final boolean verbose,
                                final Session session,
                                final String aRemoteFile,
                                final File aLocalFile,
                                final boolean recursive) {
        this(verbose, session, aRemoteFile, aLocalFile, recursive, false);
    }

    /**
     * Constructor for ScpFromMessageBySftp.
     * @param session the Scp session to use
     * @param aRemoteFile the remote file name
     * @param aLocalFile  the local file
     * @param recursive   if true use recursion
     */
    public ScpFromMessageBySftp(final Session session,
                                final String aRemoteFile,
                                final File aLocalFile,
                                final boolean recursive) {
        this(false, session, aRemoteFile, aLocalFile, recursive);
    }

    /**
     * Constructor for ScpFromMessageBySftp.
     * @param verbose if true log extra information
     * @param session the Scp session to use
     * @param aRemoteFile the remote file name
     * @param aLocalFile  the local file
     * @param recursive   if true use recursion
     * @param preserveLastModified whether to preserve file
     * modification times
     * @since Ant 1.8.0
     */
    public ScpFromMessageBySftp(final boolean verbose,
                                final Session session,
                                final String aRemoteFile,
                                final File aLocalFile,
                                final boolean recursive,
                                final boolean preserveLastModified) {
        super(verbose, session, aRemoteFile, aLocalFile, recursive,
              preserveLastModified);
        this.verbose = verbose;
        this.remoteFile = aRemoteFile;
        this.localFile = aLocalFile;
        this.isRecursive = recursive;
    }

    /**
     * Carry out the transfer.
     * @throws IOException on i/o errors
     * @throws JSchException on errors detected by scp
     */
    public void execute() throws IOException, JSchException {
        final ChannelSftp channel = openSftpChannel();
        try {
            channel.connect();
            try {
                final SftpATTRS attrs = channel.stat(remoteFile);
                if (attrs.isDir() && !remoteFile.endsWith("/")) {
                    remoteFile = remoteFile + "/";
                }
            } catch (final SftpException ee) {
                // Ignored
            }
            getDir(channel, remoteFile, localFile);
        } catch (final SftpException e) {
            final JSchException schException = new JSchException("Could not get '"+ remoteFile
                    +"' to '"+localFile+"' - "
                    +e.toString());
            schException.initCause(e);
            throw schException;
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
        }
        log("done\n");
    }

    private void getDir(final ChannelSftp channel,
                        final String remoteFile,
                        final File localFile) throws IOException, SftpException {
        String pwd = remoteFile;
        if (remoteFile.lastIndexOf('/') != -1) {
            if (remoteFile.length() > 1) {
                pwd = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            }
        }
        channel.cd(pwd);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        final java.util.Vector files = channel.ls(remoteFile);
        final int size = files.size();
        for (int i = 0; i < size; i++) {
            final ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) files.elementAt(i);
            final String name = le.getFilename();
            if (le.getAttrs().isDir()) {
                if (name.equals(".") || name.equals("..")) {
                    continue;
                }
                getDir(channel,
                       channel.pwd() + "/" + name + "/",
                       new File(localFile, le.getFilename()));
            } else {
                getFile(channel, le, localFile);
            }
        }
        channel.cd("..");
    }

    private void getFile(final ChannelSftp channel,
                         final ChannelSftp.LsEntry le,
                         File localFile) throws IOException, SftpException {
        final String remoteFile = le.getFilename();
        if (!localFile.exists()) {
            final String path = localFile.getAbsolutePath();
            final int i = path.lastIndexOf(File.pathSeparator);
            if (i != -1) {
                if (path.length() > File.pathSeparator.length()) {
                    new File(path.substring(0, i)).mkdirs();
                }
            }
        }

        if (localFile.isDirectory()) {
            localFile = new File(localFile, remoteFile);
        }

        final long startTime = System.currentTimeMillis();
        final long totalLength = le.getAttrs().getSize();

        SftpProgressMonitor monitor = null;
        final boolean trackProgress = getVerbose() && totalLength > HUNDRED_KILOBYTES;
        if (trackProgress) {
            monitor = getProgressMonitor();
        }
        try {
            log("Receiving: " + remoteFile + " : " + le.getAttrs().getSize());
            channel.get(remoteFile, localFile.getAbsolutePath(), monitor);
        } finally {
            final long endTime = System.currentTimeMillis();
            logStats(startTime, endTime, (int) totalLength);
        }
        if (getPreserveLastModified()) {
            FileUtils.getFileUtils().setFileLastModified(localFile,
                                                         ((long) le.getAttrs()
                                                          .getMTime())
                                                         * 1000);
        }
    }
}