NullPointerException Hibernate

Olá. Bom sou novo no fórum, e também novo no desenvolvimento de java. Estou construindo uma aplicação simples, que vai pegar um arquivo de texto do ftp e depois gravar esse arquivo no banco de dados.
As credenciais para acessar o ftp, estão armazenadas também no banco de dados.
Acontece, que ao buscar esses dados no banco, o Spring me joga erro de NullPointerException. já isolei e execute o metódo direto no service dele e trás resultado normalmente, não sei porque quando chamo ele através do arquivo de ftp, ele dá esse erro. Segue abaixo o meu código, e agradeço toda ajuda possível.

    package br.com.symbiosyssolucoes.PharmaIntegration.services;


    import br.com.symbiosyssolucoes.PharmaIntegration.entity.Connections;
    import br.com.symbiosyssolucoes.PharmaIntegration.repository.ConnectionsRepository;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.apache.commons.net.PrintCommandListener;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;
    import org.springframework.stereotype.Service;

    import javax.transaction.Transactional;
    import java.io.*;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Optional;
    import java.util.Scanner;
    import java.util.stream.Collectors;


    @Service
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Transactional
    public class FtpConnection {

        private ConnectionsRepository connectionsRepository;
        private FTPClient ftp;




        public void menu(Scanner scanner) throws IOException {
            Boolean isTrue = true;

            while (isTrue) {
                System.out.println("Qual ação você quer executar?");
                System.out.println("0 - Voltar ao menu anterior");
                System.out.println("1 - Abrir Conexão");
                System.out.println("2 - Fechar Conexão");
                System.out.println("3 - Listar Arquivos");
                System.out.println("4 - Subir Arquivos");
                System.out.println("5 - Baixar Arquivos");

                int opcao = scanner.nextInt();

                switch (opcao) {
                    case 1:
                        this.open();
                        break;
                    case 2:
                        this.close();
                        break;
                    case 3:
                        this.listFiles("/ret/");
                        break;
                    case 4:
                        this.putFileToPath(new File("/test.txt"),"/");
                        break;
                    case 5:
                        this.downloadFile("/test.txt","C:\\Cronos\\");
                        break;
                    default:
                        isTrue = false;
                        break;

                }
            }
            System.out.println();
        }


        private void open() throws IOException {
            Long id = 1L;
            Optional<Connections> optional = this.connectionsRepository.findById(id);

            if(optional.isPresent()){

                Connections connections = optional.get();
                System.out.println(connections.toString());
                String server = "symbiosyssolucoes.com.br";
                int port = 21;
                String user = "legrand";
                String password = "@nfs32xpt#";
                ftp = new FTPClient();

                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

                ftp.connect(server, port);
                int reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    throw new IOException("Exception in connecting to FTP Server");
                }

                ftp.login(user, password);

            } else {
                System.out.println("Id Passado é invalido");
            }




        }

        private void close() throws IOException {
            ftp.disconnect();
        }

        private Collection<String> listFiles(String path) throws IOException {
            FTPFile[] files = ftp.listFiles(path);

            return Arrays.stream(files)
                    .map(FTPFile::getName)
                    .collect(Collectors.toList());
        }

        private void putFileToPath(File file, String path) throws IOException {
            ftp.storeFile(path, new FileInputStream(file));
        }

        private void downloadFile(String source, String destination) throws IOException {
            FileOutputStream out = new FileOutputStream(destination);
            ftp.retrieveFile(source, out);
            out.close();
        }
    }

Mostra o StackTrace. Assim é impossível de adivinhar onde pode estar o NullPointer

1 curtida

Desculpa a minha falta de conhecimento, mas o que seria o Stack Trace, e como faço para ver?

O erro de NullPointer tem a seguir toda a informação das classes e linhas relacionadas com o erro.

1 curtida

Essa é a mensagem de erro, seria isso?

java.lang.NullPointerException: null
	at br.com.symbiosyssolucoes.PharmaIntegration.services.FtpConnection.open(FtpConnection.java:79) ~[classes/:na]
	at br.com.symbiosyssolucoes.PharmaIntegration.services.FtpConnection.menu(FtpConnection.java:53) ~[classes/:na]
	at br.com.symbiosyssolucoes.PharmaIntegration.services.FtpConnection$$FastClassBySpringCGLIB$$c2993bb5.invoke(<generated>) ~[classes/:na]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779) ~[spring-aop-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) ~[spring-aop-5.3.3.jar:5.3.3]
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.3.jar:5.3.3]
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.3.jar:5.3.3]
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) ~[spring-aop-5.3.3.jar:5.3.3]
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) ~[spring-aop-5.3.3.jar:5.3.3]
	at br.com.symbiosyssolucoes.PharmaIntegration.services.FtpConnection$$EnhancerBySpringCGLIB$$5cc27805.menu(<generated>) ~[classes/:na]
	at br.com.symbiosyssolucoes.PharmaIntegration.PharmaIntegrationApplication.run(PharmaIntegrationApplication.java:44) ~[classes/:na]
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.2.jar:2.4.2]
	... 5 common frames omitted

Isto diz que o NullPointer está na linha 79 da tua classe. E nessa linha tens

Optional<Connections> optional = this.connectionsRepository.findById(id);

O teu this.connectionsRepository está a null. Deve faltar alguma anotação do Spring (@Autowired ?)

1 curtida

Muito Obrigado, colocando a anotação @AutoWired, solucionou o problema. Agora vou estudar o que essa anotação faz.