0

I'm creating an app using spring data without spring boot, JPA with postgresql and Vaadin. I'm trying to show the data from SQL table on a Vaadin label.

My problem is that it's null and I think it's a bean creation problem.

Sorry for pasting many lines of code but I don't know where the problem may be. The main Vaadin UI:

@Theme("valo")
@SpringUI
@SuppressWarnings("serial")
public class MyUI extends UI {
    private UserRepository usersRepo;
    @Autowired
    public MyUI(UserRepository usersRepo){
        this.usersRepo = usersRepo;
    )};
    @Override
    protected void init(VaadinRequest request) {
        Label label = new Label(usersRepo.findAll().toString());
        setContent(label);
    }
}

The User class:

@Entity
@Table(name="workers", schema="public")
public class User {
    public User( String name, String surname, String username) {
        this.name= name;
        this.surname= surname;
        this.username = username;
    }
    protected User(){

    }
    @Id
    @Column(name = "userId")
    private Long userId;
    @Column(name="name")
    private String name;
    @Column(name="surname")
    private String surname;
    @Column(name="username")
    private String username;
    public Long getUserId() {
        return userId;
    }
    public void setUserId(Long userId) {
        this.userId = userId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname= surname;
    }
    public String getNameAndSurname(){
        return name+" "+surname;
    }
    @Override
    public String toString() {
        return "User [userId=" + userId + ", name=" + name + ", surname=" + surname+ ", username=" + username + "]";
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

The user repository:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByNameStartsWithIgnoreCase(String imie);
}

Web security config for spring security:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication().userSearchFilter("(sAMAccountName={0})")
        .contextSource(contextSource());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable() 
            .authorizeRequests().anyRequest().authenticated() 
            .and()
            .formLogin().permitAll() 
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/login?logged-out").permitAll() // Logout success page is accessible to anybody
            .and()
            .sessionManagement().sessionFixation().newSession(); // Create completely new session
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/*");
    }
    public LdapContextSource contextSource () {
        LdapContextSource contextSource= new LdapContextSource();
        contextSource.setUrl("ldap://192.168.1.21:3268");
        contextSource.setBase("dc=ad,dc=example,dc=com,dc=pl");
        contextSource.setUserDn("CN=someGuy,OU=Users,DC=ad,DC=example,DC=com,DC=pl");
        contextSource.setPassword("somepassword");
        contextSource.setAnonymousReadOnly(false);
        contextSource.setPooled(true);
        contextSource.afterPropertiesSet();
        return contextSource;
    }
}

Security Initializer:

public class SecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {
}

Web context initializer:

public class WebContextInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(javax.servlet.ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan(WebContextInitializer.class.getPackage().getName());
        servletContext.addListener(new ContextLoaderListener(context));
        registerServlet(servletContext);
    }
    private void registerServlet(ServletContext servletContext) {
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "vaadin", SpringVaadinServlet.class);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }
}

Configuration:

@Configuration
@EnableVaadin
public class MyConfiguration {
    @Bean
    @Autowired
    public UserRepository userRepo(){
        return new UserRepository(){

            @Override
            public void deleteAllInBatch() {
                // TODO Auto-generated method stub

            }

            @Override
            public void deleteInBatch(Iterable<User> arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public List<User> findAll() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public List<User> findAll(Sort arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public List<User> findAll(Iterable<Long> arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> List<S> findAll(Example<S> arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> List<S> findAll(Example<S> arg0, Sort arg1) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public void flush() {
                // TODO Auto-generated method stub

            }

            @Override
            public User getOne(Long arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> List<S> save(Iterable<S> arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> S saveAndFlush(S arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public Page<User> findAll(Pageable arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public long count() {
                // TODO Auto-generated method stub
                return 0;
            }

            @Override
            public void delete(Long arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void delete(User arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void delete(Iterable<? extends User> arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void deleteAll() {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean exists(Long arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public User findOne(Long arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> S save(S arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> long count(Example<S> arg0) {
                // TODO Auto-generated method stub
                return 0;
            }

            @Override
            public <S extends User> boolean exists(Example<S> arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public <S extends User> Page<S> findAll(Example<S> arg0, Pageable arg1) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public <S extends User> S findOne(Example<S> arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public List<User> findByImieStartsWithIgnoreCase(String imie) {
                // TODO Auto-generated method stub
                return null;
            }
        };
    }
    @WebServlet(value = "/*", asyncSupported = true)
    public static class Servlet extends SpringVaadinServlet {
    }
}

And finally pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pl.com.example</groupId>
    <artifactId>SpringSecurityVaadin</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringSecurityVaadin</name>

    <prerequisites>
        <maven>3</maven>
    </prerequisites>

    <properties>
        <vaadin.version>8.0.6</vaadin.version>
        <vaadin.plugin.version>8.0.6</vaadin.plugin.version>
        <jetty.plugin.version>9.3.9.v20160517</jetty.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <vaadin.widgetset.mode>local</vaadin.widgetset.mode>
        <jdk.version>1.6</jdk.version>
        <spring.version>4.3.9.RELEASE</spring.version>
        <spring.security.version>4.2.3.RELEASE</spring.security.version>
        <jstl.version>1.2</jstl.version>
    </properties>

    <repositories>
        <repository>
            <id>vaadin-addons</id>
            <url>http://maven.vaadin.com/vaadin-addons</url>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-push</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client-compiled</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-themes</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-spring</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>src/main/webapp/VAADIN/themes</directory>
                            <includes>
                                <include>**/styles.css</include>
                                <include>**/styles.scss.cache</include>
                            </includes>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.plugin.version}</version>
                <configuration>
                    <scanIntervalSeconds>2</scanIntervalSeconds>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>vaadin-prerelease</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>

            <repositories>
                <repository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </repository>
                <repository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>vaadin-prereleases</id>
                    <url>http://maven.vaadin.com/vaadin-prereleases</url>
                </pluginRepository>
                <pluginRepository>
                    <id>vaadin-snapshots</id>
                    <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>
