Junit/Fongo: How to make use of Fongo in the unit test for checking NotNull - spring

I am writing a basic unit test that checks whether the returned query (type DataVersion) is not null. I have to make sure that I am using Fongo for testing my db.
This is the repo class:
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
#Autowired
MongoOperations mongoOperations;
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion findByDBAndCollection(String dbName, String collectionName) {
Criteria criteria = Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName);
Query query = Query.query(criteria);
return mongoOperations.findOne(query, DataVersion.class);
}
}
This is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
#Autowired
private DataVersionDaoMongo dataVersionDaoMongo;
#Autowired
private MongoOperations mongoOperations;
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
//String dbname = "mydb";
//String collectionName = "mycollection";
// DB db = fongoRule.getDB(dbname);
//DBCollection collection = db.getCollection(collectionName);
//Mongo mongo = fongoRule.getMongo();
//collection.insert(new BasicDBObject("name", "randomName"));
DataVersion dataVersion = new DataVersion();
dataVersion.setDbName("DBDataVersion");
dataVersion.setVersion("version1");
dataVersion.setCollectionName("DataVersion");
mongoOperations.insert(dataVersion);**strong text**
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
Here is the DataVersion class:
#Document(collection = "DataVersion")
public class DataVersion {
#Id
private String id;
private String dbName;
private String collectionName;
private String version;
private boolean isCompleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((collectionName == null) ? 0 : collectionName.hashCode());
result = prime * result + ((dbName == null) ? 0 : dbName.hashCode());
result = prime * result + (isCompleted ? 1231 : 1237);
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DataVersion other = (DataVersion) obj;
if (collectionName == null) {
if (other.collectionName != null)
return false;
} else if (!collectionName.equals(other.collectionName))
return false;
if (dbName == null) {
if (other.dbName != null)
return false;
} else if (!dbName.equals(other.dbName))
return false;
if (isCompleted != other.isCompleted)
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
}
This is testApplicationContext file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<bean name="fongo" class="com.github.fakemongo.Fongo">
<constructor-arg value="InMemoryMongo" />
</bean>
<bean id="mongo" factory-bean="fongo" factory-method="getMongo" />
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />
<!-- localhost settings for mongo -->
<!--<mongo:db-factory id="mongoDbFactory" />-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
</bean>
</beans>
Although my unit test is passing because I declared dataVersion variable and set the values such as DbName, Version, CollectionName inside my test and calls the method findByDBandCollection. But I am not making use of Fongo DB here and I want to make use of it. How can I go about and make use of Fongo db in my test and use assertThat so that the DataVersion returned by calling findByDBAndCollection method is not null?

I created an example which illustrates that.

Related

Issue in Saving entities with Many to Many relation in SpringData JPA / Hibernate

