CustomJschConfigSessionFactory.java Source code

Java tutorial

Introduction

Here is the source code for CustomJschConfigSessionFactory.java

Source

import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import org.eclipse.jgit.errors.UnsupportedCredentialItem;
import org.eclipse.jgit.transport.CredentialItem;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.CredentialsProviderUserInfo;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.URIish;
import org.json.JSONException;
import org.json.JSONObject;

/**
 Copyright 2016 Alianza Inc.
    
 Licensed 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.
    
 */

public class CustomJschConfigSessionFactory extends JschConfigSessionFactory {
    JSONObject config = ConfigParser.getConfig();

    @Override
    protected void configure(OpenSshConfig.Host host, Session session) {
        CredentialsProvider provider = new CredentialsProvider() {
            @Override
            public boolean isInteractive() {
                return false;
            }

            @Override
            public boolean supports(CredentialItem... credentialItems) {
                return true;
            }

            @Override
            public boolean get(URIish urIish, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
                for (CredentialItem item : credentialItems) {
                    try {
                        ((CredentialItem.StringType) item).setValue(config.getString("privateKeyPassPhrase"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }
        };
        UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
        session.setUserInfo(userInfo);
        session.setConfig("StrictHostKeyChecking", "yes");
    }
}