Why cant i import #WithMockUser to my test - spring-boot

I am trying to do an authentication test with #With Mock User but it is refusing to import to my test class in spring boot . This is the class configuration
#WebAppConfiguration
#AutoConfigureMockMvc
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = AdminPortalApplication.class)
public class BookControllerTest {
#WithMockUser not able to import ,its red in color showing that spring boot does not recognize it, I used this dependency and property
<spring-security.version>4.0.2.RELEASE</spring-security.version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Keeps saying cannot resolve symbol #WithMockUser

Try fresh dependency. I just solved such issue with this one:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

Add an import statement for the library:
import org.springframework.security.test.context.support.WithMockUser;
And declare a dependency in your pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Try forcing gradle to refresh your dependencies:
gradle --refresh-dependencies

Related

not able to resolve import org.springframework.amqp.*; statement in my spring boot project

I'm trying to use the spring apmq core package in my spring boot project. I have added the dependency in my pom file but for some weird reason the import statement for org.springframework.amqp is not getting resolved. Any idea why is this happening??
Here is the dependency I'm using in my pom file-->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-amqp</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
And this is the import statement I'm using in my config files
import org.springframework.amqp.*;
I've already tried invalidating the caches and restarting intellij and it doesn't work for me.
You should use the Spring Boot Starter for AMQP instead:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Two the same classes in maven dependencies. sealing violation

today I have bumped with an unusual situation..
For testing Java EE I am going to use glassfish-embedded-all.
In production I am going to use apache derby data base.
So when I wrote small test class for testing DB I got this error:
java.lang.SecurityException: sealing violation: can't seal package org.apache.derby.impl.services.locks: already loaded
My pom:
<dependencies>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbynet</artifactId>
<version>10.14.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.14.2.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
The problem is that embedded server also has derby classes.
So I have dervy classes for compile and I have derby classed for tests.
And during test It causes the conflict which I don't knwo how to solve.
Seems I need to ignore derиy classes in embedded server during test. Any ideas?
My tests:
public class JpaTest {
private static final String PERSISTENCE_UNIT_NAME = "people";
private EntityManagerFactory factory;
#Before
public void setUp() throws Exception {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
// Error appear here
EntityManager em = factory.createEntityManager();
P.S.
Ican't undersnat how Maven shade plugins work. Seems this plugin ia aimed for final jar. Not for unit test right now...
P.S.2.
If i try to execute test in some Main method it works fine (becase there is no glassfish dependency)
If i don't remember wrong, maven compile scope is used in every phase of the lifecicle, so dependencies with compile scope are used on test phase too. The solution claims to exclude the derby dependencies from glassfish one to force to use yours.
More on, you have dependencies with explicit scope defined as compile, and others than nothing is specified...theese are the same, as maven takes as default scope compile one

ClassNotFoundException on Spring JavaMailSenderImpl in JUnit test with Spring Boot

I've only just started a new project with Spring Boot, which I'm trying to get to grips with. I'm using Spring Tool Suite which has created a Spring Boot project for me and loaded some dependencies which I know I'll need further down the line (specifically Spring Batch and Spring Data)
This is my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- JDBC driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
</dependencies>
I've been reading the reference documentation and know that I'll need mail at some point down the line, so I added this to my application.properties file:
spring.mail.host=my.mail.host
I then tried to build the application with mvn package but it threw an error in the tests. The test consists of the following:
package its.idcard.batch;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class IdCardBatchApplicationTests {
#Test
public void contextLoads() {
}
}
So all it's doing is trying to load the application context, but it fails with a ClassNotFoundException on org.springframework.mail.javamail.JavaMailSenderImpl.
I know this is a problem purely with the test, as after adding a bit of Spring Data stuff, and skipping tests in maven, my stub application runs as expected (and looking in the generated jar, I can see that spring-context-support-4.3.4-RELEASE.jar is present, containing the offending class), so it appears to be a classpath issue on the tests but I'm stumped. If I comment out the spring.mail.host line in the properties file, the test runs without problems.
Any ideas would be gratefully appreciated.
I think that the problem that I was just having appeared to be corrupt jar files in my maven repository. I decided to manually create the MailSender bean in my configuration class to see if that helped, but Eclipse was flagging up the class as not found, even though the jar containing it was in the maven dependencies. I then tried mvn compile from the command line, which gave me a more useful error, indicating corrupt jars, so I deleted the offending jars from my local repository and had maven re-download them and now I'm no longer getting the error in the configuration above.
Hope this helps others.

HATEOAS methods not found

My controller can't seem to find the HATEOAS methods like "linkTo".
Am I missing something?
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>org.springframework</groupId>
<artifactId>provider</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security -->
<!-- Auto configured, remove dependencies to disable. -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<!-- OAuth 2.0 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test-mvc</artifactId>
<version>1.0.0.M2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Spring MongoDB -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<!-- Spring REST MVC -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<!-- Dozer: DTO/Entity Mapper -->
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>com.provider.core.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</project>
Controller
package com.provider.core;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.provider.account.Account;
import com.provider.account.AccountDTO;
#Controller
public class AccountController
{
private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
#Autowired private AccountRepository repo;
#RequestMapping(value = "account", method = RequestMethod.POST)
public #ResponseBody HttpEntity<AccountDTO> createAccount(#RequestBody AccountDTO accountDto) {
logger.info("Start createAccount()");
Mapper mapper = new DozerBeanMapper();
Account account = mapper.map(accountDto, Account.class);
Account savedAccount = repo.save(account);
AccountDTO savedAccountDto = mapper.map(savedAccount, AccountDTO.class);
// DOES NOT COMPILE "linkto" not defined.
savedAccountDto.add(linkTo(AccountController.class).slash(savedAccountDto.getId()).withSelfRel());
return new ResponseEntity<AccountDTO>(savedAccountDto, HttpStatus.OK);
}
}
In case you are using HATEOAS v1.0 and above (Spring boot >= 2.2.0), do note that the classnames have changed. Notably the below classes have been renamed:
ResourceSupport changed to RepresentationModel
Resource changed to EntityModel
Resources changed to CollectionModel
PagedResources changed to PagedModel
ResourceAssembler changed to RepresentationModelAssembler
More information available in the official documentation here.
When using Spring boot starter, the below dependency would suffice to include HATEOAS:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Hoping this information will help someone like me who searched for hours to find why Resource class was not getting resolved.
Looks like your POM is missing the spring-hateoas dependency.
So first add this to pom.xml:
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.15.0.RELEASE</version>
</dependency>
Then you can add this static import and your code should compile:
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*
If you are using HATEOAS in eclipse(Version : Oxygen.3a Release (4.7.3a)), please note that the class names have changed.
Resource changed to EntityModel
Resources changed to CollectionModel
More information available in the official documentation below link ->
https://docs.spring.io/spring-hateoas/docs/current/reference/html/
When using Spring boot starter, you've to use below dependency to include HATEOAS:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Demo Code :
EntityModel<Users> resource = new EntityModel<Users>(user);
ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
resource.add(linkTo.withRel("all-users"));
Note : You have to import
import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.*;
Hope this information is helpful to find why Resource class was not getting resolved !!
Add following dependency :-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
<version>2.4.0</version>
</dependency>
Follow Sample Code :-
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
#GetMapping(path = "/users/{id}")
public EntityModel<User> getUserInfo(#PathVariable int id) {
User user = userDao.getUser(id);
EntityModel<User> entityModel = EntityModel.of(user);
Link link = WebMvcLinkBuilder.linkTo(methodOn(this.getClass()).getUserList()).withRel("user-list");
entityModel.add(link);
if(user == null) {
throw new UserNotFoundException("User not found with id : "+id);
}
return entityModel;
}
Add below dependency in pom.xml,it could resolve your issue.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
If above doesn't work then easy solution is got with older versions of hateos.
As new versions of Hateoas has been changed totally, below link can help you.
https://docs.spring.io/spring-hateoas/docs/current/reference/html/
Am mentioning some major changes in methods of Hateoas
ResourceSupport is now RepresentationModel
Resource is now EntityModel
Resources is now CollectionModel
PagedResources is now PagedModel
The LinkDiscoverer API has been moved to the client package.
The LinkBuilder and EntityLinks APIs have been moved to the server package.
ControllerLinkBuilder has been moved into server.mvc and deprecated to be replaced by WebMvcLinkBuilder.
RelProvider has been renamed to LinkRelationProvider and returns LinkRelation instances instead of Strings.
VndError has been moved to the mediatype.vnderror package
There are some nomenclature changes in the recent release(2.2.0 or >). Refer to this document
I'm gonna leave this here in case someone new needed it:
ControllerLinkBuilder is deprecated and you should use WebMvcLinkBuilder instead (check this https://docs.spring.io/spring-hateoas/docs/1.0.0.M1/apidocs/org/springframework/hateoas/server/mvc/ControllerLinkBuilder.html)
so instead if:
import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.*;
use this:
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
This issue occurred in my case because there are two hateoas jars one has the resource interface and other has the implementaion with same groupId and arifactId.
To Resolve this issue -->
Downgrade your STS if you're using 4.* to 3.*
Add the below dependency if you're using spring boot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
After adding this dependency run below commands in the command prompt where you're pom.xml is present
mvn clean install package
mvn eclipse:eclipse
This steps resolved issue for me.
Might be helpful for some, I see one thing thats not addressed here and couple of comments ask for this:
Cannot resolve symbol 'hal'
Cannot resolve symbol 'Jackson2HalModule'
hal module is under media now. So
org.springframework.hateoas.hal.Jackson2HalModule
is now replaced with
org.springframework.hateoas.mediatype.hal.Jackson2HalModule
The below imports are required
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
With a static import from WebMvcLinkBuilder for all methods
Like others have said, hateoas had a lot of changes. I still was running into the same issues though even with the names properly changed to EntityModel etc. because it wasn't letting me import anything from org.springframework.hateoas.
I was using maven with IntelliJ IDEA and had to right-click my pom.xml, -> maven, -> reload project. Then it let me import things from hateoas properly.
Hope this helps someone!

PagingAndSortingRepository cannot be resolved

I'm try to use PagingAndSortingRepository from Spring Data:
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Integer> {}
But I receive this error:
org.springframework.data.repository.PagingAndSortingRepository
can't be resolved
What wrong with my code and how can I fix it?
This one solved issue for me
Gradle
// https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.0.1.RELEASE'
Maven
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
I resolved this including spring-data-commons that included PagingAndSortingRepository
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
Make sure the jar is installed.
mvn clean dependency:tree
2) This what did it for me:
Delete ~.m2/org/springframework.data folder and Update maven project.
If you have <artifactId>spring-data-commons</artifactId> dependency and <artifactId>spring-data-jpa</artifactId> both, then this issue will occur.
Remove the <artifactId>spring-data-commons</artifactId> dependency.

Resources