KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > ssh > AbstractSshMessage


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18
19 package org.apache.tools.ant.taskdefs.optional.ssh;
20
21 import com.jcraft.jsch.Channel;
22 import com.jcraft.jsch.ChannelExec;
23 import com.jcraft.jsch.JSchException;
24 import com.jcraft.jsch.Session;
25 import com.jcraft.jsch.ChannelSftp;
26 import com.jcraft.jsch.SftpProgressMonitor;
27
28 import java.io.IOException JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.text.NumberFormat JavaDoc;
32
33 import org.apache.tools.ant.BuildException;
34
35 /**
36  * Abstract class for ssh upload and download
37  */

38 public abstract class AbstractSshMessage {
39
40     private Session session;
41     private boolean verbose;
42     private LogListener listener = new LogListener() {
43         public void log(String JavaDoc message) {
44             // do nothing;
45
}
46     };
47
48     /**
49      * Constructor for AbstractSshMessage
50      * @param session the ssh session to use
51      */

52     public AbstractSshMessage(Session session) {
53         this(false, session);
54     }
55
56     /**
57      * Constructor for AbstractSshMessage
58      * @param verbose if true do verbose logging
59      * @param session the ssh session to use
60      * @since Ant 1.6.2
61      */

62     public AbstractSshMessage(boolean verbose, Session session) {
63         this.verbose = verbose;
64         this.session = session;
65     }
66
67     /**
68      * Open an ssh channel.
69      * @param command the command to use
70      * @return the channel
71      * @throws JSchException on error
72      */

73     protected Channel openExecChannel(String JavaDoc command) throws JSchException {
74         ChannelExec channel = (ChannelExec) session.openChannel("exec");
75         channel.setCommand(command);
76
77         return channel;
78     }
79
80     /**
81      * Open an ssh sftp channel.
82      * @return the channel
83      * @throws JSchException on error
84      */

85     protected ChannelSftp openSftpChannel() throws JSchException {
86         ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
87
88         return channel;
89     }
90
91     /**
92      * Send an ack.
93      * @param out the output stream to use
94      * @throws IOException on error
95      */

96     protected void sendAck(OutputStream JavaDoc out) throws IOException JavaDoc {
97         byte[] buf = new byte[1];
98         buf[0] = 0;
99         out.write(buf);
100         out.flush();
101     }
102
103     /**
104      * Reads the response, throws a BuildException if the response
105      * indicates an error.
106      * @param in the input stream to use
107      * @throws IOException on I/O error
108      * @throws BuildException on other errors
109      */

110     protected void waitForAck(InputStream JavaDoc in)
111         throws IOException JavaDoc, BuildException {
112         int b = in.read();
113
114         // b may be 0 for success,
115
// 1 for error,
116
// 2 for fatal error,
117

118         if (b == -1) {
119             // didn't receive any response
120
throw new BuildException("No response from server");
121         } else if (b != 0) {
122             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
123
124             int c = in.read();
125             while (c > 0 && c != '\n') {
126                 sb.append((char) c);
127                 c = in.read();
128             }
129
130             if (b == 1) {
131                 throw new BuildException("server indicated an error: "
132                                          + sb.toString());
133             } else if (b == 2) {
134                 throw new BuildException("server indicated a fatal error: "
135                                          + sb.toString());
136             } else {
137                 throw new BuildException("unknown response, code " + b
138                                          + " message: " + sb.toString());
139             }
140         }
141     }
142
143     /**
144      * Carry out the transfer.
145      * @throws IOException on I/O errors
146      * @throws JSchException on ssh errors
147      */

148     public abstract void execute() throws IOException JavaDoc, JSchException;
149
150     /**
151      * Set a log listener.
152      * @param aListener the log listener
153      */

154     public void setLogListener(LogListener aListener) {
155         listener = aListener;
156     }
157
158     /**
159      * Log a message to the log listener.
160      * @param message the message to log
161      */

162     protected void log(String JavaDoc message) {
163         listener.log(message);
164     }
165
166     /**
167      * Log transfer stats to the log listener.
168      * @param timeStarted the time started
169      * @param timeEnded the finishing time
170      * @param totalLength the total length
171      */

172     protected void logStats(long timeStarted,
173                              long timeEnded,
174                              long totalLength) {
175         double duration = (timeEnded - timeStarted) / 1000.0;
176         NumberFormat JavaDoc format = NumberFormat.getNumberInstance();
177         format.setMaximumFractionDigits(2);
178         format.setMinimumFractionDigits(1);
179         listener.log("File transfer time: " + format.format(duration)
180             + " Average Rate: " + format.format(totalLength / duration)
181             + " B/s");
182     }
183
184     /**
185      * Is the verbose attribute set.
186      * @return true if the verbose attribute is set
187      * @since Ant 1.6.2
188      */

189     protected final boolean getVerbose() {
190         return verbose;
191     }
192
193     /**
194      * Track progress every 10% if 100kb < filesize < 1mb. For larger
195      * files track progress for every percent transmitted.
196      * @param filesize the size of the file been transmitted
197      * @param totalLength the total transmission size
198      * @param percentTransmitted the current percent transmitted
199      * @return the percent that the file is of the total
200      */

201     protected final int trackProgress(long filesize, long totalLength,
202                                       int percentTransmitted) {
203
204         int percent = (int) Math.round(Math.floor((totalLength
205                                                    / (double) filesize) * 100));
206
207         if (percent > percentTransmitted) {
208             if (filesize < 1048576) {
209                 if (percent % 10 == 0) {
210                     if (percent == 100) {
211                         System.out.println(" 100%");
212                     } else {
213                         System.out.print("*");
214                     }
215                 }
216             } else {
217                 if (percent == 50) {
218                     System.out.println(" 50%");
219                 } else if (percent == 100) {
220                     System.out.println(" 100%");
221                 } else {
222                     System.out.print(".");
223                 }
224             }
225         }
226
227         return percent;
228     }
229
230     private ProgressMonitor monitor = null;
231
232     /**
233      * Get the progress monitor.
234      * @return the progress monitor.
235      */

236     protected SftpProgressMonitor getProgressMonitor() {
237         if (monitor == null) {
238             monitor = new ProgressMonitor();
239         }
240         return monitor;
241     }
242
243     private class ProgressMonitor implements SftpProgressMonitor {
244         private long initFileSize = 0;
245         private long totalLength = 0;
246         private int percentTransmitted = 0;
247
248         public void init(int op, String JavaDoc src, String JavaDoc dest, long max) {
249             initFileSize = max;
250             totalLength = 0;
251             percentTransmitted = 0;
252         }
253
254         public boolean count(long len) {
255             totalLength += len;
256             percentTransmitted = trackProgress(initFileSize,
257                                                totalLength,
258                                                percentTransmitted);
259             return true;
260         }
261
262         public void end() {
263         }
264
265         public long getTotalLength() {
266             return totalLength;
267         }
268     }
269 }
270
Popular Tags