I have Many-to-many relation for user to role entity.
So I created Bidirectional mapping with link entity life cycle.
Note: Role table is already prepopulated with the data by other process
Employee.java
#Entity
#Table(name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "EMPLOYEE_SEQ"
)
#GenericGenerator(
name = "EMPLOYEE_SEQ",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
#Parameter(name = "sequence_name", value = "EMPLOYEE_SEQ"),
#Parameter(name = "initial_value", value = "1"),
#Parameter(name = "increment_size", value = "3"),
#Parameter(name = "optimizer", value = "pooled-lo")
}
)
private Long id;
#Column(name="NAME")
private String name;
#OneToMany(mappedBy="employee", cascade= CascadeType.ALL,orphanRemoval=true)
private List<EmployeeRole> roles = new ArrayList<EmployeeRole>();
// Removed setters and getters
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public void addRole(Role role)
{
EmployeeRole employeeRole = new EmployeeRole(this,role);
roles.add(employeeRole);
role.getEmployee().add(employeeRole);
}
}
Role.Java
#Entity
#Table(name="ROLE")
public class Role {
#Id
private Long id;
private String roleName;
#OneToMany(mappedBy="role",cascade = CascadeType.ALL,orphanRemoval= true)
private List<EmployeeRole> employee = new ArrayList<EmployeeRole>();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Role other = (Role) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
EmployeeRole.java
#Entity(name = "EmployeeRole")
public class EmployeeRole implements Serializable {
public EmployeeRole() {
}
public EmployeeRole(Employee employee, Role role) {
super();
this.employee = employee;
this.role = role;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
private Employee employee;
#Id
#ManyToOne
private Role role;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employee == null) ? 0 : employee.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EmployeeRole other = (EmployeeRole) obj;
if (employee == null) {
if (other.employee != null)
return false;
} else if (!employee.equals(other.employee))
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
return true;
}
}
EmployeeService.java
#Autowired
EmployeeRepository employeeRepo;
#Autowired
RoleRepository roleRepo;
#Transactional
public void addEmployee(EmployeeDTO employeedto) {
Employee employeeDB = employeeRepo.findByName(employeedto.getEmployeeName());
Role roleDB = roleRepo.findByRoleName(employeedto.getRoles().get(0).getRoleName());
if(employeeDB==null) {
employeeDB = new Employee();
}
employeeDB.setName(employeedto.getEmployeeName());
if(roleDB == null) {
roleDB = new Role();
}
employeeDB.addRole(roleDB);
employeeRepo.save(employeeDB);
}
Problem Statement:
When I save the below Request body, I was able to create the new employee Sara and link the 'Admin' role.
{
"employeeName": "Sara",
"roles": [{
"roleName": "Admin"
}
]
}
But when I try to link another role 'Read' to the same user 'Sara' I am getting the below exception
{
"employeeName": "Sara",
"roles": [{
"roleName": "Read"
}
]
}
Exception:
2019-12-12 14:01:21.625 WARN 41064 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1400, SQLState: 23000
2019-12-12 14:01:21.625 ERROR 41064 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-01400: cannot insert NULL into ("SCHEMA"."EMPLOYEE_ROLE"."ROLE_ID")
Thoughts on this please.

JUnit/Spring/MongoDB: Unit test fails due to null value

I am fairly new to unit test and started writing a simple test to make sure the returned query is not null using assertJ. I am using Fongo for my unit test and although I am having no error, the returned value is always null.
This is the class to be tested:
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
#Autowired
MongoOperations mongoOperations;
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion findByDBAndCollection(String dbName, String collectionName) {
//return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
Criteria criteria = Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName);
Query query = Query.query(criteria);
return mongoOperations.findOne(query, DataVersion.class);
}
}
This is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
#Autowired
private DataVersionDaoMongo dataVersionDaoMongo;
//private MongoOperations mongoOperations;
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
String dbname = "mydb";
String collectionName = "mycollection";
DB db = fongoRule.getDB(dbname);
DBCollection collection = db.getCollection(collectionName);
Mongo mongo = fongoRule.getMongo();
collection.insert(new BasicDBObject("name", "randomName"));
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
I am sure that
dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName) is returning null (It is returning DataVersion object which is null), so the test fails. How would I actually go about and make it return DataVersion that is not null?
Here is the DataVersion class:
#Document(collection = "DataVersion")
public class DataVersion {
#Id
private String id;
private String dbName;
private String collectionName;
private String version;
private boolean isCompleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((collectionName == null) ? 0 : collectionName.hashCode());
result = prime * result + ((dbName == null) ? 0 : dbName.hashCode());
result = prime * result + (isCompleted ? 1231 : 1237);
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DataVersion other = (DataVersion) obj;
if (collectionName == null) {
if (other.collectionName != null)
return false;
} else if (!collectionName.equals(other.collectionName))
return false;
if (dbName == null) {
if (other.dbName != null)
return false;
} else if (!dbName.equals(other.dbName))
return false;
if (isCompleted != other.isCompleted)
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
}
Any help would be greatly appreciated!
P.S.
This is what I am adding in my unit test class:
#Autowired
private MongoOperations mongoOperations;
Then
DataVersion dataVersion = new DataVersion();
dataVersion.setDbName("DBDataVersion");
dataVersion.setVersion("version1");
dataVersion.setCollectionName("DataVersion");
mongoOperations.insert(dataVersion);
assertThat(dataVersionDaoMongo.findByDBAndCollection(dataVersionDaoMongo.getDbName(), dataVersion.getCollectionName())).isNotNull();
The unit test passes because it is no longer returning null, but then I am not making use of Fongo anymore. I am not sure if what I am doing is right or not.
You insert the document into mycollection collection in the test but the dao queries DataVersion collection.
Also you don't define dbName and collectionName in the stored object, hence, it won't be picked by a query which targets that two fields.

