classcastexceptionjgit

JGit throws ClassCastException in TransportConfigCallback


I am trying to use JGit. I tried following http://www.codeaffine.com/2014/12/09/jgit-authentication/ and the following block of the code throws a ClassCastException

remoteRepository.setTransportConfigCallback(new TransportConfigCallback() {
    @Override
    public void configure(Transport transport) {
        SshTransport sshTransport = (SshTransport) transport;
        sshTransport.setSshSessionFactory(sshSessionFactory);
    }
});

Exception:

java.lang.ClassCastException: org.eclipse.jgit.transport.TransportHttp cannot be cast to org.eclipse.jgit.transport.SshTransport

What am I missing? I am using JGit version 4.10.0.201712302008-r.


Solution

  • The code is only meant to handle SSH connections. If you are connecting through other protocols, you need to adjust the code to be aware that transport can be something different than SshTransport.

    For example:

    command.setTransportConfigCallback(new TransportConfigCallback() {
      @Override
      public void configure(Transport transport) {
        if(transport instanceof SshTransport) {
          SshTransport sshTransport = (SshTransport) transport;
          sshTransport.setSshSessionFactory(sshSessionFactory);
        } else if(transport instanceof HttpTransport) {
          // configure HTTP protocol specifics
        }
      }
    } );