Package sos.net.ssh

Source Code of sos.net.ssh.SOSSSHJob2SuperClass

/********************************************************* begin of preamble
**
** Copyright (C) 2003-2010 Software- und Organisations-Service GmbH.
** All rights reserved.
**
** This file may be used under the terms of either the
**
**   GNU General Public License version 2.0 (GPL)
**
**   as published by the Free Software Foundation
**   http://www.gnu.org/licenses/gpl-2.0.txt and appearing in the file
**   LICENSE.GPL included in the packaging of this file.
**
** or the
** 
**   Agreement for Purchase and Licensing
**
**   as offered by Software- und Organisations-Service GmbH
**   in the respective terms of supply that ship with this file.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
** THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
** BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
********************************************************** end of preamble*/
package sos.net.ssh;

import java.io.File;

import com.sos.JSHelper.Basics.JSToolBox;
import com.sos.i18n.annotation.I18NResourceBundle;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.SFTPv3Client;
import com.trilead.ssh2.SFTPv3FileAttributes;
import com.trilead.ssh2.Session;

/**
* \class SOSSSHJob2SuperClass
*
* \brief SOSSSHJob2SuperClass -
*
* \details
*
* \section SOSSSHJob2SuperClass.java_intro_sec Introduction
*
* \section SOSSSHJob2SuperClass.java_samples Some Samples
*
* \code
*   .... code goes here ...
* \endcode
*
* <p style="text-align:center">
* <br />---------------------------------------------------------------------------
* <br /> APL/Software GmbH - Berlin
* <br />##### generated by ClaviusXPress (http://www.sos-berlin.com) #########
* <br />---------------------------------------------------------------------------
* </p>
* \author KB
* @version $Id$16.05.2010
* \see reference
*
* Created on 16.05.2010 19:17:53
*/
@I18NResourceBundle(baseName = "com.sos.net.messages", defaultLocale = "en")
public class SOSSSHJob2SuperClass extends JSToolBox {

  private final String  conClassName  = "SOSSSHJob2SuperClass";

  SOSSSHJob2SuperClass() {
    //
  }
  protected SOSSSHJobOptions  objOptions        = null;

  /** ssh connection object */
  protected Connection    sshConnection      = null;

  /** ssh session object */
  protected Session      sshSession        = null;

  public void Options(final SOSSSHJobOptions pobjOptions) throws Exception {
    objOptions = pobjOptions;
    objOptions.CheckMandatory();
  }

  /**
   *
   * \brief Options
   *
   * \details
   *
   * \return SOSSSHJobOptions
   *
   * @return
   */
  public SOSSSHJobOptions Options() {

    @SuppressWarnings("unused")
    final String conMethodName = conClassName + "::Options";

    if (objOptions == null) {
      objOptions = new SOSSSHJobOptions();
    }
    return objOptions;
  }


