I have two questions regarding two annotations:
1) Why does the "faceContext" has to be injected from Resources class? Instead, MemberController can directly use "FacesContext.getCurrentInstance()" in register() method to obatin a FacesContext object? It seems much simpler to do that.
2) Can #Model be replaced by #Singleton? Or even #ApplicationScoped?
Thanks.
MemberController.java
#Model
public class MemberController {
#Inject
private FacesContext facesContext;
#Inject
private MemberRegistration memberRegistration;
#Produces
#Named
private Member newMember;
#PostConstruct
public void initNewMember() {
newMember = new Member();
}
public void register() throws Exception {
try {
memberRegistration.register(newMember);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registered!", "Registration successful");
facesContext.addMessage(null, m);
initNewMember();
} catch (Exception e) {
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful");
facesContext.addMessage(null, m);
}
}
}
Resources.java
public class Resources {
// use #SuppressWarnings to tell IDE to ignore warnings about field not being referenced directly
#SuppressWarnings("unused")
#Produces
#PersistenceContext
private EntityManager em;
#Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
#Produces
#RequestScoped
public FacesContext produceFacesContext() {
return FacesContext.getCurrentInstance();
}
}
injecting the FacesContext istead of getting it using the static factory method has the advantage that you will only once have to care about how to get the current context, when implementing the producer method or field. Each time you need the context you can simply inject it and it is fully transparent to you where it comes from. This might also have some benefits when anything changes in how to get the context, ...
The answer to the second question depends on your requirements. Since #Model is simply a stereotype for #RequestScoped and #Named, you cannot directly replace it with #Singleton or #ApplicationScoped since these both annotations adwise the container to create a single object for all requests. Nevertheless, if this meets your requirements better than having a different object for each request, you are free to change it ;)
Related
I need to make validations on my custom ConstraintValidator that uses an #Inject needed for some validations, it's like this example from quarkus https://quarkus.io/guides/validation
#ApplicationScoped
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, String> {
#Inject
MyService service;
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return service.validate(value);
}
}
When i run the application I see that is made the right validation, but i'm trying to make unit test using mockito i can't mock the object is always null on the default using the Default Bean validation.
On the example from quarkus is unit test only for integration.
this is my implementation
#ApplicationScoped
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, String> {
#Inject
BookService service;
#ConfigProperty(name = "my.property")
int myLimit;
public MyConstraintValidator(BookService service) {
this.service = service;
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
System.out.println("myLimit property: " + myLimit);
int limit = Integer.parseInt(value);
if (limit < myLimit) {
return service.validate(value);
} else {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(NAME_EMPTY).addConstraintViolation();
return false;
}
}
}
Unit test for testing the custom Validator
#Test
void testAmountValidationWithContext() {
BookRequest bookRequest = new BookRequest();
bookRequest.setTitle("my title");
bookRequest.setAuthor("my Author");
bookRequest.setPages(2L);
bookRequest.setAmount("11");
//when:
myConstraintValidator = new MyConstraintValidator(service);
Mockito.when(service.validate(anyString())).thenReturn(true);
//then:
Set<ConstraintViolation<BookRequest>> violations = validator.validate(bookRequest);
// verify that the context is called with the correct argument
Mockito.verify(context).buildConstraintViolationWithTemplate(NAME_EMPTY);
}
The unit test to test the default #NoBlank.
#Test
void testBeanValidationWithInvalidAmount() {
BookRequest bookRequest = new BookRequest();
bookRequest.setTitle("my title");
bookRequest.setAuthor("my Author");
bookRequest.setPages(2L);
bookRequest.setAmount("AA");
//when:
Set<ConstraintViolation<BookRequest>> violations = validator.validate(bookRequest);
//then:
assertEquals(1, violations.size());
assertEquals(NOT_EMPTY, violations.stream().findFirst().get().getMessage());
}
The first unit test works weel, i can mock the object and test the result.
The problem is on my second test, when i try to test the other validations #NotNull, #Pattern. On this test the method isValid() is also invoked and here it's my problem because the #ConfigProperty and the #Inject are always null, and i can't mocked them.
I already saw several examples over internet but doesn't work and are almost for spring but i need to make the custom validation on quarkus.
How can i implement the custom ConstraintValidator unit test using quarkus?
Does any one have any example with this working?
Changing your code from field injection to constructor injection will make unit testing much easier.
#ApplicationScoped
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, String> {
private final MyService service;
private final int myLimit;
public MyConstraintValidator(MyService service, #ConfigProperty(name = "my.property") int myLimit) {
this.service = service;
this.myLimit = myLimit;
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
if (value == null) {
return true;
}
return service.validate(value);
}
}
Updated description with my implementations.
but resuming the issue.
when i have the default annotations with my custom validator i can't mock the objects using the
Set<ConstraintViolation<BookRequest>> violations = validator.validate(bookRequest);
I have a Spring MVC application where I'm exposing an endpoint, and a small library where I wrote some common functionality.
I have an utility class like this:
class SecurityUtil {
public static Principal getPrincipal(){
return SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
}
}
And from the Controller I'm doing something like:
class MyController {
public ResponseEntity<Void> myEndpoint(){
// do something
Principal principal = SecurityUtil.getPrincipal();
// use the principal information for some audit processes
}
}
In this case the Principal is null, but if replace my code like this:
class MyController {
public ResponseEntity<Void> myEndpoint(){
// do something
Principal principal = SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
// use the principal information for some audit processes
}
}
In this case the Principal is not null and it has the information that I need.
Do you know what could be happening?
I was going through the same problem and then I have solved it in following manner.
Create UserService interface
public interface UserService {
String getLoggedInUserName();
User getLoggedInUser();
}
Provide an implementation for UserService, However, you can also it without creating the interface and by simply creating UserService as a class.
#Service
public class UserServiceImpl implements UserService {
private static Log log = LogFactory.getLog(UserServiceImpl.class);
#Override
public String getLoggedInUserName() {
try {
return getLoggedInUser().getUsername();
} catch (Exception ex) {
throw new UsernameNotFoundException("Please Log in", ex);
}
}
#Override
public User getLoggedInUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof User) {
return (User) authentication.getPrincipal();
} else {
throw new UsernameNotFoundException("User is not authenticated; Found " + authentication.getPrincipal() + " of type " + authentication.getPrincipal().getClass() + "; Expected type User");
}
}
}
And the calling userService.getLoggedInUserName() by auto wiring UserService
#Autowired UserService userService
Update:
If you are getting them in your controller only then you can simply pass Principal principal as a method argument to your controller method instead of getting it from the security context. It will be auto-wired to controller automatically and later on you can pass it your service methods. This way is also considered a good practice Spring MVC, getting principal from security context in service layer
#RequestMapping(value = "/myEndpoint", method = GET)
public ResponseEntity<Void> myEndpoint(Principal principal){
// do something
// use the principal information for some audit processes
}
In order to retrieve a list in a Spring MVC application I would like to write something like:
public String myMethod(#RequestParam("foo") List<FooUi> foos)
But the only solution I've found so far is the following :
public String myMethod(FooListWrapperUi fooListWrapperUi)
I don't like this solution because I have to write a wrapper each time I need to retrieve a list. In this example, the wrapper is the following :
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class FooListWrapperUi
{
private ArrayList<FooUi> fooList;
}
So my question is, is it possible to use something like the first solution or is it impossible and I need to write a wrapper?
Thanks.
You can accommodate your use case by creating your own HandlerMethodArgumentResolver:
public class FooUiResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter methodParameter) {
return (methodParameter.getParameterType().equals(FooUi.class) ||
(methodParameter instanceof Collection<?> && ((ParameterizedType) methodParameter.getParameterType().getGenericSuperclass()).getActualTypeArguments()[0] == FooUi.class));
}
#Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
// Create instances of FooUi by accessing requests parameters in nativeWebRequest.getParameterMap()
}
}
The actual implementation will depend on how you would create one or more FooUi instances from the request parameters or body. You then need to register FooUiResolver in your servlet config:
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
argumentResolvers.add(new FooUiResolver());
super.addArgumentResolvers(argumentResolvers);
}
Once registered, you can use FooUi in your controller method arguments without RequestParam or any other annotation:
#RequestMapping(value = "/foo")
public String myMethod(List<FooUi> foos){}
In an effort to make my entities persistent ignorant and make my repositories testable, I've implemented a repository pattern like so:
public interface IJobRepository : IRepository<Job>
{
Job GetJobById(int jobId); //Special case where I'm eager loading other entities
void SaveJob(Job job, Job originalJob);
}
public class JobRepository : IJobRepository
{
private readonly IContext _context;
public JobRepository()
{
_context = new CustomObjectContext();
}
public JobRepository(UnitOfWork unitOfWork)
{
_context = unitOfWork.Context;
}
//Basic GetAll, GetById, Add and Delete methods from IRepository<T> Interface here
//omitted for brevity
public Job GetJobById(int jobId)
{
var job = _context.Jobs.Include("Company").Include("Location").
Include("PlantInfo").Where(j => j.Jobid == jobId).SingleOrDefault();
_context.DisposeContext();
return job;
}
public void SaveJob(Job job, Job originalJob)
{
if (job.Jobid > 0)
{
// Update
_context.Jobs.Attach(originalJob);
_context.PlantInfoes.Attach(originalJob.PlantInfo);
_context.Jobs.ApplyCurrentValues(job);
_context.PlantInfoes.ApplyCurrentValues(job.PlantInfo);
Note: ApplyCurrentValues is an extension method I'm using on the ObjectSet
}
else
{
// Create
_context.Jobs.AddObject(job);
}
_context.Save();
}
}
public class UnitOfWork
{
private readonly IContext _context;
public UnitOfWork()
{
_context = new CustomObjectContext();
}
public UnitOfWork(IContext context)
{
_context = context;
}
public string Save()
{
return _context.Save();
}
internal IContext Context
{
get { return _context; }
}
}
public interface IContext
{
IObjectSet<Job> Jobs { get; }
IObjectSet<Company> Companies { get; }
IObjectSet<Location> Locations { get; }
IObjectSet<PlantInfo> PlantInfoes { get; }
string Save();
}
My ObjectContext inherits from IContext...So my understanding is that I will only use the overloaded constructor on the repository to facilitate unit tests or to use it in the case that I want to use the same context (not desirable based on this post I found on SO "Entity Framework and Connection Pooling" -- Is this right?
Also, assuming the context only gets disposed when the repository is garbage collected, I have to dispose the context explicitly to avoid the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker." exception when attaching the entity prior to a save.
That said, what is the best practice for managing the DataContext in a manner that keeps your entities persistent ignorant and repositories testable?
Note: This is an asp.net webapplication; UnitOfWork and IContext implementation was based on examples from "Programming Entity Framework", Second Edition by Julia Lerman Ch24.
Thanks in advance!
Firstly, I would ensure that whatever my "consumable" object is (either repository or unit of work, depending on your setup) implements IDisposable. When your consumbed object is disposed of, then you would dispose your underlying context.
For instance, if you're using your UnitOfWork as the consumable object (the one that gets created and called in your application), it would look something like:
public class UnitOfWork : IDisposable
{
// All the other stuff you had before plus:
public void Dispose ()
{
if (_context != null)
{
_context.Dispose ();
}
}
}
(Note: This can also be done on your repositories if they're the ones being consumed directly)
And then, you have a few options in your application. If you are going to use the UnitOfWork directly, you can use it like:
public void SomeMethodThatAccessesYourData ()
{
using (var unitOfWork = new UnitOfWork (/*Load in the context*/))
{
// Access your data here.
}
}
Or, in your Web Forms or MVC object you can use constructor injection and dispose of it when the Web Forms or MVC object is disposed of:
// If you're using MVC:
public class MyController : Controller
{
private UnitOfWork _unitOfWork;
public MyController (UnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public override Dispose (bool Disposing)
{
if (Disposing && _unitOfWork != null)
{
_unitOfWork.Dispose ();
}
}
}
The same idea stands for a web forms Page.
The main reason for using the constructor overload is for Inversion of Control (IOC). It helps with both unit testing and with production code when used with an IoC Container. WebForms doesn't lend itself well to IoC, but it is really easy with MVC.
Edit
I don't really see the connection with your repositories and the unit of work. Usually you access the repositories from a unit of work or, in other implementations, you request a unit of work from your target repository. In your implementation (which I understand is not your own) there seems to be no need for both.
Edit 2
If the UoW is overkill for your application, and you know you can use IoC to inject your IContext, and you don't have very many repositories, you can do something like:
public IRepository<T> : IDisposable { }
public IJobRepository : IRepository<Job> { /* All the stuff you put here */ }
public JobRepository : IJobRepository
{
private IContext _context;
...
public void Dispose ()
{
if (_context != null)
{
_context.Dispose ();
}
}
public JobRepository (IContext context)
{
_context = context;
}
}
Then, how you use it depends on your specific task. I'm not a fan of this direct use of IRepository, but this answer is getting too long.
I am new to WCF i am using constructor in my WCF service.svc.cs file....It throws this error when i use the constructor
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor.
To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
When i remove the constructor its working fine....But its compulsory that i have to use constructor...
This is my code
namespace UserAuthentication
{
[ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)]
public class UserAuthentication : UserRepository,IUserAuthentication
{
private ISqlMapper _mapper;
private IRoleRepository _roleRepository;
public UserAuthentication(ISqlMapper mapper): base(mapper)
{
_mapper = mapper;
_roleRepository = new RoleRepository(_mapper);
}
public string EduvisionLogin(EduvisionUser aUser, int SchoolID)
{
UserRepository sampleCode= new UserRepository(_mapper);
sampleCode.Login(aUser);
return "Login Success";
}
}
}
can anyone provide ideas or suggestions or sample code hw to resolve this issue...
You could add something like (if possible):
public UserAuth() : this(SqlMapperFactory.Create())
{
}