I am trying to assign a string whose value is passed into the method when I got this error :
Bus error: 10
My code:
struct user {
string username;
string password;
};
The method:
user *init_user(const string & username, const string & password){
user *u = (user *)malloc(sizeof(user));
if (u == NULL){
return NULL;
}
u->username = username;
u->password = password;
return u;
}
Calling:
user *root = init_user("root", "root");
I think the error is raised by
u->username = username;
u->password = password;
The compiler I'm using is c++11
OS: MacOS
malloc does not call constructors, so that the strings you assign to are invalid, hence SIGBUS.
In C++ use new, it allocates memory and calls the constructor for you:
user *init_user(const string & username, const string & password) {
user* u = new user;
u->username = username;
u->password = password;
return u;
}
The factory functions should return a smart-pointer, like std::unique_ptr to convey the transfer of ownership and prevent memory leaks:
std::unique_ptr<user> init_user(const string & username, const string & password) {
std::unique_ptr<user> u(new user);
u->username = username;
u->password = password;
return u;
}
Related
I am learning Spring-Boot and I'm doing a little project to practice, but I have a problem.
This is a simple authentication app, you can register and log in. My aim is: If you log in your username should be appeared, and for further functions I need the ID as well.
So I have this code:
#PostMapping("/main")
public String login(#ModelAttribute Users user, Model model) {
time = sdf.format(new Date());
Users correctUser = serv.selectUser(user.getName(), user.getPassword());
if (correctUser != null) {
//Users data
login_name = user.getName();
actual_user_id = user.getId();
model.addAttribute("given_name", login_name);
System.out.println("DEBUG: " + user);
System.out.println(time + " Successful");
return "main_screen";
} else {
System.out.println(time + " Log in failed");
return "error_page";
}
}
I can get and storage the name well in login_name, but with the ID I have some problems. As you can see I use user.getId() same as with name, but either way I get null and can't storage the ID in my actual_user_id variable.
Here is my repository:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Optional<Users> findFirstByName(String name);
Optional<Users> findUserByNameAndPassword(String name, String password);
}
And my service method:
public Users authentication(String name, String password) {
return repo.findUserByNameAndPassword(name, password).orElse(null);
}
EDIT: And this is my Users class
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String password;
private String email;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", passowrd='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
I think it should work, but I can't find the problem.
Can anyone help me?
As I can see, I get the name and the password with the findUserByNameAndPassword() and nothing else, however I should I suppose.
You look to be trying to get your id from the user passed to you in the post request:
actual_user_id = user.getId();
Try getting your information from the user you retrieved from the database:
actual_user_id = correctUser.getId();
public Account(BaseEntityBuilder<?, ?> b, String email, String name, String nickname, String pwd, UserRole usertype,
String userf1, String userf2, String userf3, String userf4, String userf5, String filetype) {
super(b);
this.email = email;
this.name = name;
this.nickname = nickname;
this.pwd = pwd;
this.usertype = usertype;
this.userf1 = userf1;
this.userf2 = userf2;
this.userf3 = userf3;
this.userf4 = userf4;
this.userf5 = userf5;
this.filetype = filetype;
}
code
public interface SpringReadFileService {
List<Account> findAll();
boolean saveDataFromUploadfile(MultipartFile file);
}
code
List<Account> users = springReadFileService.findAll();
for(int i = 0; i< users.size(); ++i) {
String a = users.get(i).getEmail();
}
code
In this way, I'm trying to get only all email value among the values in the account array, but it keeps coming to an empty value. Can't I bring it like this? I want to get the value of all the emails in the data.
This is how I understand your question:
You are using findAll of a Spring Data JPA repository in order to load all Account instances.
You are only interested in the non empty email addresses.
Define your repository as
class AccountRepository<Account, Long> { // replace Long with the type of the primary key
#Query("SELECT DISTINCT email FROM Account WHERE email IS NOT NULL")
String findAllEmails();
}
Then use findAllEmails to get the required result.
There are a couple of variants of the JPQL statement depending on what you want:
If you want duplicates or email is unique through some constraint drop the DISTINCT
If you also have empty but not null emails, i.e. emails of length 0 you might want to add AND email <> '' to the query.
I have an existing system that uses string based unique IDs for users and I want to transfer that System into a Spring boot application. I want to creat a user so I send a POST request with the following content:
As you can see, the id gets ignored.
This is my Spring code for the user class:
#PostMapping("/user")
ResponseEntity addUser(User receivedUser) {
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
logger.info("Empfangener User: " + receivedUser.toString());
try {
User mailCheckUser = userService.getUserByMail(receivedUser.getEmail());
User nameCheckUser = userService.getUserByName(receivedUser.getUsername());
if (mailCheckUser != null){
return new ResponseEntity("Email already exists", HttpStatus.NOT_ACCEPTABLE);
}
if (nameCheckUser != null){
return new ResponseEntity("Username already exists", HttpStatus.NOT_ACCEPTABLE);
}
userService.addUser(receivedUser);
} catch (Exception userCreationError) {
return new ResponseEntity(receivedUser, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity(receivedUser, HttpStatus.OK);
}
public void addUser(User user) {
userRepository.save(user);
}
And this is my user class:
#Entity
#Table
public class User {
#Id
#Column(unique =true)
private String id;
private #Column(unique =true)
String username;
private #Column(unique =true)
String email;
private #Column(unique =true)
String simpleAuthToken;
private
String password;
/*REDACTED*/
private
boolean isBlocked;
public User(String id, String name, String email, boolean isBlocked) {
this.id = id;
this.username = name;
this.email = email;
this.simpleAuthToken = simpleAuthToken;
this.isBlocked = false;
}
public User() {
}
/*GETTERS AND SETTERS ARE HERE, BUT I CUT THEM FOR SPACING REASONS*/
}
And this is the Spring Output:
My expected outcome would be that Spring would recognize the id and then create a user with the id I provided. Why is the id always null?
EDIT: If I put the ID in a Put or Get Mapping as Path variable, like so:
#PutMapping("/user/{id}")
ResponseEntity updateUser(#PathVariable String id, User receivedUser) {}
then it gets read and recognized, but it will still be null in the receivedUser
First add #RequestBody in the post request body. In the Post request (/test/user) your passing some params but in the method level not received.
If you want receive id from postman then add #RequestParam("id")String id in the method level.
How you generating unique Id by manually or some generators?
And double check user id at the database console level.
I am updating user's information like first name and last name and I am getting first name and last name in all the pages for welcome message.
I have two controllers one for ajax request mapping and the other for normal request mapping.
Normal request mapping controller have this method. In this controller all page navigation is present and some request mapping which are not ajax calls
private String getPrincipalDisplay() {
GreenBusUser user = null;
String userName = "";
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
user = (GreenBusUser) principal;
userName = user.getFirstName() + " " + user.getLastName();
} else {
userName = "";
}
return userName;
}
This is how I am getting the username on every page by return string of this function I am adding it in ModelMap object.
When I update user's information I am doing in ajax request mapping.
#RequestMapping(value = "/restify/updateUserData", method = RequestMethod.PUT, headers = "Accept=application/json")
public ServiceResponse forgotPassword(#RequestBody Object user)
{
//logger.debug("getting response");
return setDataPut("http://localhost:7020/forgotPassword",user);
}
user is an Object type which has json data. Now how do I retrieve data from object and update my first name and last name in principal.
This is my GreenBusUser class
public class GreenBusUser implements UserDetails
{
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Collection<? extends GrantedAuthority> grantedAuthorities;
private String firstName;
private String lastName;
public GreenBusUser(String username,String password,Collection<? extends GrantedAuthority> authorities,String firstName, String lastName)
{
this.username = username;
this.password = password;
this.grantedAuthorities = authorities;
this.firstName=firstName;
this.lastName=lastName;
this.grantedAuthorities.stream().forEach(System.out::println);
}
public Collection<? extends GrantedAuthority> getAuthorities()
{
return grantedAuthorities;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPassword()
{
return password;
}
public String getUsername()
{
return username;
}
public boolean isAccountNonExpired()
{
return true;
}
public boolean isAccountNonLocked()
{
return true;
}
public boolean isCredentialsNonExpired()
{
return true;
}
public boolean isEnabled()
{
return true;
}
}
UPDATE:::::
I have updated your code and applied some part of your answer into mine but still I ran into a problem
#RequestMapping(value="/updateUser",method=RequestMethod.GET)
public String updateUser(ModelMap model) {
UserInfo user = getUserObject();
GreenBusUser newGreenBususer = null;
List<User> list = new ArrayList<User>();
list = FetchDataService.fetchDataUser("http://localhost:8060/GetuserbyUserName?username=" + getPrincipal(), user.getUsername(), user.getPassword());
logger.debug("new user list ----->>>"+list.size());
User newuser=(User)list.get(0);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
SecurityContextHolder.getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext().getAuthentication().getCredentials());
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
newGreenBususer=(GreenBusUser)principal;
logger.debug("newGreenBususerDetails---->>>"+newGreenBususer.toString());
newGreenBususer.setFirstName(newuser.getFirstName());
newGreenBususer.setLastName(newuser.getLastName());
if(newGreenBususer.getFirstName()!=null) {
logger.debug("got my first name");
}
if(newGreenBususer.getLastName()!=null) {
logger.debug("got my last name");
}
auth.setDetails(newGreenBususer);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
model.addAttribute("user", getPrincipalDisplay());
model.addAttribute("userData", list);
model.addAttribute("check", true);
return "GreenBus_updateProfile_User";
}
At first it sets the firstname and lastname to GreenBusUser and then there is setDetails method when I reload the page it says No user found when I am calling getUserObject() method at the top of this method.
private X2CUser getUserObject() {
X2CUser userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((X2CUser) principal);
} else {
logger.info("No user found");
}
return userName;
}
If you are updating the password, then it will be good to logout the user and tell him to relogin.
Try this code .. It might help you.
UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
I have finally resolved my problem though I have later added some code in my question part in UPDATE section.
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
newGreenBususer=(GreenBusUser)principal;
newGreenBususer.setFirstName(newuser.getFirstName());
newGreenBususer.setLastName(newuser.getLastName());
Yes that's all need to be done.
This part--->>
auth.setDetails(newGreenBususer);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
set new context making security pointing to null when I reload still not clear because I am setting the details before reload so its like I get new context but I have set the new user details.
Though I have finally resolved my problem but if anyone could shed some light why it was happening then I will accept his/her answer.
Thanks alot for your support. Keep Learning!
User enters Username, password and system generates unique field. Each username password combination along with an auto generated unique field is stored in a List as an object.
I want to find out if the username-password combination is repeated or not in the list (without considering the unique key).
I wanted to avoid using for loops to figure this out. Using hashmap to find out if there are repeated combinations-
//hm is the hashmap...
//up is the list....
for(int i=0; i<up.length(); i++){
if(hm.contains(up[i])){
System.out.println("Repeated combination");
break;
}
else{
hm.put(up[i],i);
}
}
However the object has a unique auto generated field and the above logic wouldn't work. Any suggestions to achieve this in the fastest possible way.
I assume that up[i] is some class(User) which has username, password and unique_id as three fields.
If that's true you can create wrapper around this class(UserWrapper) and override equals/hashCode methods to rely only on username/password attributes of User class.
That should be really quick to code/test
EDIT: Sample classes are below. You could you LinkedHashMap (so you'll have map functionality and still have users ordered in the same way as you put them in)
class User {
private final String id = UUID.randomUUID().toString();
private final String username;
private final String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof User) {
User user = (User) obj;
return id.equals(user.getId()) &&
username.equals(user.getUsername()) &&
password.equals(user.getPassword());
}
return false;
}
public int hashCode() {
return id.hashCode() + username.hashCode() * 31 + password.hashCode() * 31 * 31;
}
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
Wrapper:
class UserWrapper {
private final User user;
public UserWrapper(User user) {
this.user = user;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof UserWrapper) {
UserWrapper userWrapper = (UserWrapper) obj;
return user.getUsername().equals(userWrapper.getUser().getUsername()) &&
user.getPassword().equals(userWrapper.getUser().getPassword());
}
return false;
}
public int hashCode() {
return user.getUsername().hashCode() + user.getPassword().hashCode() * 31;
}
public User getUser() {
return user;
}
}
Finder:
class DuplicateUserFinder {
public List<UserWrapper> findDuplicates(List<UserWrapper> allUsers) {
final List<UserWrapper> duplicateList = new ArrayList<UserWrapper>();
final Set<UserWrapper> duplicateSet = new HashSet<UserWrapper>();
for (UserWrapper wrapper : allUsers) {
if (duplicateSet.contains(wrapper)) {
duplicateList.add(wrapper);
} else {
duplicateSet.add(wrapper);
}
}
return duplicateList;
}
}
Unit Test:
public class DuplicateUserFinderTest {
private final DuplicateUserFinder finder = new DuplicateUserFinder();
#Test
public void shouldReturnEmptyIfNoDuplicates() {
User user1 = new User("user1", "pass1");
User user2 = new User("user2", "pass2");
UserWrapper userWrapper1 = new UserWrapper(user1);
UserWrapper userWrapper2 = new UserWrapper(user2);
Assert.assertTrue(finder.findDuplicates(Arrays.asList(userWrapper1, userWrapper2)).isEmpty());
}
#Test
public void shouldReturnDuplicates() {
User user1 = new User("user", "pass");
User user2 = new User("user", "pass");
UserWrapper userWrapper1 = new UserWrapper(user1);
UserWrapper userWrapper2 = new UserWrapper(user2);
Assert.assertTrue(finder.findDuplicates(Arrays.asList(userWrapper1, userWrapper2)).contains(userWrapper2));
Assert.assertThat(finder.findDuplicates(Arrays.asList(userWrapper1, userWrapper2)).size(), CoreMatchers.equalTo(1));
}
}