001/*
002 * Copyright (c) 2009-2012 The Regents of the University of California.
003 * All rights reserved.
004 *
005 * '$Author: crawl $'
006 * '$Date: 2012-11-26 22:19:36 +0000 (Mon, 26 Nov 2012) $' 
007 * '$Revision: 31113 $'
008 * 
009 * Permission is hereby granted, without written agreement and without
010 * license or royalty fees, to use, copy, modify, and distribute this
011 * software and its documentation for any purpose, provided that the above
012 * copyright notice and the following two paragraphs appear in all copies
013 * of this software.
014 *
015 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
016 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
017 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
018 * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
019 * SUCH DAMAGE.
020 *
021 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
022 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
023 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
024 * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
025 * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
026 * ENHANCEMENTS, OR MODIFICATIONS.
027 *
028 */
029
030package org.sdm.spa.actors.transport;
031
032import java.io.BufferedWriter;
033import java.io.ByteArrayOutputStream;
034import java.io.File;
035import java.io.FileWriter;
036import java.io.IOException;
037import java.io.OutputStream;
038
039import org.apache.commons.logging.Log;
040import org.apache.commons.logging.LogFactory;
041import org.kepler.ssh.ExecException;
042import org.kepler.ssh.LocalExec;
043import org.kepler.ssh.SshException;
044import org.kepler.ssh.SshExec;
045import org.sdm.spa.actors.transport.vo.ConnectionDetails;
046
047/**
048 * This class copies files/directories from one machine to another using the
049 * srmlite protocol. It uses the <code>LocalExec</code> to copy file/directory
050 * between local host and a remote host. To copy files between remote machines,
051 * uses <code>SshExec</code>, connects to source machine using ssh and execute
052 * srmlite command to copy to remote machine
053 * <P>
054 * scp is used as the default protocol passed to srmlite. It can be overriden by
055 * setting the srmProtocol variable
056 * <P>
057 * Copy operation will overwrite existing files by default. Retry feature of
058 * srmlite is not currently supported.
059 * <P>
060 * On the source machine, if srmlite is not on standard path and if the variable
061 * protocolPathSrc is not set, the class attempts to search in the most common
062 * locations - user's home directory, /usr/bin, /bin, and /usr/local/bin
063 * 
064 * @author Chandrika Sivaramakrishnan
065 * 
066 *         Anand: We assume that target location is always a directory.
067 */
068public class SrmliteCopier extends FileCopierBase {
069
070        // /////////////////////Private Variables/////////////////////////////////
071        private static final Log log = LogFactory.getLog(SrmliteCopier.class
072                        .getName());
073        private static final boolean isDebugging = log.isDebugEnabled();
074        private String srmProtocol = "";
075
076        // //////////////////Protected Methods////////////////////////////////////
077
078        /*
079         * Generates the srmlite command to copy from remote host to local host.
080         * Executes the command using LocalExec class
081         * 
082         * @see
083         * org.sdm.spa.actors.transport.FileCopier#copyFrom(org.sdm.spa.actors.transport
084         * .vo.ConnectionDetails, java.lang.String, java.lang.String, boolean)
085         */
086        @Override
087        // Anusua Change - Starts
088        protected CopyResult copyFrom(ConnectionDetails srcDetails, String srcFile,
089                        String destFile, boolean recursive) throws SshException {
090                int exitCode = 0;
091                StringBuffer cmd = new StringBuffer(100);
092                OutputStream streamOut = new ByteArrayOutputStream();
093                OutputStream streamErr = new ByteArrayOutputStream();
094                LocalExec localObject = new LocalExec();
095                localObject.setTimeout(timeout, false, false);
096                String[] srcFileList = null;
097                String[] srcFile_list = null;
098                StringBuffer warn = new StringBuffer(100);
099                boolean warn_flag = false;
100                String cmdWithPath;
101                String osname = (System.getProperty("os.name")).toLowerCase();
102                String userhome = (System.getProperty("user.home")).toLowerCase();
103                String cmdFile = userhome + File.separatorChar + "srmlite_" + System.currentTimeMillis() + ".xml";
104
105
106                if (srcFile.contains(",")) {
107                        srcFileList = srcFile.split(",");
108                        srcFile_list = new String[srcFileList.length];
109                        for (int count = 0; count < srcFileList.length; count++) {
110                                if ((srcFileList[count].trim()).startsWith("/")) {
111                                        srcFile_list[count] = srcFileList[count].trim();
112                                } else {
113                                        warn.append(srcFile_list[count].trim() + " ");
114                                        if (!warn_flag)
115                                                warn_flag = true;
116                                }
117                        }
118                        if (warn_flag) {
119                                warn
120                                                .append(" does not contain full path to the source file. Please provide full path. ");
121                                warn_flag = false;
122                        }
123                } else {
124                        if (!srcFile.startsWith("/")) {
125                                throw new SshException(
126                                                srcFile
127                                                                + "does not contain full path to the file. Please provide full path.");
128                        }
129                }
130                try {
131                        if (srcFile.contains(",")) {
132                                build_xmlForRemoteSource(cmdFile, srcFile_list, srcDetails);
133                        }
134                } catch (Exception e) {// Catch exception if any
135                        e.printStackTrace();
136                        return new CopyResult(1, e.getMessage(), warn.toString());
137                }
138
139                // command format
140                // "<path>/srmlite -s file:////<srcfile> -t scp://user@host/<dest path>"
141                // srmlite -f <cmdFile>
142                if (srcFile.contains(",")) {
143                        if (osname.contains("windows"))
144                                cmd.append("srmlite.bat -f ");
145                        else
146                                cmd.append("srmlite -f ");
147                        cmd.append("file:///");
148                        cmd.append(cmdFile);
149                        cmd.append(" -td ");
150                } else {
151                        if (osname.contains("windows"))
152                                cmd.append("srmlite.bat -s ");
153                        else
154                                cmd.append("srmlite -s ");
155                        cmd.append("\"");
156                        if (srmProtocol.equals("")) {
157                                cmd.append("scp://");
158                        } else {
159                                cmd.append(srmProtocol);
160                                cmd.append("://");
161                        }
162                        cmd.append(srcDetails.toString());
163                        // Anand: we dont need this /
164                        // cmd.append("/");
165                        cmd.append(srcFile);
166                        cmd.append("\"");
167                        if (recursive) {
168                                cmd.append(" -recursive");
169                        }
170                        File tempSrcFile = new File(destFile);
171                        if (tempSrcFile.isDirectory())
172                                cmd.append(" -td ");
173                        else
174                                cmd.append(" -t ");
175                }
176                cmd.append("file:///");
177                cmd.append(destFile);
178
179                if (protocolPathSrc.equals("")) {
180                        if (osname.contains("windows")) {
181                                cmdWithPath = cmd.toString();
182                        } else {
183                                cmdWithPath = getCmdWithDefaultPath(cmd);
184                        }
185                } else {
186                        cmdWithPath = protocolPathSrc + cmd;
187                }
188                // TODO Anand: Adjust path variable
189                // cmdWithPath = "C:\\Projects\\srmlite\\bin\\" + cmd;
190
191                System.out.println("*************Full command executed is ::  "
192                                + cmdWithPath);
193                try {
194                        if (isDebugging)
195                                log.debug("copy cmd=" + cmdWithPath);
196                        streamOut = new ByteArrayOutputStream();
197                        streamErr = new ByteArrayOutputStream();
198                        try {
199                                exitCode = localObject.executeCmd(cmdWithPath, streamOut,
200                                                streamErr, srcDetails.toString());
201                        } catch (ExecException e) {
202                                return new CopyResult(exitCode, e.toString(), "");
203                        }
204                        if (isDebugging) {
205                                log.error("Output on stdout:" + streamOut);
206                                log.error("Output on stderr:" + streamErr);
207                        }
208                } catch (Exception e) {
209                        return new CopyResult(1, "SRMLite Copy failed!\n"
210                                        + streamErr.toString(), "");
211                }
212                String message = streamErr.toString();
213                message = message + " \n\n" + streamOut.toString();
214                String fileDeleteMsg = "";
215                if (srcFile.contains(",")) {
216                        try {
217                                boolean success = false;
218                                success = localObject.deleteFile(cmdFile, false, false);
219                                if (success) {
220                                        log.debug("deleted the xml script file " + cmdFile
221                                                        + " created for file copy");
222                                }
223                                if (!success) {
224                                        log.warn("Unable to delete the xml script file " + cmdFile
225                                                        + " created for file copy");
226                                        fileDeleteMsg = "Unable to delete the xml script file "
227                                                        + cmdFile + " created for file copy";
228                                }
229                        } catch (ExecException e) {
230                                log.warn("Unable to delete the xml script file " + cmdFile
231                                                + " created for file copy : " + e.toString());
232                        }
233                }
234                return new CopyResult(exitCode, message + fileDeleteMsg, "");
235        }
236
237        private void build_xmlForRemoteSource(String fileName,
238                        String[] srcFile_list, ConnectionDetails srcDetails)
239                        throws Exception {
240                FileWriter fstream;
241                fstream = new FileWriter(fileName);
242                BufferedWriter out = new BufferedWriter(fstream);
243                out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
244                out.write("\n");
245                out.write("<request>");
246                out.write("\n");
247
248                SshExec sshObject = new SshExec(srcDetails.getUser(), srcDetails
249                                .getHost(), srcDetails.getPort());
250
251                for (int i = 0; i < srcFile_list.length; i++) {
252                        out.write("<file>");
253                        out.write("\n");
254                        out.write("<sourceurl>");
255                        if (srmProtocol.equals("")) {
256                                out.write("scp://");
257                        } else {
258                                out.write(srmProtocol);
259                                out.write("://");
260                        }
261                        out.write(srcDetails.toString());
262                        out.write("/");
263                        out.write(srcFile_list[i]);
264                        out.write("</sourceurl>");
265                        out.write("\n");
266                        // if src_file is not a file add recursive
267                        if (sshObject.isRemoteFileDirectory(srcFile_list[i])) {
268                                out.write("<recursive>");
269                                out.write("true");
270                                out.write("</recursive>");
271                                out.write("\n");
272                        }
273                        out.write("</file>");
274                        out.write("\n");
275                }
276                out.write("</request>");
277                out.close();
278                System.out.println("exit function build xml****************");
279        }
280
281        /*
282         * Generates the srmlite command to copy from local host to remote host.
283         * Executes the command using LocalExec class
284         * 
285         * @see org.sdm.spa.actors.transport.FileCopier#copyTo(java.lang.String,
286         * org.sdm.spa.actors.transport.vo.ConnectionDetails, java.lang.String,
287         * boolean)
288         */
289        @Override
290        protected CopyResult copyTo(String srcFile, ConnectionDetails destDetails,
291                        String destFile, boolean recursive) throws SshException {
292                int exitCode = 0;
293                String cmdWithPath = null;
294
295                StringBuffer cmd = new StringBuffer(100);
296                LocalExec localObject = new LocalExec();
297                localObject.setTimeout(timeout, false, false);
298                String[] srcFileList = null;
299                String[] srcFile_list = null;
300                StringBuffer warn = new StringBuffer(100);
301                boolean warn_flag = false;
302                String osname = (System.getProperty("os.name")).toLowerCase();
303                String cmdFile = "srmlite_" + System.currentTimeMillis() + ".xml";
304                String userhome = (System.getProperty("user.home")).toLowerCase();
305
306                // srmlite -f xml_file -td target_directory
307                if (srcFile.contains(",")) { // List of files is provided
308                        srcFileList = srcFile.split(",");
309                        srcFile_list = new String[srcFileList.length];
310                        for (int count = 0; count < srcFileList.length; count++) {
311                                if ((srcFileList[count].trim()).startsWith("/")
312                                                || (srcFileList[count].trim()).startsWith(":/", 1) 
313                                                || (srcFileList[count].trim()).contains(":\\")) {
314                                        srcFile_list[count] = srcFileList[count].trim();
315                                } else {
316                                        warn.append(srcFile_list[count].trim() + " ");
317                                        if (!warn_flag)
318                                                warn_flag = true;
319                                }
320                        }
321                        if (warn_flag) {
322                                warn
323                                                .append(" does not contain full path to the source file. Please provide full path. ");
324                                warn_flag = false;
325                        }
326                }
327
328                try {
329                        if (srcFile.contains(",")) {
330                                build_xml_ForLocalSource(userhome + File.separatorChar
331                                                + cmdFile, srcFile_list, destFile);
332                        }
333                } catch (Exception e) {// Catch exception if any
334                        System.err.println("Error: " + e.getMessage());
335                }
336
337                if (srcFile.contains(",")) {
338                        // command format
339                        // "<path>/srmlite -f xml_input -td scp://user@host/<dest path>"
340                        if (osname.contains("windows"))
341                                cmd.append("srmlite.bat -f ");
342                        else
343                                cmd.append("srmlite -f ");
344                        cmd.append("file:///");
345                        cmd.append(userhome + File.separatorChar + cmdFile);
346                        cmd.append(" -td ");
347                        if (srmProtocol.equals("")) {
348                                cmd.append("scp://");
349                        } else {
350                                cmd.append(srmProtocol);
351                                cmd.append("://");
352                        }
353                        cmd.append(destDetails.toString());
354                        cmd.append(destFile);
355                        // cmd.append("/");
356                } else {
357                        // command format
358                        // "<path>/srmlite -s file:////<srcfile> -t scp://user@host/<dest path>"
359                        if (osname.contains("windows"))
360                                cmd.append("srmlite.bat -s ");
361                        else
362                                cmd.append("srmlite -s ");
363                        cmd.append("\"");
364                        // Anand: might need file:////
365                        cmd.append("file:///");
366                        cmd.append(srcFile);
367                        cmd.append("\"");
368                        if (recursive)
369                                cmd.append(" -recursive");
370                        // TODO: We assume that target is always a directory.
371                        cmd.append(" -td ");
372
373                        if (srmProtocol.equals("")) {
374                                cmd.append("scp://");
375                        } else {
376                                cmd.append(srmProtocol);
377                                cmd.append("://");
378                        }
379
380                        cmd.append(destDetails.toString());
381                        // Anand: Commented because it shows as host@ip//root instead of
382                        // /root
383                        // cmd.append("/");
384                        cmd.append(destFile);
385                }
386
387                log.debug("Command without path = " + cmd);
388
389                if (protocolPathSrc.equals("")) {
390                        if (osname.contains("windows")) {
391                                System.out.println("OSNAME WINDOWS*****************");
392                                cmdWithPath = cmd.toString();
393                        } else {
394                                cmdWithPath = getCmdWithDefaultPath(cmd);
395                        }
396                } else {
397                        cmdWithPath = protocolPathSrc + cmd;
398                }
399                
400                log.debug("*************Full command executed is ::  "
401                                + cmdWithPath);
402
403                if (isDebugging)
404                        log.debug("copy cmd=" + cmdWithPath);
405                OutputStream streamOut = new ByteArrayOutputStream();
406                OutputStream streamErr = new ByteArrayOutputStream();
407                try {
408                        exitCode = localObject.executeCmd(cmdWithPath, streamOut,
409                                        streamErr, destDetails.toString());
410                } catch (Exception e) {
411                        return new CopyResult(1, e.toString(), "");
412                }
413                if (isDebugging) {
414                        log.error("Output on stdout:" + streamOut);
415                        log.error("Output on stderr:" + streamErr);
416                }
417                String message = streamErr.toString();
418                message = message + " \n\n" + streamOut.toString();
419                String fileDeleteMsg = "";
420                if (srcFile.contains(",")) {
421                        try {
422                                boolean success = false;
423                                success = localObject.deleteFile(cmdFile, false, false);
424                                if (success) {
425                                        log.debug("deleted the xml script file " + cmdFile
426                                                        + " created for file copy");
427                                }
428                                if (!success) {
429                                        log.warn("Unable to delete the xml script file " + cmdFile
430                                                        + " created for file copy");
431                                        fileDeleteMsg = "Unable to delete the xml script file "
432                                                        + cmdFile + " created for file copy";
433                                }
434                        } catch (ExecException e) {
435                                log.warn("Unable to delete the xml script file " + cmdFile
436                                                + " created for file copy : " + e.toString());
437                        }
438                }
439                return new CopyResult(exitCode, message + fileDeleteMsg, "");
440        }
441
442        public void build_xml_ForLocalSource(String fileName, String[] fileList,
443                        String destFile) throws IOException {
444                FileWriter fstream;
445                fstream = new FileWriter(fileName);
446                BufferedWriter out = new BufferedWriter(fstream);
447                out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
448                out.write("\n");
449                out.write("<request>");
450                out.write("\n");
451                for (int i = 0; i < fileList.length; i++) {
452                        out.write("<file>");
453                        out.write("\n");
454                        out.write("<sourceurl>");
455                        /*
456                         * if (destFile.startsWith("/")) { out.write("file:////"); } else {
457                         * out.write("file:////"); }
458                         */
459                        out.write("file:////");
460                        out.write(fileList[i]);
461                        out.write("</sourceurl>");
462                        out.write("\n");
463
464                        File fileObj = new File(fileList[i]);
465                        if (!fileObj.isFile()) {// if the file is a dir or wildcard
466                                out.write("<recursive>");
467                                out.write("true");
468                                out.write("</recursive>");
469                                out.write("\n");
470                        }
471                        out.write("</file>");
472                        out.write("\n");
473                }
474                out.write("</request>");
475                // Close the output stream
476                out.close();
477        }
478
479        /*
480         * Generates the srmlite command to copy from a remote host to another
481         * remote host. Executes the command using SshExec class
482         * 
483         * @see
484         * org.sdm.spa.actors.transport.FileCopier#copyRemote(org.sdm.spa.actors
485         * .transport.vo.ConnectionDetails, java.lang.String,
486         * org.sdm.spa.actors.transport.vo.ConnectionDetails, java.lang.String,
487         * boolean)
488         */
489        @Override
490        protected CopyResult copyRemote(ConnectionDetails srcDetails,
491                        String srcFile, ConnectionDetails destDetails, String destFile,
492                        boolean recursive) throws ExecException {
493                if (isDebugging)
494                        log.debug("remote srmlite copy");
495                ByteArrayOutputStream cmdStdout = new ByteArrayOutputStream();
496                ByteArrayOutputStream cmdStderr = new ByteArrayOutputStream();
497                String remoteHostStr = "";
498                SshExec sshObjectSrc = null;
499                SshExec sshObjectDest = null;
500                // String file_transfer_cmd = null;
501                String filehome = null;
502                // File single_srcFileObj = null;
503                // File mult_srcFileObj = null;
504                String[] srcFileList = null;
505                String[] srcFile_list = null;
506                StringBuffer warn = new StringBuffer(100);
507                boolean warn_flag = false;
508                // FileWriter fstream;
509                StringBuffer cmd = new StringBuffer(100);
510                String cmdWithPath = null;
511                int exitCode = 0;
512                OutputStream streamOut = new ByteArrayOutputStream();
513                OutputStream streamErr = new ByteArrayOutputStream();
514                StringBuffer xml_file_contents = new StringBuffer();
515
516                String osname = (System.getProperty("os.name")).toLowerCase();
517                String cmdFile = "srmlite_" + System.currentTimeMillis() + ".xml";
518                String userhome = (System.getProperty("user.home")).toLowerCase();
519                String getRemoteHome_Cmd = "echo $HOME";
520
521                // File destfileobj = new File(destFile);
522                // File srcFileObj = new File(srcFile);
523
524                if (srcFile.contains(",")) {
525                        srcFileList = srcFile.split(",");
526                        srcFile_list = new String[srcFileList.length];
527                        for (int count = 0; count < srcFileList.length; count++) {
528                                if ((srcFileList[count].trim()).startsWith("/")) {
529                                        srcFile_list[count] = srcFileList[count].trim();
530                                } else {
531                                        warn.append(srcFile_list[count].trim() + " ");
532                                        if (!warn_flag)
533                                                warn_flag = true;
534                                }
535                        }
536                        if (warn_flag) {
537                                warn
538                                                .append(" does not contain full path to the source file. Please provide full path. ");
539                                warn_flag = false;
540                        }
541                } else {
542                        if (!srcFile.startsWith("/")) {
543                                throw new SshException(
544                                                srcFile
545                                                                + "does not contain full path to the file. Please provide full path.");
546                        }
547                }
548                sshObjectSrc = new SshExec(srcDetails.getUser(), srcDetails.getHost(),
549                                srcDetails.getPort());
550                sshObjectDest = new SshExec(destDetails.getUser(), destDetails
551                                .getHost(), destDetails.getPort());
552                if (srcDetails.isConnectionOrigin()) {
553                        // Conenct to source by ssh
554                        System.out.println("***********SRC is connection origin");
555
556                        remoteHostStr = destDetails.toString();
557                        exitCode = sshObjectSrc.executeCmd(getRemoteHome_Cmd, streamOut,
558                                        streamErr, remoteHostStr);
559                        filehome = streamOut.toString().trim();
560                        sshObjectSrc.setTimeout(timeout, false, false);
561                        sshObjectSrc.setForcedCleanUp(forcedCleanup);
562                        // srmlite doesn't need a pseudo terminal
563                        sshObjectSrc.setPseudoTerminal(false);
564
565                } else {
566                        System.out.println("***********DEST is connection origin");
567                        remoteHostStr = srcDetails.toString();
568                        exitCode = sshObjectDest.executeCmd(getRemoteHome_Cmd, streamOut,
569                                        streamErr, remoteHostStr);
570                        filehome = streamOut.toString().trim();
571                        sshObjectDest.setTimeout(timeout, false, false);
572                        sshObjectDest.setForcedCleanUp(forcedCleanup);
573                        // srmlite doesn't need a pseudo terminal
574                        sshObjectDest.setPseudoTerminal(false);
575                }
576
577                cmdFile = filehome + "/" + cmdFile;
578
579                if (srcFile.contains(",")) {
580                        System.out.println("***********Building xml file");
581                        try {
582                                // Create xml file
583                                // fstream = new FileWriter(userhome + File.separatorChar
584                                // + cmdFile);
585                                // BufferedWriter out = new BufferedWriter(fstream);
586
587                                xml_file_contents
588                                                .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
589                                xml_file_contents.append("\n");
590                                xml_file_contents.append("<request>");
591                                xml_file_contents.append("\n");
592
593                                if (srcDetails.isConnectionOrigin()) {
594                                        // Create list of source files to be copied
595                                        for (int i = 0; i < srcFile_list.length; i++) {
596                                                xml_file_contents.append("<file>");
597                                                xml_file_contents.append("\n");
598                                                xml_file_contents.append("<sourceurl>");
599                                                xml_file_contents.append("file:///");
600                                                xml_file_contents.append(srcFile_list[i]);
601                                                xml_file_contents.append("</sourceurl>");
602                                                xml_file_contents.append("\n");
603                                                // File fileObj = new File(srcFile_list[i]);
604                                                if (sshObjectSrc.isRemoteFileDirectory(srcFile_list[i])) {
605                                                        // if the file is a dir
606                                                        xml_file_contents.append("<recursive>");
607                                                        xml_file_contents.append("true");
608                                                        xml_file_contents.append("</recursive>");
609                                                        xml_file_contents.append("\n");
610                                                }
611                                                xml_file_contents.append("</file>");
612                                                xml_file_contents.append("\n");
613                                        }
614                                        xml_file_contents.append("</request>");
615                                        // Close the output stream
616                                        // out.close();
617                                } else {
618                                        for (int i = 0; i < srcFile_list.length; i++) {
619                                                xml_file_contents.append("<file>");
620                                                xml_file_contents.append("\n");
621                                                xml_file_contents.append("<sourceurl>");
622                                                if (srmProtocol.equals("")) {
623                                                        xml_file_contents.append("scp://");
624                                                } else {
625                                                        xml_file_contents.append(srmProtocol);
626                                                        xml_file_contents.append("://");
627                                                }
628                                                xml_file_contents.append(srcDetails.toString());
629                                                xml_file_contents.append("/");
630                                                xml_file_contents.append(srcFile_list[i]);
631                                                xml_file_contents.append("</sourceurl>");
632                                                xml_file_contents.append("\n");
633                                                if (sshObjectSrc.isRemoteFileDirectory(srcFile_list[i])) {
634                                                        // if the file is a dir
635                                                        xml_file_contents.append("<recursive>");
636                                                        xml_file_contents.append("true");
637                                                        xml_file_contents.append("</recursive>");
638                                                        xml_file_contents.append("\n");
639                                                }
640                                                xml_file_contents.append("</file>");
641                                                xml_file_contents.append("\n");
642                                        }
643                                        xml_file_contents.append("</request>");
644                                        // out.close();
645                                }
646                        } catch (Exception e) {// Catch exception if any
647                                System.err
648                                                .println("Error creating xml file: " + e.getMessage());
649                        }
650
651                        System.out.println("**************Xml file created...");
652                        System.out.println("**************Transferring sml file...");
653                        try {
654                                String temp_cmd = "echo -e '" + xml_file_contents + "' >> "
655                                                + cmdFile;
656                                System.out.println("***************XML command : " + temp_cmd);
657                                if (srcDetails.isConnectionOrigin())
658                                        exitCode = sshObjectSrc.executeCmd(temp_cmd, streamOut,
659                                                        streamErr, remoteHostStr);
660                                else
661                                        exitCode = sshObjectDest.executeCmd(temp_cmd, streamOut,
662                                                        streamErr, remoteHostStr);
663                                if (exitCode != 0)
664                                        throw new Exception(
665                                                        "XML file creation failed with exit code : "
666                                                                        + exitCode);
667                        } catch (Exception e) {
668                                return new CopyResult(1,
669                                                "Failed to copy XML file to remote source!!!", e
670                                                                .toString());
671                        }
672                }// end of build & transfer xml file
673                /*
674                 * //command format
675                 * //"<path>/srmlite -s file:////<srcfile> -t scp://user@host/<dest path>"
676                 */
677
678                if (srcDetails.isConnectionOrigin()) {
679                        System.out
680                                        .println("*********************Building srmlite copy command");
681
682                        if (srcFile.contains(",")) {// list of files is provided.
683                                // TODO Anand: Do not use srmlite.bat - this is always a linux
684                                // machine
685                                cmd.append("srmlite -f ");
686                                cmd.append("file:///");
687                                cmd.append(cmdFile);
688                                cmd.append(" -td ");
689                        } else { // single file/directory to be copied
690                                // TODO Anand: Do not use srmlite.bat - this is always a linux
691                                // machine
692                                cmd.append("srmlite -s ");
693                                cmd.append("\"");
694                                cmd.append("file:///");
695                                cmd.append(srcFile);
696                                cmd.append("\"");
697                                if (recursive) {
698                                        cmd.append(" -recursive");
699                                }
700                                try {
701                                        if (sshObjectDest.isRemoteFileDirectory(destFile)) {
702                                                // target is a directory
703                                                cmd.append(" -td ");
704                                        } else {// target is a file
705                                                cmd.append(" -t ");
706                                        }
707                                } catch (Exception e) {
708                                        return new CopyResult(1, destFile + " not found!!!", e
709                                                        .toString());
710                                }
711                        }// single file else ends
712
713                        if (srmProtocol.equals("")) {
714                                cmd.append("scp://");
715                        } else {
716                                cmd.append(srmProtocol);
717                                cmd.append("://");
718                        }
719                        cmd.append(destDetails.toString());
720                        cmd.append(destFile);
721                } else {
722                        // Anand: destination is selected as origin
723
724                        System.out
725                                        .println("************* Building srmlite command: *****************");
726
727                        if (srcFile.contains(",")) {
728                                // TODO Anand: Add/remove .bat - this is always a linux machine
729                                cmd.append("srmlite -f ");
730                                cmd.append("file:///");
731                                cmd.append(cmdFile);
732                                cmd.append(" -td ");
733                        } else {
734                                // TODO Anand: Add/remove .bat - this is always a linux machine
735                                cmd.append("srmlite -s ");
736                                cmd.append("\"");
737                                if (srmProtocol.equals("")) {
738                                        cmd.append("scp://");
739                                } else {
740                                        cmd.append(srmProtocol);
741                                        cmd.append("://");
742                                }
743                                cmd.append(srcDetails.toString());
744                                // cmd.append("/");
745                                cmd.append(srcFile);
746                                cmd.append("\"");
747                                if (recursive) // if copying directories
748                                        cmd.append(" -recursive");
749
750                                try {
751                                        if (sshObjectDest.isRemoteFileDirectory(destFile)) {
752                                                // -td is used if target is a directory.
753                                                cmd.append(" -td ");
754                                        } else {
755                                                cmd.append(" -t ");
756                                        }
757                                } catch (Exception e) {
758                                        return new CopyResult(1, destFile + " not found!!!", e
759                                                        .toString());
760                                }
761                        }
762                        cmd.append("file:///");
763                        cmd.append(destFile);
764                }
765                if (srcDetails.isConnectionOrigin()) {
766                        if (protocolPathSrc.equals("")) {
767                                if (osname.contains("windows")) {
768                                        cmdWithPath = cmd.toString();
769                                } else {
770                                        cmdWithPath = getCmdWithDefaultPath(cmd);
771                                }
772                        } else {
773                                cmdWithPath = protocolPathSrc + cmd;
774                        }
775                } else {
776                        if (protocolPathDest.equals("")) {
777                                if (osname.contains("windows")) {
778                                        cmdWithPath = cmd.toString();
779                                } else {
780                                        cmdWithPath = getCmdWithDefaultPath(cmd);
781                                }
782                        } else {
783                                cmdWithPath = protocolPathDest + cmd;
784                        }
785                }
786
787                System.out.println("****Srmlite command executed is : " + cmdWithPath);
788
789                try {
790                        if (srcDetails.isConnectionOrigin())
791                                exitCode = sshObjectSrc.executeCmd(cmdWithPath, cmdStdout,
792                                                cmdStderr, remoteHostStr);
793                        else
794                                exitCode = sshObjectDest.executeCmd(cmdWithPath, cmdStdout,
795                                                cmdStderr, remoteHostStr);
796                } catch (ExecException e) {
797                        return new CopyResult(1, e.toString(), "");
798                }
799                if (isDebugging) {
800                        log.error("Output on stdout:" + cmdStdout);
801                        log.error("Output on stderr:" + cmdStderr);
802                }
803                String message = cmdStderr.toString();
804                message = message + " \n\n" + cmdStdout.toString();
805
806                String fileDeleteMsg = "";
807                try {
808                        boolean success = false;
809                        if (srcDetails.isConnectionOrigin())
810                                success = sshObjectSrc.deleteFile(cmdFile, false, false);
811                        else
812                                success = sshObjectDest.deleteFile(cmdFile, false, false);
813
814                        if (success) {
815                                log.debug("deleted the xml script file " + cmdFile
816                                                + " created for file copy");
817                        }
818                        if (!success) {
819                                log.warn("Unable to delete the xml script file " + cmdFile
820                                                + " created for file copy");
821                                fileDeleteMsg = "Unable to delete the xml script file "
822                                                + cmdFile + " created for file copy";
823                        }
824                } catch (ExecException e) {
825                        log.warn("Unable to delete the xml script file " + cmdFile
826                                        + " created for file copy : " + e.toString());
827                }
828                return new CopyResult(exitCode, message + fileDeleteMsg, "");
829        }
830
831        @Override
832        protected int getDefaultPort() {
833                return -1;
834        }
835
836        public String getSrmProtocol() {
837                return srmProtocol;
838        }
839
840        public void setSrmProtocol(String srmProtocol) {
841                if (null == srmProtocol) {
842                        this.srmProtocol = "";
843                } else {
844                        this.srmProtocol = srmProtocol.trim();
845                }
846        }
847
848        // New Method added by ANUSUA
849        protected int fileListCopyFrom(String cmdWithPath, String HostStr)
850                        throws Exception {
851
852                int exitCode = 0;
853                LocalExec localObject = new LocalExec();
854                localObject.setTimeout(timeout, false, false);
855                OutputStream streamOut = new ByteArrayOutputStream();
856                OutputStream streamErr = new ByteArrayOutputStream();
857                exitCode = localObject.executeCmd(cmdWithPath, streamOut, streamErr,
858                                HostStr);
859                if (isDebugging) {
860                        log.error("Output on stdout:" + streamOut);
861                        log.error("Output on stderr:" + streamErr);
862                }
863                String message = streamErr.toString();
864                message = message + " \n\n" + streamOut.toString();
865                log.debug(message);
866                return exitCode;
867        }
868
869}