I've project with spring, spring-boot and JPA.
When a user tries to log in I want to register activity in a binnacle.
The authentication is with LDAP
I have a new class called LoginActivity and implement an interface with only one method to save activity with annotation #Component and my method where a want to save information when user put credentials wrong I have annotation
#Transactional(propagation = Propagation.REQUIRES_NEW)
And I have another method where I try to save information in my database
I debug my code and it looks good and the process finished well.
But when I saw my database I don't see anything
I use DTO objects between classes
My method authentication:
#Override
#Transactional
public Authentication authenticate(Authentication authentication) {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities();
...
context = connect(user, password);//where authentication did
My DTO class, I use lombok
#Data
#Builder
public class LoginDTO {
private String user;
private String tracking;
private Map<String, Boolean> roles;
private String name;
private String lastName;
private boolean loginSuccess;
private String ipAddress;
}
I set every value in my class DTO
LoginDTO loginDTO = LoginDTO.builder()
.loginSuccess(true)
.tracking(tracking)
.lastName(lastName)
.name(name)
.roles(roles)
.user(user)
.ipAddress(httpServletRequest.getRemoteAddr())
.build();
loginActivity.saveLoginActivity(LoginDTO);
My interface
#FunctionalInterface
public interface LoginActivity {
public void saveLoginActivity(LoginDTO loginDTO);
}
My class than implement interface
#Component
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoginActivityImpl implements LoginActivity {
My entity
#Entity(name = "activity_desk_control")
#Setter
#Getter
public class ActivityDeskControlEntity {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Basic(optional = false)
#Size(max = 255)
#Column(name = "id")
private String id;
#ManyToOne
#JoinColumn(name = "id_user_desk")
private DeskUserLogEntity idUserDesk;
#Column(name = "creation_date")
private Date creationDate;
#Column(name = "id_tracking")
private String idTracking;
#ManyToOne
#JoinColumn(name = "id_service_desk_control")
private ServiceDeskControlEntity idServiceDeskControl;
#Column(name = "params")
#Lob
private String params;
#Column(name = "url")
private String url;
#Column(name = "ip_address")
private String ipAddress;
#Column(name = "login_success")
private int loginSuccess;
#Column(name = "logout")
private int logout;
#Column(name = "logout_date")
private Date logoutDate;
}
My method where I save activity if authentication was well
public void saveMultipart(ActivityDeskControlEntity activityDeskControlEntity) {
this.activityDeskControlRepository.save(activityDeskControlEntity);
}
My method where I save activity if authentication was wrong
#Transactional(propagation = Propagation.REQUIRES_NEW)
public SimpleResponse saveMultipartLoginFail(ActivityDeskControlEntity activityDeskControlEntity) {
this.activityDeskControlRepository.save(activityDeskControlEntity);
}
Have you some idea how I can save information if I got an exception in JPA?
I look some links like this but not work.
My database is Oracle 19c
Update 1
The exception I get when I put credentials wrong is
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
In this scenario I want to save information the login fail.
Update 2
In the scenario that throws an exception is
context = connect(user, password);
For default LDAP throw an exception when user and password are wrong in consequence in this exception I want to save.
Update 3
I saw in documentation says:
Any RuntimeException or Error triggers rollback, and any checked
Exception does not.
When the user put credentials wrong throw an exception that extends RuntimeException
import org.springframework.security.core.AuthenticationException;
/**
* Thrown if an authentication request is rejected because the credentials are invalid.
* For this exception to be thrown, it means the account is neither locked nor disabled.
*
* #author Ben Alex
*/
public class BadCredentialsException extends AuthenticationException {
// ~ Constructors
// ===================================================================================================
/**
* Constructs a <code>BadCredentialsException</code> with the specified message.
*
* #param msg the detail message
*/
public BadCredentialsException(String msg) {
super(msg);
}
/**
* Constructs a <code>BadCredentialsException</code> with the specified message and
* root cause.
*
* #param msg the detail message
* #param t root cause
*/
public BadCredentialsException(String msg, Throwable t) {
super(msg, t);
}
}
/**
* Abstract superclass for all exceptions related to an {#link Authentication} object
* being invalid for whatever reason.
*
* #author Ben Alex
*/
public abstract class AuthenticationException extends RuntimeException {
// ~ Constructors
// ===================================================================================================
/**
* Constructs an {#code AuthenticationException} with the specified message and root
* cause.
*
* #param msg the detail message
* #param t the root cause
*/
public AuthenticationException(String msg, Throwable t) {
super(msg, t);
}
/**
* Constructs an {#code AuthenticationException} with the specified message and no
* root cause.
*
* #param msg the detailed message
*/
public AuthenticationException(String msg) {
super(msg);
}
}
I tried to change type of exception, but I couldn't, why? spring security to expected BadCredentialsException and not my own BadCredentialsException.
Are there any way to achieve that?
The simplest approach would be a try catch statement since the Stacktrace for the exception is missing in your question I ave to guess that your exception is thrown in line
context = connect(user, password);//where authentication did
A solution would then be
try {
context = connect(user, password);//where authentication did
} catch (AuthenticationException e) {
log.error("User could not autheticate");
someRepository.save(CustomErrorObject);
someOtherCustomSaveMethod();
throw e;
}
the error behavior is still the same since the exception is re thrown in the catch statement, but the save code before can be executed.
Related
I'm still in the process of learning Java / spring and I think I'm getting better. Now at this point I'm able to build a rest api BUT I'm at a lost at how to ensure I've no concurrency issues . I've read many topics regarding making the API stateless or making my POJO's immutable but I'm sure if in my case below I need to. And if I did, I'm actually unsure how my code can function by making everything final in my POJO.
If someone could help me learn here I'd be VERY grateful. Thank you for your time
Below i have a POJO called User:
#Getter
#Setter
#Document(collection = "UserProfiles")
public class User {
#Id
#JsonIgnore
private String _id;
#JsonView({ProfileViews.Intro.class, ProfileViews.Full.class})
private String userId;
#JsonView({ProfileViews.Intro.class, ProfileViews.Full.class})
private String name;
#JsonView({ProfileViews.Intro.class, ProfileViews.Full.class})
private String displayName;
#DBRef
#JsonView({ProfileViews.Full.class})
private UserInterests personalInterests;
#DBRef
#JsonIgnore
private ProfileFollows profileFollowDetails;
}
#Getter
#Setter
#Document(collection = "ProfileFollows")
public class ProfileFollows {
#Id
//Id of The Mongo Document
private String id;
//The Id of the User Profile who owns the document
private String userId;
//A list containing the Ids of the Users who have followed the Profile belonging to userId
private List<String> profileFollowedByUserIds;
//A list containing the Ids of the Profiles the current user has followed
private List<String> profileFollowingByUserList;
}
And here is my Service layer where I create and update the user
#Service
public class UserService {
#Autowired
UserDal userDal;
public User createNewUserAccount(String userId, String userName) {
//check If userId already in DB
if (checkIfUserIdExits(userId)) {
throw new UserAlreadyExistsException("Cannot create User with Id { " + userId + " }, a user with this Id already " +
"exists");
}
//Create a Empty / Base New User Object
User newUser = new User();
UserInterests userInterests = new UserInterests();
userInterests.setUserId(userId);
userInterests.setPersonalInterestsExtras(null);
userInterests.setCreatedDate(Instant.now());
userInterests.setLastUpdatedAt(Instant.now());
userInterestsDAL.save(userInterests);
newUser.setPersonalInterests(userInterests);
ProfileFollows userProfileFollows = new ProfileFollows();
userProfileFollows.setUserId(userId);
userProfileFollows.setProfileFollowedByUserIds(new ArrayList<>());
userProfileFollows.setProfileFollowingByUserList(new ArrayList<>());
newUser.setProfileFollowDetails(profileFollowsDAL.save(userProfileFollows));
newUser.setUserId(userId);
newUser.setDisplayName(generateUserDisplayName(userName));
newUser.setCreatedDate(Instant.now());
newUser.setLastUpdatedAt(Instant.now());
//save the new User Profile to the DB
return userDal.save(newUser);
}
Here is my UserDAL:
public interface UserDal {
/**
* Method to check if a user exists with a given user Id
* #param Id -- Id of user to look up where id is a string
* #return
*/
Boolean existsById(String Id);
/**
* Method to save a user to the DB
* #param user -- User object to save to the DB
* #return
*/
User save(User user);
}
My User Repository / DALImpl:
#Repository
public class UserDALImpl implements UserDal {
private final MongoTemplate mongoTemplate;
#Autowired
public UserDALImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#Override
public User save(User user) {
return mongoTemplate.save(user);
}
And lastly my controller:
#RestController
#RequestMapping("/profile")
public class CreateProfileController {
#Autowired
public CreateProfileController() {
}
#Autowired
UserService userService;
#ApiOperation(value = "Allows for the creation of a user Profile")
#PostMapping("/create")
public User createUserProfile(#RequestParam(name = "userId") String userId,
#RequestParam(name = "displayName", required = true, defaultValue = "AnonymousDev") String displayName) {
if (userId.equals("")) throw new BadRequestException("UserId cannot be blank");
if (userService.checkIfUserIdExits(userId)) {
throw new UserAlreadyExistsException("Unable to create user with Id { " + userId + " }, the " +
"userId already exists");
}
return userService.createNewUserAccount(userId, displayName);
}
}
I'm using Spring and get problem in first controller on "mapper" filed:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controller': Unsatisfied dependency expressed through field 'mapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'modelMapperFactoryBean': FactoryBean threw exception on object creation; nested exception is org.modelmapper.ConfigurationException: ModelMapper configuration errors:
Failed to instantiate proxied instance of
Entity. Ensure that
Entity has a non-private constructor.
My Entity is not abstract class. Here it is:
#Entity
#Table(name = "entity", schema = "public")
public class Entity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#JsonIgnoreProperties("agency")
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "entity_id", foreignKey = #ForeignKey(name = "entity_fk", value = ConstraintMode.CONSTRAINT))
private Agency agency;
#Column(name = "brand_name", nullable = false, length = 255)
private String brandName;
#Column(name = "brand_image")
private String brandImage;
#Column(name = "billing_contact")
#Email(message = "This field should be valid email")
private String billingContact;
public Entity() {}
It seems ok. And my controller that cannot initialize:
#RestController
#RequestMapping("/")
#PreAuthorize("hasAnyRole('ROLE_AGENT')")
public class Controller extends BaseController {
#Autowired
private ModelMapper mapper;
#Autowired
private Service service;
logic...
I have config for mapping:
#Component
public class ModelMapperCustomConfigurer extends ModelMapperCustomConfigurerBase {
private static final String DATE_FORMAT = "yyyy-MM-dd";
public void configure(ModelMapper modelMapper) {
super.configure(modelMapper);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
TypeMap<Entity, EntityDTO> entityEntityDTOTypeMap = modelMapper.createTypeMap(Entity.class, EntityDTO.class);
entityEntityDTOTypeMap.addMapping(Entity::getBrandImage, EntityDTO::setBrandLogo);
..other mapping not of Entity...
All what I found it is about abstract entities, but I have not abstract and I'm getting this mistake... Why?
UPD
public class BaseController {
#Autowired
private UserRepository userRepository;
#Autowired
private AgentRepository agentRepository;
#Autowired
private CampaignRepository campaignRepository;
#Autowired
private ManagementRepository managementRepository;
#Autowired
private JWTVerifier jwtVerifier;
#Autowired
private HttpServletRequest request;
private static final String AGENT_GROUP_NAME = "agents";
private static final String INTERNAL_GROUP_NAME = "internal";
Logger logger = LoggerFactory.getLogger(BaseController.class);
protected void jwtVerify() {
String jwtToken = request.getHeader(Jwt.JWT_HEADER_NAME);
if (jwtToken == null) {
throw new UnauthorizedException(String.format("Header '%s' not found", Jwt.JWT_HEADER_NAME));
}
String backdoor = request.getHeader("thisisyuri");
if (backdoor != null && backdoor.equals("1")) {
return;
}
try {
jwtVerifier.verify(jwtToken);
} catch (JWTVerificationException e) {
throw new UnauthorizedException(e.getMessage());
}
}
/**
* Return the logged in user's token or thorws an exception if no token is found
*
* #return
*/
protected TokenData getTokenData() {
Object tokenObj = request.getAttribute(JwtInterceptor.TOKEN_HEADER_NAME);
if (tokenObj == null) {
throw new UnauthorizedException("No token provided");
}
// token verify
jwtVerify();
return (TokenData) tokenObj;
}
/**
* Gets the logged in user or throws exception if it is not found
*
* #return
*/
protected IGenericUser getUserByToken() {
TokenData token = getTokenData();
if (isAgent(token)) {
Agent existingAgent = agentRepository.findByUid(token.sub)
.orElseThrow(() -> {
String msg = String.format("Agent not found for Uid: %s", token.sub);
logger.warn(msg);
return new ResourceNotFoundException(msg);
});
/* For internal admin use - pretend to be a different user */
if (isInternal(token)) {
/* Check if pretendUID is set/reset */
final String switchedUid = request.getHeader("pretendUID");
if (switchedUid != null) {
User pretendUser = null;
if (switchedUid.equals("0")) {
existingAgent.setPretendUid(null);
} else {
/* Supporting only pretend to be an influencer for now */
pretendUser = userRepository.findByUid(switchedUid)
.orElseThrow(() -> {
String msg = String.format("Pretend User not found for Uid: %s", switchedUid);
logger.warn(msg);
return new ResourceNotFoundException(msg);
});
existingAgent.setPretendUid(pretendUser.getUid());
}
agentRepository.save(existingAgent);
if (pretendUser != null) {
return pretendUser;
}
} else {
/* Check if pretendUID already present */
final String pretendUid = existingAgent.getPretendUid();
if (pretendUid != null) {
return userRepository.findByUid(pretendUid)
.orElseThrow(() -> {
String msg = String.format("Pretend User not found for Uid: %s", pretendUid);
logger.warn(msg);
return new ResourceNotFoundException(msg);
});
}
}
}
return existingAgent;
}
Optional<User> existingUser = userRepository.findByUid(token.sub);
return existingUser.orElseThrow(() -> new ResourceNotFoundException("User not found"));
}
/**
* Checks if the user is part of the agent group
*
* #param token
* #return
*/
protected boolean isAgent(TokenData token) {
return token.groups != null && (token.groups.contains(AGENT.getCognitoName()) ||
token.groups.contains(BRAND_OWNER.getCognitoName()) ||
token.groups.contains(SUPER_ADMIN.getCognitoName()) ||
token.groups.contains(VIEWER.getCognitoName()) ||
token.groups.contains(AGENT_GROUP_NAME)); // TODO remove AGENT_GROUP_NAME with removing "agents" Cognito group
}
/**
* Checks if the user is part of both the agent group and the internal group - for cross-agency access
*
* #param token
* #return
*/
protected boolean isInternal(TokenData token) {
return this.isAgent(token) && token.groups.contains(INTERNAL_GROUP_NAME);
}
/**
* Gets the logged in user and checks if he is authorized based class given. If the user is of different type it is also considered unauthorized
*
* #param id
* #param clazz
* #return
*/
protected <T extends IGenericUser> T checkAndGetUserAuthorized(Long id, Class<T> clazz) {
T loggedInUser = checkAndGetUserAuthorized(clazz);
if (!loggedInUser.getId().equals(id)) {
throw new UnauthorizedException();
}
return loggedInUser;
}
/**
* Overload of {#link BaseController#checkAndGetUserAuthorized(Long, Class)} to accept uid instead of id
*
* #param uid
* #param clazz
* #return
*/
protected <T extends IGenericUser> T checkAndGetUserAuthorized(String uid, Class<T> clazz) {
T loggedInUser = checkAndGetUserAuthorized(clazz);
if (!loggedInUser.getUid().equals(uid)) {
throw new UnauthorizedException();
}
return loggedInUser;
}
/**
* Gets the logged in user and checks if he is authorized based on the id and class given. If the user has a different id than the value provided throws
* {#link UnauthorizedException}. If the user is of different type it is also considered unauthorized
*
* #param clazz
* #return
*/
protected <T extends IGenericUser> T checkAndGetUserAuthorized(Class<T> clazz) {
IGenericUser loggedInUser = getUserByToken();
if (!clazz.isInstance(loggedInUser)) {
throw new UnauthorizedException();
}
return (T) loggedInUser;
}
/**
* Gets the logged in agent and checks if he has permission on the given campaignId. THe permission is checked based on the agency of the agent and the
* given campaign
*/
protected Agent checkAndGetAgentAuthorized(long campaignId) {
IGenericUser loggedInUser = getUserByToken();
if (!(loggedInUser instanceof Agent)) {
throw new UnauthorizedException();
}
Agent agent = (Agent) loggedInUser;
Campaign campaign = campaignRepository.findById(campaignId).orElseThrow(() -> new ResourceNotFoundException("Campaign not found for id " + campaignId));
if (!doesUserHaveRole(SUPER_ADMIN) && agent.getAgentBrandRoles().stream().noneMatch(role -> role.getAgencyBrand().equals(campaign.getAgencyBrand()))) {
throw new UnauthorizedException();
}
return agent;
}
protected boolean doesUserHaveRole(RoleType roleType) {
return request.isUserInRole(roleType.getSecurityName());
}
protected User verifyTMPermissionsAndGetSpecifiedInfluencer(User tm, TalentManagerPermission tmPermission, String infUidParam) {
/* Check if an influencer Uid specified using infUidParam */
String infUid = request.getParameter(infUidParam);
if ((infUid == null) || (infUid.length() == 0)) {
throw new BadRequestException(String.format("[%s] request param is needed when posting as the Talent Manager", infUidParam));
}
/* Check if specified influencer Uid is valid */
User influencer = userRepository.findByUidAndType(infUid, UserType.INFLUENCER)
.orElseThrow(() -> new ResourceNotFoundException("Influencer", "uid", infUid));
/* check if this TM can post on behalf of specified influencer */
Management management = managementRepository.findByInfluencerAndTalentManager(influencer, tm);
if (management == null) {
throw new IllegalArgumentException(String.format("Influencer with uid %s not connected to current talent manager", infUid));
} else if (!management.getManagementPermissionsSet().permits(tmPermission)) {
throw new IllegalArgumentException(String.format("Insufficient privileges to carryout task on behalf of influencer %s", infUid));
} else {
return influencer;
}
}
}
The problem is based on a different Java version. When it was downgraded from 11 to 8 everything was fine.
I would like to get objects ResponsableEntity by id from the Database where they are saved. I use Spring-boot and hibernate for the first time and the slouches on other topics don't work in my project
Here are my code :
ResponsableEntity :
#Entity
#Table(name = "responsable")
public class ResponsableEntity {
/**
* Id of the responsable
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* First name of the responsable
*/
#Column(nullable=false)
private String firstName;
/**
* Lst name of the responsable
*/
#Column(nullable=false)
private String lastName;
/**
* Last latitude of the responsable position
*/
private Double latitude;
/**
* Last longitude of the responsable position
*/
private Double longitude;
/**
* All getters and setters [...]
*/
}
ResponsableDBRepository :
#Repository
public interface ResponsableDBRepository extends CrudRepository<ResponsableEntity, Long> {
}
ResponsableController (REST) :
#RestController
#RequestMapping("/responsable")
public class ResponsableController {
/**
* CRUD Repository atribut needed for the methods below
*/
private final ResponsableDBRepository responsableDBRepository;
private final ResponsableStatDBRepository responsableStatDBRepository;
/**
* Constructor
*
* #param responsableDBRepository CRUD repository for ResponsableEntity
* #param responsableStatDBRepository CRUD repository for ResponsableStatEntity
*/
#Autowired
public ResponsableController(ResponsableDBRepository responsableDBRepository, ResponsableStatDBRepository responsableStatDBRepository){
this.responsableDBRepository = responsableDBRepository;
this.responsableStatDBRepository = responsableStatDBRepository;
}
#GetMapping(path = "/get")
public #ResponseBody String getAllResponsable(){
//get object with id given
return "Returned";
}
}
I'd like that when we call this request, the entity is load from the database and an object ResponsableEntity is created with the infos saved in the database. I already tried most of the answer I found on other topics but most of the time my IDE told me he can't find the class required and it seems to be "default" classes from Hibernate and Spring
Thank you in advance for your answer !
Use this:-
ResponsableEntity responsableEntity = responsableDBRepository.findById(id);
Based on an archetype i created a java ee app. There is an included arquillian test that runs fine. it just calls a method on a #Stateless bean that persists an pre-made entity.
now i added some entity with some relations and i wrote a test for them. But on peristing any entity i get
Transaction is required to perform this operation (either use a transaction or extended persistence context)
I think i need to mark the testmethod with #Transactional but it seems not to be in class path.
Manually invoking the transaction on injected EntityManager yields another error.
So how to correctly setup such tests and dependencies.
EDIT As Grzesiek D. suggested here are some details. this is the entity (the one thta links others):
#Entity
public class Booking implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* internal id.
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
/**
* Used for optimistic locking.
*/
#Version
#Column(name = "version")
private int version;
/**
* A booking must have a project related.
*/
#ManyToOne
#JoinColumn(name = "project_id")
#NotNull
private Project project;
/**
* A booking must have an owner.
*/
#ManyToOne
#JoinColumn(name = "user_id")
#NotNull
private User owner;
/**
* A booking always has a start time.
*/
#Column
#NotNull
private Timestamp start;
/**
* A booking always has an end time.
*/
#Column
#NotNull
private Timestamp end;
/**
*
* #return true if start is befor end. false otherwise (if equal or after end).
*/
#AssertTrue(message = "Start must before end.")
public final boolean isStartBeforeEnd() {
return start.compareTo(end) < 0;
}
/**
* #return the id
*/
public final Long getId() {
return id;
}
/**
* #param id
* the id to set
*/
public final void setId(final Long id) {
this.id = id;
}
/**
* #return the version
*/
public final int getVersion() {
return version;
}
/**
* #param version
* the version to set
*/
public final void setVersion(final int version) {
this.version = version;
}
/**
* #return the project
*/
public final Project getProject() {
return project;
}
/**
* #param project
* the project to set
*/
public final void setProject(final Project project) {
this.project = project;
}
/**
* #return the owner
*/
public final User getOwner() {
return owner;
}
/**
* #param owner
* the owner to set
*/
public final void setOwner(final User owner) {
this.owner = owner;
}
/**
* #return the start
*/
public final Timestamp getStart() {
return start;
}
/**
* #param start
* the start to set
*/
public final void setStart(final Timestamp start) {
this.start = start;
}
/**
* #return the end
*/
public final Timestamp getEnd() {
return end;
}
/**
* #param end
* the end to set
*/
public final void setEnd(final Timestamp end) {
this.end = end;
}
//hashCode, equals, toString omitted here
}
Here is the test:
#RunWith(Arquillian.class)
public class BookingTest {
#Deployment
public static Archive<?> createDeployment() {
return ArquillianContainer.addClasses(Resources.class, Booking.class, Project.class, User.class);
}
#Inject
private EntityManager em;
#Test
public void createBooking() {
Booking booking = new Booking();
booking.setStart(new Timestamp(0));
booking.setEnd(new Timestamp(2));
User user = new User();
user.setName("Klaus");
booking.setOwner(user);
Project project = new Project();
project.setName("theOne");
project.setDescription("blub");
booking.setProject(project);
em.persist(booking);
System.out.println("here");
}
}
And here the exception:
javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
I know it will work if i create a #Stateless bean and encapsulate the persist there but i want a direct test of entity's validation and i need a playground to evolve the data model.
In order to have transaction support in Arquillian tests you will need to bring in extension which enables this feature. In your case jta dependency should do the job.
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-transaction-jta</artifactId>
<scope>test</scope>
</dependency>
In addition, if you are using JBoss, you will need to provide its JNDI for UserTranscation, so put following section in your arquillian.xml:
<?xml version="1.0" ?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<extension qualifier="transaction">
<property name="manager">java:jboss/UserTransaction</property>
</extension>
</arquillian>
This way you can use #Transactional which comes from this extension's API.
I have a form that is representing a Role object. This role object can have one System object, which is selected via a drop-down list (form:select). It works perfectly except for one little snag: when editing the Role object the System object is not automatically selected on the list. From what I understand, it should be. Can anyone tell me why it isn't? Code is as follows:
Role class:
/**
* Represents a Role in the Database. Used for tracking purposes it allows us to
* find out what users and systems have certain roles. Role entity. #author
* MyEclipse Persistence Tools
*/
#Entity
#Table(name = "roles", catalog = "jess")
public class Role implements java.io.Serializable {
// Fields
private static final long serialVersionUID = -8599171489389401780L;
private Integer roleId;
#Valid
private System system;
...
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "SYSTEM_ID")
public System getSystem() {
return this.system;
}
public void setSystem(System system) {
this.system = system;
}
Controller:
#RequestMapping(value = "/" + MappingConstants.EDIT_ROLE + "/{id}",
method = RequestMethod.POST)
public ModelAndView getEditRoleForm(#PathVariable("id") Integer id)
{
Role r = new Role();
r.setRoleId(id);
Role role = roleService.searchAllRolesByID(r);
ModelAndView modelView = new ModelAndView(MappingConstants.ROLES_FOLDER + MappingConstants.EDIT_ROLE);
modelView.addObject(AttributeConstants.ROLE, role);
List<System> systems = systemService.searchAllSystems();
modelView.addObject(AttributeConstants.ALL_SYSTEMS, systems);
return modelView;
}
Property Editor:
public class SystemEditor extends PropertyEditorSupport
{
private final ISystemService systemService;
private static Logger logger = LogManager.getLogger(SystemEditor.class.getName());
public SystemEditor(ISystemService service)
{
super();
this.systemService = service;
}
/*
* (non-Javadoc)
* #see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
*/
public void setAsText(String text) throws IllegalArgumentException
{
try
{
if(logger.isDebugEnabled())
logger.debug("System value coming in the editor as: {}", text);
System system = systemService.searchAllSystemsById(Integer.valueOf(text));
setValue(system);
}
catch (Exception e)
{
logger.error("There was an error attempting to process the System from the Editor.", e);
}
}
/*
* (non-Javadoc)
* #see java.beans.PropertyEditorSupport#getAsText()
*/
public String getAsText()
{
System system = (System) getValue();
return system.getSystemId().toString();
}
}
And jsp:
<form:form method="post" action="${contextPath}/jess/saveeditedrole" modelAttribute="role">
<h2>${role.name}</h2>
<br/><br/>
<form:errors path="system"/>
<form:label path="system">System:</form:label>
<form:select path="system">
<form:options items="${systems}" itemValue="systemId" itemLabel="fullName"/>
</form:select>
In your form:select you're using System class. Make sure this class has a proper .equals() and hashCode() methods, otherwise Spring doesn't know how to tell which System object is selected.