  /**
   * Authentication-Processing
   *
   */
  protected Connection getBaseAuthentication() throws Exception {

    final String conMethodName = conClassName + "::getBaseAuthentication";

    try { // to connect and authenticate
      boolean isAuthenticated = false;
      this.setSshConnection(new Connection(Options().host.Value(), objOptions.port.value()));

      if (objOptions.proxy_host.IsEmpty() == false) {
        if (objOptions.proxy_user.IsEmpty() == false) {
          this.getSshConnection().setProxyData(new HTTPProxyData(objOptions.proxy_host.Value(), objOptions.proxy_port.value()));
        }
        else {
          this.getSshConnection().setProxyData(
              new HTTPProxyData(objOptions.proxy_host.Value(), objOptions.proxy_port.value(), objOptions.proxy_user.Value(),
                  objOptions.proxy_password.Value()));
        }
      }

      this.getSshConnection().connect();

      if (objOptions.auth_method.isPublicKey()) {
        /**
         * \todo
         * TODO File-Handling in der Option-Klasse abhandeln. Return vom Type JSFile einbauen
         */
        File authenticationFile = new File(objOptions.auth_file.Value());
        if (!authenticationFile.exists())
          throw new Exception("authentication file does not exist: " + authenticationFile.getCanonicalPath());
        if (!authenticationFile.canRead())
          throw new Exception("authentication file not accessible: " + authenticationFile.getCanonicalPath());

        isAuthenticated = this.getSshConnection().authenticateWithPublicKey(objOptions.user.Value(), authenticationFile, objOptions.password.Value());
      }
      else
        if (objOptions.auth_method.isPassword()) {
          isAuthenticated = this.getSshConnection().authenticateWithPassword(objOptions.user.Value(), objOptions.password.Value());
        }

      if (!isAuthenticated) {
//        throw new Exception("authentication failed [host=" + this.getHost() + ", port=" + this.getPort() + ", user:" + this.getUser()
//            + ", auth_method=" + this.getAuthenticationMethod() + ", auth_file=" + this.getAuthenticationFilename());
        throw new Exception(conMethodName + ": " + "authentication failed " + objOptions.toString());
      }
     
      return this.getSshConnection();

    }
    catch (Exception e) {
      if (this.getSshConnection() != null)
        try {
          this.getSshConnection().close();
          this.setSshConnection(null);
        }
        catch (Exception ex) {
        }
      throw new Exception(e.getMessage());
    }
  }

  /**
   * Check existence of a file or directory
   *
   * @param sftpClient
   * @param filename
   * @return true, if file exists
   * @throws Exception
   */
  protected boolean sshFileExists(SFTPv3Client sftpClient, String filename) {

    try {
      SFTPv3FileAttributes attributes = sftpClient.stat(filename);

      if (attributes != null) {
        return (attributes.isRegularFile() || attributes.isDirectory());
      }
      else {
        return false;
      }

    }
    catch (Exception e) {
      return false;
    }
  }

  /**
   * Checks if file is a directory
   *
   * @param sftpClient
   * @param filename
   * @return true, if filename is a directory
   */
  protected boolean isDirectory(SFTPv3Client sftpClient, String filename) {
    try {
      return sftpClient.stat(filename).isDirectory();
    }
    catch (Exception e) {
    }
    return false;
  }

  /**
   * Returns the file size of a file
   *
   * @param sftpClient
   * @param filename
   * @return the size of the file
   * @throws Exception
   */
  protected long getFileSize(SFTPv3Client sftpClient, String filename) throws Exception {
    return sftpClient.stat(filename).size.longValue();
  }

  /**
   * Check existence of a file or directory
   *
   * @param sftpClient
   * @param filename
   * @return integer representation of file permissions
   * @throws Exception
   */
  protected int sshFilePermissions(SFTPv3Client sftpClient, String filename) {

    try {
      SFTPv3FileAttributes attributes = sftpClient.stat(filename);

      if (attributes != null) {
        return attributes.permissions.intValue();
      }
      else {
        return 0;
      }

    }
    catch (Exception e) {
      return 0;
    }
  }

  /**
   * normalize / to \ and remove trailing slashes from a path
   *
   * @param path
   * @return normalized path
   * @throws Exception
   */
  private String normalizePath(String path) throws Exception {

    String normalizedPath = path.replaceAll("\\\\", "/");
    while (normalizedPath.endsWith("\\") || normalizedPath.endsWith("/")) {
      normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1);
    }

    return normalizedPath;
  }

  /**
   * @return Returns the sshConnection.
   */
  protected Connection getSshConnection() {
    return sshConnection;
  }

  /**
   * @param sshConnection The sshConnection to set.
   */
  protected void setSshConnection(Connection sshConnection) {
    this.sshConnection = sshConnection;
  }

  /**
   * @return Returns the sshSession.
   */
  public Session getSshSession() {
    return sshSession;
  }

  /**
   * @param sshSession The sshSession to set.
   */
  public void setSshSession(Session sshSession) {
    this.sshSession = sshSession;
  }


}
TOP

Related Classes of sos.net.ssh.SOSSSHJob2SuperClass

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.