001    package org.apache.maven.scm.provider.integrity;
002    
003    /**
004     * Licensed to the Apache Software Foundation (ASF) under one
005     * or more contributor license agreements.  See the NOTICE file
006     * distributed with this work for additional information
007     * regarding copyright ownership.  The ASF licenses this file
008     * to you under the Apache License, Version 2.0 (the
009     * "License"); you may not use this file except in compliance
010     * with the License.  You may obtain a copy of the License at
011     *
012     * http://www.apache.org/licenses/LICENSE-2.0
013     *
014     * Unless required by applicable law or agreed to in writing,
015     * software distributed under the License is distributed on an
016     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017     * KIND, either express or implied.  See the License for the
018     * specific language governing permissions and limitations
019     * under the License.
020     */
021    
022    import com.mks.api.CmdRunner;
023    import com.mks.api.Command;
024    import com.mks.api.IntegrationPoint;
025    import com.mks.api.IntegrationPointFactory;
026    import com.mks.api.Session;
027    import com.mks.api.response.APIException;
028    import com.mks.api.response.Response;
029    import org.apache.maven.scm.log.ScmLogger;
030    import org.codehaus.plexus.util.StringUtils;
031    
032    import java.io.IOException;
033    
034    /**
035     * The APISession provides a wrapper for the MKS JAVA API
036     *
037     * @author <a href="mailto:cletus@mks.com">Cletus D'Souza</a>
038     * @version $Id: APISession.java 1.2 2011/08/22 13:06:44EDT Cletus D'Souza (dsouza) Exp  $
039     * @since 1.6
040     */
041    public class APISession
042    {
043        // Store the API Version
044        public static final String VERSION =
045            IntegrationPointFactory.getAPIVersion().substring( 0, IntegrationPointFactory.getAPIVersion().indexOf( ' ' ) );
046    
047        public static final int MAJOR_VERSION = Integer.parseInt( VERSION.substring( 0, VERSION.indexOf( '.' ) ) );
048    
049        public static final int MINOR_VERSION =
050            Integer.parseInt( VERSION.substring( VERSION.indexOf( '.' ) + 1, VERSION.length() ) );
051    
052        // Logs all API work...
053        private ScmLogger logger;
054    
055        // Class variables used to create an API Session
056        private String hostName;
057    
058        private int port = 0;
059    
060        private String userName;
061    
062        private String password;
063    
064        // API Specific Objects
065        private IntegrationPoint ip;
066    
067        private Session session;
068    
069        private boolean terminated;
070    
071        /**
072         * Constructor for the API Session Object
073         * Needs an ScmLogger to log all API operations
074         *
075         * @param logger
076         */
077        public APISession( ScmLogger logger )
078        {
079            logger.info( "MKS Integrity API Version: " + VERSION );
080            this.logger = logger;
081        }
082    
083        /**
084         * Establishes a connection with the MKS Integrity Server
085         *
086         * @param host    Hostname or IP address for the MKS Integrity Server
087         * @param portNum Port number for the MKS Integrity Server
088         * @param user    Username to connect to the MKS Integrity Server
089         * @param paswd   Password for the User connecting to the server
090         * @throws APIException
091         */
092        public Response connect( String host, int portNum, String user, String paswd )
093            throws APIException
094        {
095            // Initialize our termination flag...
096            terminated = false;
097            // Create a local integration point
098            ip = IntegrationPointFactory.getInstance().createLocalIntegrationPoint( MAJOR_VERSION, MINOR_VERSION );
099            // Set the flag to automatically start the MKS Integrity Client, if not running
100            ip.setAutoStartIntegrityClient( true );
101            // Use a common session, which means we don't have to manage the password
102            if ( null != paswd && paswd.length() > 0 )
103            {
104                logger.info( "Creating session for " + user + "/" + StringUtils.repeat( "*", paswd.length() ) );
105                session = ip.createSession( user, paswd );
106                logger.info( "Attempting to establish connection using " + user + "@" + host + ":" + portNum );
107            }
108            else
109            {
110                logger.info( "Using a common session.  Connection information is obtained from client preferences" );
111                session = ip.getCommonSession();
112            }
113            // Test the connection to the MKS Integrity Server
114            Command ping = new Command( Command.SI, "connect" );
115            CmdRunner cmdRunner = session.createCmdRunner();
116            // Initialize the command runner with valid connection information
117            if ( null != host && host.length() > 0 )
118            {
119                cmdRunner.setDefaultHostname( host );
120            }
121            if ( portNum > 0 )
122            {
123                cmdRunner.setDefaultPort( portNum );
124            }
125            if ( null != user && user.length() > 0 )
126            {
127                cmdRunner.setDefaultUsername( user );
128            }
129            if ( null != paswd && paswd.length() > 0 )
130            {
131                cmdRunner.setDefaultPassword( paswd );
132            }
133            // Execute the connection
134            Response res = cmdRunner.execute( ping );
135            logger.debug( res.getCommandString() + " returned exit code " + res.getExitCode() );
136            // Initialize class variables based on the connection information
137            hostName = res.getConnectionHostname();
138            port = res.getConnectionPort();
139            userName = res.getConnectionUsername();
140            password = paswd;
141            cmdRunner.release();
142            logger.info( "Successfully established connection " + userName + "@" + hostName + ":" + port );
143            return res;
144        }
145    
146        /**
147         * This function executes a generic API Command
148         *
149         * @param cmd MKS API Command Object representing an API command
150         * @return MKS API Response Object
151         * @throws APIException
152         */
153        public Response runCommand( Command cmd )
154            throws APIException
155        {
156            CmdRunner cmdRunner = session.createCmdRunner();
157            cmdRunner.setDefaultHostname( hostName );
158            cmdRunner.setDefaultPort( port );
159            cmdRunner.setDefaultUsername( userName );
160            if ( null != password && password.length() > 0 )
161            {
162                cmdRunner.setDefaultPassword( password );
163            }
164            Response res = cmdRunner.execute( cmd );
165            logger.debug( res.getCommandString() + " returned exit code " + res.getExitCode() );
166            cmdRunner.release();
167            return res;
168        }
169    
170        /**
171         * This function executes a generic API Command impersonating another user
172         *
173         * @param cmd             MKS API Command Object representing a API command
174         * @param impersonateUser The user to impersonate
175         * @return MKS API Response Object
176         * @throws APIException
177         */
178        public Response runCommandAs( Command cmd, String impersonateUser )
179            throws APIException
180        {
181            CmdRunner cmdRunner = session.createCmdRunner();
182            cmdRunner.setDefaultHostname( hostName );
183            cmdRunner.setDefaultPort( port );
184            cmdRunner.setDefaultUsername( userName );
185            if ( null != password && password.length() > 0 )
186            {
187                cmdRunner.setDefaultPassword( password );
188            }
189            cmdRunner.setDefaultImpersonationUser( impersonateUser );
190            Response res = cmdRunner.execute( cmd );
191            logger.debug( res.getCommandString() + " returned exit code " + res.getExitCode() );
192            cmdRunner.release();
193            return res;
194        }
195    
196        /**
197         * Terminate the API Session and Integration Point
198         */
199        public void Terminate()
200        {
201            // Terminate only if not already terminated!
202            if ( !terminated )
203            {
204                try
205                {
206                    if ( null != session )
207                    {
208                        session.release();
209                    }
210    
211                    if ( null != ip )
212                    {
213                        ip.release();
214                    }
215                    terminated = true;
216                    logger.info( "Successfully disconnected connection " + userName + "@" + hostName + ":" + port );
217                }
218                catch ( APIException aex )
219                {
220                    logger.debug( "Caught API Exception when releasing session!" );
221                    aex.printStackTrace();
222                }
223                catch ( IOException ioe )
224                {
225                    logger.debug( "Caught IO Exception when releasing session!" );
226                    ioe.printStackTrace();
227                }
228            }
229        }
230    
231        /**
232         * Returns the MKS Integrity Hostname for this APISession
233         *
234         * @return
235         */
236        public String getHostName()
237        {
238            return hostName;
239        }
240    
241        /**
242         * Returns the MKS Integrity Port for this APISession
243         *
244         * @return
245         */
246        public int getPort()
247        {
248            return port;
249        }
250    
251        /**
252         * Returns the MKS Integrity User for this APISession
253         *
254         * @return
255         */
256        public String getUserName()
257        {
258            return userName;
259        }
260    
261        /**
262         * Returns the MKS Integrity Password for this APISession
263         *
264         * @return
265         */
266        public String getPassword()
267        {
268            if ( null != password && password.length() > 0 )
269            {
270                return password;
271            }
272            else
273            {
274                return "";
275            }
276        }
277    
278        /**
279         * Returns the ScmLogger for this APISession
280         */
281        public ScmLogger getLogger()
282        {
283            return logger;
284        }
285    }