</project>

The result is:

com.example.server.DefaultErrorHandler doDefault SEVERE: java.lang.NullPointerException at pl.com.example.SpringSecurityVaadin.MyUI.init(MyUI.java:47)

Which is this line:

Label label = new Label(usersRepo.findAll().toString());

I have no idea where the problem is, Did I configured beans wrong? or something else?

Greetings, Rafał

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Rafalsonn
  • 430
  • 7
  • 23
  • UsersRepo is not autowired. But a [MCvE] would be better If this works let me know I will post it as an answer – bichito Jun 20 '17 at 19:53
  • Did you autowired all the services,repository classess. – Akash Jun 20 '17 at 19:59
  • I think you should put @autowired upon UserRepository, and make sure your User repo is declared as a spring service – Zakaria Jun 20 '17 at 20:07
  • Thanks for hints, I think that everything is Autowired – Rafalsonn Jun 21 '17 at 08:31
  • did you place a breakpoint in the UI constructor? If it breaks you can see who is the caller and it would give you an idea of where things are not working – bichito Jun 21 '17 at 12:05
  • 2
    You have a `return new UserRepository()` in your config class, that defines `public List findAll() {return null;}`. Any particular reason why you're doing that instead of letting spring-data do its thing? Not sure without debugging, but it could be that your instance is injected, and, well, `null.toString()` ... – Morfic Jun 21 '17 at 12:17
  • Morfic makes a great point here. Return an empty list instead of null. This other question is helpful, https://stackoverflow.com/q/19414734/794088 – petey Jun 21 '17 at 21:18

1 Answers1

0
@Theme("valo")
@SpringUI
@SuppressWarnings("serial")
public class MyUI extends UI {
    private UserRepository usersRepo;
    @Autowired
    public MyUI(UserRepository usersRepo){
        this.usersRepo = usersRepo;
    )};

This is the entry point of the vaadin app. usersRepo is not autowired. Any use of it will result in a NPE. This should work for you

    @Autowired
    private UserRepository usersRepo;
bichito
  • 1,406
  • 2
  • 19
  • 23
  • I've tried to autowire this, but with still the same NPE, I've also tried something like this: `ApplicationContext ctx = new` `AnnotationConfigApplicationContext(MyConfiguration.class);` `UserRepository usersRepo1 =` `ctx.getBean(UserRepository.class);` `Label label = new Label(usersRepo1.findAll().toString());` but also NPE – Rafalsonn Jun 21 '17 at 08:22
  • OP has an autowired constructor. I don't see why this should be necessarily replaced by an autowired field... – Morfic Jun 21 '17 at 10:06
  • @Morfic This is the vaadin entry point class. The likelihood of the constructor annotation being ignored is really high. I am using vaadin with no constructor and works like a champ. So if this doesn't work then I would provide an [MCVE] because is too much code. I am using this pattern extensively "...Theme("vale") ...SpringUI(path = "client") public final class ClientView extends UI { ...Autowired private RestTemplate...." – bichito Jun 21 '17 at 11:46
  • I see your reasoning and I myself use field/setter injection, but I highly doubt Spring would ignore one of its fundamental functionalities, which is dependency injection via constructors (and also what [they currently recommend](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-setter-injection) - scroll a few lines to `Constructor-based or setter-based DI?`). After all, the Spring context is where the UI instance is retrieved, right? What I'm trying to say is that I suspect the problem is elsewhere, and not with the way the dependency is injected. – Morfic Jun 21 '17 at 12:14
  • Thais why I asked the op to place a breakpoint in the constructor. If it breaks then we know – bichito Jun 21 '17 at 12:29
  • I didn't found the reason why this was happening, the solution was easy, I've made the same app in spring boot and it worked, I don't know why it was crashing without spring boot – Rafalsonn Aug 12 '17 at 08:06