Does it exist a way for autowiring any Spring #Component inside a JPA repository?

The point is i have a Custom JPA Repository which is load using "#EnableJpaRepositories", but inside of this Custom JPA repository i do autowire another Spring Bean annotated with #Component, but it never comes filled, always bringing a null reference...
I read that JPA Repository does join and share the same Spring Application Context and so it cannot see those Beans loaded by the common Application Context... Is it really true? If so, is there any way to glue them and make Custom Repositories to inject my componentes properly???
Down here the relevant code:
public class DefaultCrudRepository<T extends IdentifiableEntity> extends QuerydslJpaRepository<T, BigInteger>
implements CrudRepository<T> {
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
private JpaEntityInformation<T, BigInteger> jpaEntityInformation;
private EntityManager entityManager;
private EntityPath<T> path;
private PathBuilder<T> builder;
private Querydsl querydsl;
#Autowired
private SortComponent sortComponent;
#Autowired
private PageComponent pageComponent;
#Autowired
private FilterComponent filterComponent;
#Autowired
private ExpandComponent expandComponent;
public DefaultCrudRepository(JpaEntityInformation<T, BigInteger> jpaEntityInformation, EntityManager entityManager,
EntityPathResolver resolver) {
super(jpaEntityInformation, entityManager, resolver);
this.jpaEntityInformation = jpaEntityInformation;
this.entityManager = entityManager;
this.path = resolver.createPath(jpaEntityInformation.getJavaType());
this.builder = new PathBuilder<T>(path.getType(), path.getMetadata());
this.querydsl = new Querydsl(entityManager, builder);
this.expandComponent = new DefaultExpandComponent(entityManager);
this.sortComponent = new DefaultSortComponent();
this.filterComponent = new DefaultFilterComponent();
this.pageComponent = new DefaultPageComponent();
init();
}
public DefaultCrudRepository(JpaEntityInformation<T, BigInteger> jpaEntityInformation,
EntityManager entityManager) {
this(jpaEntityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
this.jpaEntityInformation = jpaEntityInformation;
this.entityManager = entityManager;
}
/*
* private Class<?> getDomainClass(Class<?> clazz) { Type type =
* clazz.getGenericSuperclass(); if (type instanceof ParameterizedType) {
* ParameterizedType parameterizedType = (ParameterizedType) type; return
* (Class<?>) parameterizedType.getActualTypeArguments()[0]; } else { return
* getDomainClass(clazz.getSuperclass()); } }
*/
#PostConstruct
private void init() {
this.filterComponent.init(this.jpaEntityInformation.getJavaType());
this.expandComponent.init(this.jpaEntityInformation.getJavaType());
}
#Override
public <S extends T> List<S> save(Iterable<S> entities) {
List<S> savedEntities = super.save(entities);
super.flush();
this.entityManager.refresh(savedEntities);
return savedEntities;
}
#Override
public <S extends T> S save(S entity) {
S savedEntity = super.save(entity);
super.flush();
if (!this.jpaEntityInformation.isNew(entity)) {
this.entityManager.refresh(savedEntity);
}
return savedEntity;
}
protected JPQLQuery<T> createQuery(final Predicate predicate, final EntityGraph<?> entityGraph) {
JPQLQuery<?> query = createQuery(predicate);
if (entityGraph != null) {
((AbstractJPAQuery<?, ?>) query).setHint(EntityGraphType.LOAD.getKey(), entityGraph);
}
return query.select(path);
}
protected Page<T> findAll(final Pageable pageable, final Predicate predicate, final EntityGraph<?> entityGraph) {
final JPQLQuery<?> countQuery = createCountQuery(predicate);
JPQLQuery<T> query = querydsl.applyPagination(pageable, createQuery(predicate, entityGraph));
return PageableExecutionUtils.getPage(query.fetch(), pageable, new LongSupplier() {
#Override
public long getAsLong() {
return countQuery.fetchCount();
}
});
}
#Override
public Page<T> findAll(Integer pageNumber, Integer pageSize, BooleanExpression booleanExpression,
String filterExpression, String sortExpression, String expandExpression)
throws InvalidFilterExpressionException, InvalidSortExpressionException,
InvalidExpandExpressionException {
Sort sort = null;
if (sortExpression != null && !sortExpression.isEmpty()) {
sort = this.sortComponent.getSort(sortExpression);
}
Pageable pageable = this.pageComponent.getPage(pageNumber, pageSize, sort);
BooleanExpression filterBooleanExpression = null;
if (filterExpression != null) {
filterBooleanExpression = this.filterComponent.getBooleanExpression(filterExpression);
}
BooleanExpression mergedBooleanExpression = null;
if (booleanExpression != null && filterBooleanExpression != null) {
mergedBooleanExpression = booleanExpression.and(filterBooleanExpression);
} else if (booleanExpression != null && filterBooleanExpression == null) {
mergedBooleanExpression = booleanExpression;
} else if (booleanExpression == null && filterBooleanExpression != null) {
mergedBooleanExpression = filterBooleanExpression;
}
EntityGraph<?> entityGraph = null;
if (expandExpression != null && !expandExpression.isEmpty()) {
entityGraph = this.expandComponent.getEntityGraph(expandExpression);
}
return this.findAll(pageable, mergedBooleanExpression, entityGraph);
}
protected Predicate getPredicate(final BigInteger identifier, final Predicate predicate) {
Class<?> clazz = this.jpaEntityInformation.getJavaType();
String name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, clazz.getSimpleName());
Path<?> rootPath = Expressions.path(this.jpaEntityInformation.getJavaType(), name);
Class<?> idType = this.jpaEntityInformation.getIdType();
String idAttributeName = this.jpaEntityInformation.getIdAttribute().getName();
Path<?> leftPath = Expressions.path(idType, rootPath, idAttributeName);
Expression<?> rightExpression = Expressions.constant(identifier);
BooleanExpression booleanExpression = Expressions.predicate(Ops.EQ, leftPath, rightExpression);
BooleanBuilder booleanBuilder = new BooleanBuilder(booleanExpression);
booleanBuilder.and(predicate);
return booleanBuilder.getValue();
}
protected T findOne(final BigInteger identifier, final BooleanExpression booleanExpression,
final EntityGraph<?> entityGraph) {
Assert.notNull(identifier, "The given id must not be null!");
T object = null;
if (booleanExpression != null) {
Predicate mergedPredicate = getPredicate(identifier, booleanExpression);
JPQLQuery<T> query = createQuery(mergedPredicate, entityGraph);
object = query.fetchOne();
} else {
Map<String, Object> hints = new HashMap<String, Object>();
if (entityGraph != null) {
hints.put("javax.persistence.loadgraph", entityGraph);
}
object = this.entityManager.find(this.jpaEntityInformation.getJavaType(), identifier, hints);
}
return object;
}
#Override
public T findOne(final BigInteger identifier, final BooleanExpression booleanExpression,
final String expandExpression) throws InvalidExpandExpressionException {
EntityGraph<?> entityGraph = null;
if (booleanExpression != null) {
entityGraph = this.expandComponent.getEntityGraph(expandExpression);
}
return this.findOne(identifier, booleanExpression, entityGraph);
}
#Override
public Map<Number, T> findAllRevisions(final BigInteger identifier) {
Assert.notNull(identifier, "The given id must not be null!");
AuditReader auditReader = AuditReaderFactory.get(this.entityManager);
List<Number> revisionList = auditReader.getRevisions(this.jpaEntityInformation.getJavaType(), identifier);
if (revisionList == null || revisionList.isEmpty()) {
return null;
}
Set<Number> revisionSet = new LinkedHashSet<Number>(revisionList);
return auditReader.findRevisions(this.jpaEntityInformation.getJavaType(), revisionSet);
}
#Override
public void delete(Iterable<? extends T> entities) {
super.delete(entities);
super.flush();
}
#Override
public void delete(T entity) {
super.delete(entity);
super.flush();
}
}
public class AbstractCrudService<T extends IdentifiableEntity> implements CrudService<T> {
#Autowired(required=false)
private CrudRepository<T> repository;
#Autowired(required=false)
private NotificationComponent<T> notificationComponent;
private NotificationContext<T> geNotificationContext(String action, List<T> payload) {
DefaultNotificationContext<T> defaultNotificationContext = new DefaultNotificationContext<T>();
/*defaultNotificationContext.setAction(action);
defaultNotificationContext.setObject(this.domainClazz.getSimpleName());
defaultNotificationContext.setInstant(Instant.now());
defaultNotificationContext.setResponsibleId(null);
defaultNotificationContext.setPayload(payload);*/
return defaultNotificationContext;
}
private NotificationContext<T> geNotificationContext(String action, Page<T> payload) {
return geNotificationContext(action, payload.getContent());
}
private NotificationContext<T> geNotificationContext(String action, T payload) {
List<T> payloadList = new ArrayList<T>();
payloadList.add(payload);
return geNotificationContext(action, payloadList);
}
#Override
#Transactional(dontRollbackOn = LongTermRunningException.class)
#TypeTaskCriteria(pre = PreSaveTask.class, post = PostSaveTask.class, referenceGenericType = AbstractCrudService.class)
public List<T> save(List<T> objects)
throws ConcurrentModificationException, UnexpectedException {
List<T> savedObjectList = this.repository.save(objects);
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.SAVE, savedObjectList));
}
return savedObjectList;
}
#Override
#Transactional(dontRollbackOn = LongTermRunningException.class)
#TypeTaskCriteria(pre = PreSaveTask.class, post = PostSaveTask.class, referenceGenericType = AbstractCrudService.class)
public T save(T object) throws ConcurrentModificationException, UnexpectedException {
T savedObject = this.repository.save(object);
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.SAVE, savedObject));
}
return savedObject;
}
#Override
#TypeTaskCriteria(pre = PreRetrieveTask.class, post = PostRetrieveTask.class, referenceGenericType = AbstractCrudService.class)
public Page<T> retrieve(
#P(PAGE_NUMBER) final Integer pageNumber,
#P(PAGE_SIZE) final Integer pageSize,
#P(FILTER_EXPRESSION) final String filterExpression,
#P(SORT_EXPRESSION) final String sortExpression,
#P(EXPAND_EXPRESSION) final String expandExpression,
#P(PARAMETERS) final Map<String, String> parameters) throws InvalidParameterException, UnexpectedException {
DefaultRetrieveTaskContext context = TaskContextHolder.getContext();
BooleanExpression booleanExpression = context.getBooleanExpression();
Page<T> page = null;
try {
page = new Page<T>(this.repository.findAll(pageNumber, pageSize, booleanExpression, filterExpression, sortExpression, expandExpression));
} catch (InvalidFilterExpressionException | InvalidSortExpressionException
| InvalidExpandExpressionException e) {
throw new UnexpectedException(e);
}
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.RETRIEVE, page));
}
return page;
}
#Override
#TypeTaskCriteria(pre = PreRetrieveTask.class, post = PostRetrieveTask.class, referenceGenericType = AbstractCrudService.class)
public T retrieve(BigInteger identifyer, String expandExpression) throws NotFoundException, UnexpectedException {
RetrieveTaskContext context = TaskContextHolder.getContext();
BooleanExpression booleanExpression = context.getBooleanExpression();
T object = null;
try {
object = this.repository.findOne(identifyer, booleanExpression, expandExpression);
} catch (InvalidExpandExpressionException invalidExpandExpressionException) {
throw new UnexpectedException(invalidExpandExpressionException);
}
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.RETRIEVE, object));
}
return object;
}
#Override
#Transactional(dontRollbackOn = LongTermRunningException.class)
#TypeTaskCriteria(pre = PreDeleteTask.class, post = PostDeleteTask.class, referenceGenericType = AbstractCrudService.class)
public void delete(List<T> objects) throws ConcurrentModificationException, UnexpectedException {
this.repository.delete(objects);
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.DELETE, (List<T>) null));
}
}
#Override
#Transactional(dontRollbackOn = LongTermRunningException.class)
#TypeTaskCriteria(pre = PreDeleteTask.class, post = PostDeleteTask.class, referenceGenericType = AbstractCrudService.class)
public void delete(T object) throws ConcurrentModificationException, UnexpectedException {
this.repository.delete(object);
if (this.notificationComponent != null) {
this.notificationComponent.notify(geNotificationContext(NotificationContext.DELETE, (T) null));
}
}
}
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(value = "br.org.ccee", repositoryFactoryBeanClass = CrudRepositoryFactoryBean.class)
#EnableAspectJAutoProxy
public class ServiceConfiguration {
#Bean
//#Scope("request")
public ServiceContext serviceContext() {
DefaultServiceContext defaultServiceContext = new DefaultServiceContext();
defaultServiceContext.setInstant(Instant.now());
defaultServiceContext.setUserId(new BigInteger("33"));
defaultServiceContext.setTenantId(new BigInteger("69"));
return defaultServiceContext;
}
#Bean
public TenantEventListener tenantEventListener() {
return new TenantEventListener();
}
#Bean
public AuditEventListener auditEventListener() {
return new AuditEventListener();
}
#Bean
public EventListenerRegistry eventListenerRegistry(
LocalContainerEntityManagerFactoryBean entityManagerFactory,
TenantEventListener tenantEventListener,
AuditEventListener auditEventListener) {
SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) entityManagerFactory.getNativeEntityManagerFactory();
ServiceRegistryImplementor serviceRegistryImplementor = sessionFactoryImpl.getServiceRegistry();
EventListenerRegistry eventListenerRegistry = serviceRegistryImplementor.getService(EventListenerRegistry.class);
eventListenerRegistry.prependListeners(EventType.PRE_INSERT, auditEventListener);
eventListenerRegistry.prependListeners(EventType.PRE_INSERT, tenantEventListener);
eventListenerRegistry.prependListeners(EventType.PRE_UPDATE, auditEventListener);
return eventListenerRegistry;
}
}
public class DefaultCrudRepository<T extends IdentifiableEntity> extends QueryDslJpaRepository<T, BigInteger>
implements CrudRepository<T> {
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
private JpaEntityInformation<T, BigInteger> jpaEntityInformation;
private EntityManager entityManager;
private EntityPath<T> path;
private PathBuilder<T> builder;
private Querydsl querydsl;
#Autowired
private SortComponent sortComponent;
#Autowired
private PageComponent pageComponent;
#Autowired
private FilterComponent filterComponent;
#Autowired
private ExpandComponent expandComponent;

Spring - NoSuchMethodException when calling a RestService

I have this simple Mapping that should return me a List objects
#RestController
#RequestMapping(value="/api")
public class ServerRESTController {
#Autowired ServerService serverService;
#RequestMapping(value="/server/{idServer}", method = RequestMethod.GET)
public ResponseEntity<Server> getFloorLatUpdate(#PathVariable int idServer){
Server server = serverService.findById(idServer);
return new ResponseEntity<Server>(server, HttpStatus.OK);
}
#RequestMapping(value="/server/list", method = RequestMethod.GET)
public ResponseEntity<List<Server>> listAllServers(){
List<Server> servers = serverService.findAllServers(-1);
return new ResponseEntity<List<Server>>(servers, HttpStatus.OK);
}
}
Server.class is a model
#Entity
#Table(name = "server")
public class Server implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int serverId;
private Piano piano;
private String nomeServer;
private String serverIp;
private String descrizione;
private boolean online;
private Set<Interruttore> interruttori;
private String firmwareVersion;
public Server(){
}
public Server(int serverId, Piano piano, String nomeServer, String serverIp, String descrizione, boolean online,
Set<Interruttore> interruttori, String firmwareVersion){
this.serverId = serverId;
this.piano = piano;
this.nomeServer = nomeServer;
this.descrizione = descrizione;
this.serverIp = serverIp;
this.online = online;
this.interruttori = interruttori;
this.setFirmwareVersion(firmwareVersion);
}
#Id
#Column(name = "id_server", unique = true, nullable = false)
#GeneratedValue(strategy = IDENTITY)
public int getServerId() {
return serverId;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
#ManyToOne
#JoinColumn(name="id_piano")
public Piano getPiano() {
return piano;
}
public void setPiano(Piano piano) {
this.piano = piano;
}
#Column(name="nome_server")
public String getNomeServer() {
return nomeServer;
}
public void setNomeServer(String nomeServer) {
this.nomeServer = nomeServer;
}
#Column(name="server_ip")
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
#Column(name="descrizione")
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
#Column(name="online")
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
#JsonIgnore
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "server")
public Set<Interruttore> getInterruttori() {
return interruttori;
}
public void setInterruttori(Set<Interruttore> interruttori) {
this.interruttori = interruttori;
}
#Column(name = "firmware_version")
public String getFirmwareVersion() {
return firmwareVersion;
}
public void setFirmwareVersion(String firmwareVersion) {
this.firmwareVersion = firmwareVersion;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((descrizione == null) ? 0 : descrizione.hashCode());
result = prime * result + ((nomeServer == null) ? 0 : nomeServer.hashCode());
result = prime * result + (online ? 1231 : 1237);
result = prime * result + ((piano == null) ? 0 : piano.hashCode());
result = prime * result + serverId;
result = prime * result + ((serverIp == null) ? 0 : serverIp.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Server other = (Server) obj;
if (descrizione == null) {
if (other.descrizione != null)
return false;
} else if (!descrizione.equals(other.descrizione))
return false;
if (nomeServer == null) {
if (other.nomeServer != null)
return false;
} else if (!nomeServer.equals(other.nomeServer))
return false;
if (online != other.online)
return false;
if (piano == null) {
if (other.piano != null)
return false;
} else if (!piano.equals(other.piano))
return false;
if (serverId != other.serverId)
return false;
if (serverIp == null) {
if (other.serverIp != null)
return false;
} else if (!serverIp.equals(other.serverIp))
return false;
return true;
}
}
When trying to call for the service i'm getting:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: Method [listAllServers] was discovered in the .class file but cannot be resolved in the class object
cause by
java.lang.NoSuchMethodException: it.besmart.restcontroller.ServerRESTController.listAllServers()
I cannot understand why this happens, I have always used ResponseEntity in this way... maybe it's for the List?
Please post the whole code so we can find out.
This usually comes when the method is invoked at the wrong place or when there is a mismatch in build and runtime environments or when you miss arguments in a constructor and so on.
Also, you may want to check the files in the classpath. There may be a mismatch between compile time and actual runtime environments for some reason. For example, you say that you build it using command line. So, there may be some discrepancy there, no harm in checking.
Finally, you can check for spelling mistakes - I know that sounds strange, but case sensitivity is important.

Spring Security: password don't match with stored one

I have a problem with password hashing. I want to appply sha-256 with salt and 1024 iterations to authenticate my users using Spring Security. But somehow, my password in database dont match those from user input.
Here is my code:
security-context.xml
<beans:bean
id="passwordEncoder"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" >
<beans:constructor-arg value="256" />
<beans:property
name="iterations"
value="1024" />
</beans:bean>
<beans:bean class="org.springframework.security.authentication.dao.ReflectionSaltSource" id="saltSource">
<beans:property name="userPropertyToUse" value="id"/>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userLoginDetails" >
<password-encoder ref="passwordEncoder" >
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>
userLoginDetails
#Transactional(readOnly = true)
public class UserLoginDetails implements UserDetailsService {
private EregDaoFactory daoFactory;
#Autowired
public void setDaoFactory(EregDaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
/**
* Retrieves a user record containing the user's credentials and access.
*/
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
DataAccessException {
Logger logger = Logger.getLogger(getClass());
logger.setLevel(Level.ALL);
int userId = Integer.parseInt(username);
UzytkownikDao dao = daoFactory.getUzytkownikDao();
LoggedUser user = null;
Uzytkownik dbUser = null;
try {
dbUser = (Uzytkownik) dao.findById(Integer.parseInt(username));
List<SimpleGrantedAuthority> grants = new ArrayList<SimpleGrantedAuthority>();
Collection<Object> userNames = new ArrayList<Object>();
if (dbUser.getRola() == 'U') {
grants.add(new SimpleGrantedAuthority("ROLE_STUDENT"));
userNames = daoFactory.getUczenDao().getNameAndLastName(userId);
} else if (dbUser.getRola() == 'N') {
grants.add(new SimpleGrantedAuthority("ROLE_TEACHER"));
userNames = daoFactory.getNauczycielDao().getNameAndLastName(userId);
} else if (dbUser.getRola() == 'O') {
grants.add(new SimpleGrantedAuthority("ROLE_PARENT"));
userNames = daoFactory.getOpiekunDao().getNameAndLastName(userId);
}
grants.add(new SimpleGrantedAuthority("ROLE_USER"));
Object[] names = userNames.toArray();
user =
new LoggedUser(username, dbUser.getHaslo(), true, true, true, true, grants,
(String) names[0], (String) names[1], dbUser.getRola());
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
throw new UsernameNotFoundException("Error in retrieving user");
}
return user;
}
}
LoggedUser
package ereg.security.userdetails;
public class LoggedUser extends User {
private static final long serialVersionUID = 1L;
private final String id;
private final String imie;
private final String nazwisko;
private final char rola;
private Date lastSuccessfulLogin;
private String lastKnowIpAddress;
public LoggedUser(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, String name, String lastName, char rola) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
authorities);
this.imie = name;
this.nazwisko = lastName;
this.rola = rola;
this.id = username;
}
public String getId() {
return id;
}
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
public char getRola() {
return rola;
}
public Date getLastSuccessfulLogin() {
return lastSuccessfulLogin;
}
public String getFormattedDate() {
if (lastSuccessfulLogin != null) {
return new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss").format(lastSuccessfulLogin);
} else
return null;
}
public String getLastKnowIpAddress() {
return lastKnowIpAddress;
}
public void setLastSuccessfulLogin(Date lastSuccessfulLogin) {
this.lastSuccessfulLogin = lastSuccessfulLogin;
}
public void setLastKnowIpAddress(String lastKnowIpAddress) {
this.lastKnowIpAddress = lastKnowIpAddress;
}
}
And here is the program that hashes passwords:
EncryptAllUsersPasswords
private void encryptPasswords() throws Exception {
OneWayEncryptor encryptor = OneWayEncryptor.getInstance();
appContext =
new FileSystemXmlApplicationContext(
"C:/EclipseWorkSpace/myereg/WebContent/WEB-INF/applicationContext.xml");
ds = (DataSource) appContext.getBean("dataSource");
JdbcTemplate jdbc = new JdbcTemplate(ds);
BigDecimal userId = null;
String password = "";
String encrypted = "";
Map<?, ?> row = new HashMap<Object, Object>();
for (Iterator<?> it = jdbc.queryForList("SELECT id, haslo FROM UZYTKOWNIK").iterator(); it.hasNext();) {
row = (Map<?, ?>) it.next();
userId = (BigDecimal) row.get("ID");
password = (String) row.get("HASLO");
encrypted = encryptor.encrypt(password, userId.toString());
System.out.println(userId.toString());
jdbc.execute("UPDATE UZYTKOWNIK SET haslo = '" + encrypted + "' WHERE id = " + userId);
}
}
public static void main(String[] args) {
EncryptAllUserPasswords encrypt = new EncryptAllUserPasswords();
try {
encrypt.encryptPasswords();
} catch (Exception e) {
e.printStackTrace();
}
}
OneWayEncryptor
public final class OneWayEncryptor {
private static final OneWayEncryptor INSTANCE = new OneWayEncryptor();
private static final int ITERATIONS = 1024;
private static final String ALGORITHM = "SHA-256";
private OneWayEncryptor() {
}
public static OneWayEncryptor getInstance() {
return INSTANCE;
}
public String encrypt(String plaintext, String salt) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
messageDigest.reset();
messageDigest.update(salt.getBytes());
byte[] btPass = messageDigest.digest(plaintext.getBytes("UTF-8"));
for (int i = 0; i < ITERATIONS; i++) {
messageDigest.reset();
btPass = messageDigest.digest(btPass);
}
String encodedPassword = byteToBase64(btPass);
return encodedPassword;
}
private String byteToBase64(byte[] bt) throws UnsupportedEncodingException {
return new String(Base64.encodeBase64(bt));
}
}
I believe that problem lies in the last one... Please help
actually, this worked:
public String encrypt(String plaintext, String salt) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
String pass = plaintext + "{" + salt + "}";
MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
messageDigest.reset();
byte[] btPass = messageDigest.digest(pass.getBytes("UTF-8"));
for (int i = 0; i < ITERATIONS - 1; i++) {
messageDigest.reset();
btPass = messageDigest.digest(btPass);
}
String hashedPass = new BigInteger(1, btPass).toString(16);
if (hashedPass.length() < 32) {
hashedPass = "0" + hashedPass;
}
return hashedPass;
}
can someone tell my why? I mean why when i tried using update(salt) method it didint and when i switch to concate string it did. and i dont mind part with "{salt}", cause that only allows me to generate exactly the same hash as spring does. the thing is that before it generated wrong hash even with given salt. I checked it with sha256 generators. Can someone tell me why it started working after string concatating?

Resources