I'm trying to log a login action with AspectJ. I need to obtain the logged user. I tried this but it doesn't work. The joinpoint is never executed.
#Aspect
public class LoginActivityAspect {
#Pointcut(value = "call(void com.android.project.activities.LoginActivity.loginSuccess(String)) && this(username)", argNames = "username")
public void loginSuccess(String username) {}
#Before(value = "loginSuccess(username)")
public void logLoginSuccess(username) {
logger.debug("loginSuccess", "Login success: " + username);
}
}
In LoginActivity I have this method:
public void loginSuccess(String username){
//DO STUFF
}
What am I doing wrong? Thanks.
Solved! Sorry I'm newbie in AOP.
I have modified the pointcut into this:
#Pointcut(value = "call(void com.android.project.activities.LoginActivity.loginSuccess(String)) && args(username)")
public void loginSuccess(String username) {}
Related
I want custom UserNamePasswordValidator in my orchard project.
Like this,How can i injection IUserService? thank you.
public class CustomUserNameValidator: UserNamePasswordValidator
{
private IUserSevice m_UserService;
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if(!m_UserService.CheckUser(userName,password))
{
throw new SecurityTokenException("Unknown Username or Password");
}
}
}
There's an excellent article in the docs about dependency injection.
You basically need to build and implement an interface like this:
public interface ICustomUserNameValidator : IDependency{}
Afterwards you can inject it wherever you want.
public class MyPartDriver : ContentPartDriver
{
public MyPartDriver(ICustomerUserNameValidator validator)
{
}
}
I am relatively new to the Spring boot frame work. I had a basic web application built in Angular with Spring boot connected and to a Mongodb. The application allowed users to add todo lists and register for the the website. When the application started it returned the todolists stored in mongodb to the view. The user could register, and there details were stored in a Mongo repository.
When I added and implemented spring security I got the error message
Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
What I want to happen is, when the webapp loads, I want the index.html to be injected with todo.html. Then if a user logs in they will be directed to another page or some Ui feature to become available. At the moment I am stuck in this Circular view pathloop.
I have looked through the different answers but I still am confused as to what exactly is causing the issue. I believe it is in the WebSecurityConfig class
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
UserDetailsService userDS;
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/api/todos/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDS);
}
#Override
protected UserDetailsService userDetailsService() {
return userDS;
}
}
AuthUserDetailsService
#Repository
public class AuthUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository users;
private org.springframework.security.core.userdetails.User userdetails;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// TODO Auto-generated method stub
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
todoapp.models.User user = getUserDetail(username);
userdetails = new User (user.getUsername(),
user.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(user.getRole())
);
return userdetails;
}
public List<GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
if (role.intValue() == 1) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
} else if (role.intValue() == 2) {
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
}
return authList;
}
private todoapp.models.User getUserDetail(String username){
todoapp.models.User user = users.findByUsername(username);
return user;
}
}
TodoController
#RestController
#RequestMapping("/api/todos")
public class TodoController {
#Autowired
TodoRepository todoRepository;
#RequestMapping(method=RequestMethod.GET)
public List<Todo> getAllTodos() {
return todoRepository.findAll();
}
#RequestMapping(method=RequestMethod.POST)
public Todo createTodo(#Valid #RequestBody Todo todo) {
return todoRepository.save(todo);
}
#RequestMapping(value="{id}", method=RequestMethod.GET)
public ResponseEntity<Todo> getTodoById(#PathVariable("id") String id) {
Todo todo = todoRepository.findOne(id);
if(todo == null) {
return new ResponseEntity<Todo>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<Todo>(todo, HttpStatus.OK);
}
}
#RequestMapping(value="{id}", method=RequestMethod.PUT)
public ResponseEntity<Todo> updateTodo(#Valid #RequestBody Todo todo, #PathVariable("id") String id) {
Todo todoData = todoRepository.findOne(id);
if(todoData == null) {
return new ResponseEntity<Todo>(HttpStatus.NOT_FOUND);
}
todoData.setTitle(todo.getTitle());
todoData.setCompleted(todo.getCompleted());
Todo updatedTodo = todoRepository.save(todoData);
return new ResponseEntity<Todo>(updatedTodo, HttpStatus.OK);
}
#RequestMapping(value="{id}", method=RequestMethod.DELETE)
public void deleteTodo(#PathVariable("id") String id) {
todoRepository.delete(id);
}
}
RecourceController
#Configuration
public class ResourceController extends WebMvcConfigurerAdapter{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/api/todos").setViewName("home");
registry.addViewController("/register").setViewName("register");
registry.addViewController("/login").setViewName("login");
}
}
Any help will be greatly appreciated.
This is the Project Layout.
You forgot to add .html to your view names:
registry.addViewController("/").setViewName("app/views/index.html");
registry.addViewController("/api/todos").setViewName("app/views/home.html");
registry.addViewController("/register").setViewName("app/views/register.html");
registry.addViewController("/login").setViewName("app/views/login.html");
Spring Boot registers a ResourceHttpRequestHandler which is capable of resolving static resources under static folder.
Because you set login as view name ResourceHttpRequestHandler tries to load static/login which apparently does not exist.
Change it to app/views/login.html so that static/login becomes static/app/views/login.html.
I'm using SpecFlow with Nunit and I'm trying to setup my enviroment tests using TestFixtureSetUpAttribute, but it's never called.
I already tried to use MSTests and ClassInitialize attribute, but the same happen. The function isn't called.
Any ideas Why?
[Binding]
public class UsersCRUDSteps
{
[NUnit.Framework.TestFixtureSetUpAttribute()]
public virtual void TestInitialize()
{
// THIS FUNCTION IS NEVER CALLER
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
private string username, password;
[Given(#"I have entered username ""(.*)"" and password ""(.*)""")]
public void GivenIHaveEnteredUsernameAndPassword(string username, string password)
{
this.username = username;
this.password = password;
}
[When(#"I press register")]
public void WhenIPressRegister()
{
}
[Then(#"the result should be default account created")]
public void ThenTheResultShouldBeDefaultAccountCreated()
{
}
Solution:
[Binding]
public class UsersCRUDSteps
{
[BeforeFeature]
public static void TestInitialize()
{
// THIS FUNCTION IS NEVER CALLER
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
private string username, password;
[Given(#"I have entered username ""(.*)"" and password ""(.*)""")]
public void GivenIHaveEnteredUsernameAndPassword(string username, string password)
{
this.username = username;
this.password = password;
}
[When(#"I press register")]
public void WhenIPressRegister()
{
}
[Then(#"the result should be default account created")]
public void ThenTheResultShouldBeDefaultAccountCreated()
{
}
Your TestInitialize is not called because it is inside your Steps class and not inside in an Unit Tests (because the actual unit test is inside the .cs which is generated from your .feature file).
SpecFlow has it's own test-lifetime events which are called hooks, these are all the predefined hooks:
[BeforeTestRun] / [AfterTestRun]
[BeforeFeature] / [AfterFeature]
[BeforeScenario] / [AfterScenario]
[BeforeScenarioBlock] / [AfterScenarioBlock]
[BeforeStep] / [AfterStep]
Note that this allows for greater flexibility in setup. For additional information see the documentation.
Based on the fact that you want to use the TestFixtureSetUp attribute you will probably need the BeforeFeature hook which will be called once before each feature, so you need to write:
[Binding]
public class UsersCRUDSteps
{
[BeforeFeature]
public static void TestInitialize()
{
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
//...
}
Note that the [BeforeFeature] attribute needs a static method.
You should also note that if you are using the VS integration there is an project item type called SpecFlow Hooks (event bindings) which creates a binding class with some predefined hooks to help you get started.
I am trying to write a pointcut and advice which could print a string from following method -
public CustomerDto getCustomer(Integer customerCode){
CustomerDto customerDto = new CustomerDto();
String emailID =getEmailAddress();
customerDto.setEmailAddress(emailID);
customerDto.setEmployer(getEmployer());
customerDto.setSpouseName(getSpouse());
return customerDto;
}
I am unable to figure out a way by which a pointcut look at String emailID and then print the value of the same in an advice.
Maybe you need something like the following:
public privileged aspect LocalMethodCallAspect {
private pointcut localMethodExecution() : withincode(public CustomerDto TargetClass.getCustomer(Integer)) &&
call(private String TargetClass.getEmailAddress());
after() returning(String email) : localMethodExecution()
{
System.out.println(email);
}
}
Where TargetClass is a class containing getCustomer() and getEmailAddress() methods.
Or the same using #AspectJ:
#Aspect
public class LocalMethodCallAnnotationDrivenAspect {
#Pointcut("withincode(public CustomerDto TargetClass.getCustomer(Integer)) && " +
"call(private String TargetClass.getEmailAddress())")
private void localMethodExecution() {
}
#AfterReturning(pointcut="localMethodExecution()",returning="email")
public void printingEmail(String email) {
System.out.println(email);
}
}
I'm working on a GWT project and have several void remote services that seem to execute just fine, but on the client side, end up firing the onFailure() method. No exceptions are thrown anywhere, and the expected behavior is observed on the backend. I have no idea what could be going wrong. Here is the relevant code:
Interfaces and implementation...
#RemoteServiceRelativePath("DeleteSearchService")
public interface DeleteSearchService extends RemoteService {
/**
* Utility class for simplifying access to the instance of async service.
*/
public static class Util {
private static DeleteSearchServiceAsync instance;
public static DeleteSearchServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(DeleteSearchService.class);
}
return instance;
}
}
public void delete(SearchBean search);
}
public interface DeleteSearchServiceAsync {
public void delete(SearchBean bean, AsyncCallback<Void> callback);
}
public class DeleteSearchServiceImpl extends RemoteServiceServlet implements DeleteSearchService {
private static final long serialVersionUID = 1L;
#Override
public void delete(SearchBean search) {
try {
Connection conn = SQLAccess.getConnection();
String sql = "DELETE FROM `searches` WHERE `id`=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
sql = "DELETE FROM `searchsourcemap` WHERE `search-id` = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, search.getSearchId());
ps.execute();
return;
} catch (Exception e) {
// TODO Log error
e.printStackTrace();
}
}
}
Calling code...
private class DeleteListener implements ClickListener {
public void onClick(Widget sender) {
DeleteSearchServiceAsync dss = DeleteSearchService.Util.getInstance();
SearchBean bean = buildBeanFromGUI();
dss.delete(bean, new AsyncCallback<Void>(){
//#Override
public void onFailure(Throwable caught) {
// TODO log
SearchNotDeleted snd = new SearchNotDeleted();
snd.show();
}
//#Override
public void onSuccess(Void result) {
SearchDeleted sd = new SearchDeleted();
sd.show();
searchDef.getParent().removeFromParent();
}
});
}
}
I know I'm a jerk for posting like 500 lines of code but I've been staring at this since yesterday and can't figure out where I'm going wrong. Maybe a 2nd set of eyes would help...
Thanks,
brian
LGTM I'm afraid.
Are you using the hosted mode or a full-fledged browser? You can try switching and see if it helps.
Also, it might help listening to that //TODO and perform a GWT.log when onFailure is invoked.