Full text search for entity with user - java

I have a simple web application with two entities:
User
State (with field: User ownerUser)
User can create and read own States. I created full text search (elasticsearch) for States but my search returns me all States, not only created by logged user. I tried something like this but it doesn't work:
public Page<StatusDTO> search(String query, Pageable pageable) {
log.debug("Request to search for a page of Statuses for query {}", query);
String login = SecurityUtils.getCurrentUserLogin();
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(queryStringQuery(query))
.withFilter(boolQuery().filter(termQuery("ownerUser : login", login)))
.build();
Page<Status> result = statusSearchRepository.search(searchQuery.getQuery(), pageable);
return result.map(statusMapper::toDto);
}

Can you try
.withFilter(boolQuery().filter(termQuery("ownerUser.login", login)))

Related

Problem to implement FindById to a return statement in java with MongoDB

UPDATE: The return statement is still not working as expected to show single user detail by id in the DAO. I could only use for loop to iterate through the _id to match the userId, but when I click the edit button for the number of user will show all previous user Id in the console.
Another problem is when I call this method in the Service class, the output is null. Still crave for the solution to help me get over it.
#Override
public User get(Object userId) {
User user = new User();
FindIterable<Document> userTbl = database.getCollection("User").find();
for (Document doc : userTbl) {
String id = doc.getObjectId("_id").toString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return user;
}
}
return null;
}
edit user in Service class
public void editUser() throws ServletException, IOException {
Object userId = request.getParameter("id"); // get query string from the jsp
User user = userDAO.get(userId);
System.out.println("User full name is? " + user.getFullName());
}
After getting hints from #Smutje and think through it again, finally figured it out at my 2nd weeks of learning MongoDB. At my level I need to iterate the user document then find the id and return it.it
#Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc;
}
}
return null;
}

Thyme, Spring: stuck on creating a single item view

I have successfully implemented adding a visit and showing a list of all visits, but now I'm stuck on creating a view for a single visit.
My findById function works:
logger.info("Visit id 2 -> {}", repository.findById(2));
Visit id 2 -> DentistVisitDTO[id='0', dentistName='Mait Kuusevaik', visitTime='2018-10-12T12:15']
And when I click on a list item it sucessfully redirects to a url using ID (i.e "/results/1" and so on. Is there a way I can use the ID from the URL and somehow render the item on the page using findById()?
I'm new to Spring and Thyme.
public DentistVisitDTO findById(long id) {
return jdbcTemplate.queryForObject("SELECT * FROM DENTIST_VISIT where id=?", new Object[] { id },
new BeanPropertyRowMapper<DentistVisitDTO>(DentistVisitDTO.class));
}
You can use the #RequestMapping annotation of SpringMVC/SpringWeb to get the id attribute from the URL:
import org.springframework.web.bind.annotation.RequestMapping;
#RequestMapping(value="/results/{id}", method=RequestMethod.GET)
public String detail(#PathVariable(value="id") String id, Model model) {
DentistVisitDTO dentistVisit = repository.findById(id);
System.out.println("GET /results [" + id + "]");
model.addAttribute("dentistVisit", dentistVisit);
return "details";
}

Variable getting overwritten

I've written some code using Spring Boot and Lombok. I've got two objects, user and loggedInUser both are based on User.class. I assign a different value to the each of the objects userEmail field. I got the following code. The user is what is in the request from the endpoint while the loggedInUser is the user performing the request.
This is the User.class:
#Component
#Data
public class User {
private String userEmail;
}
This is the class where I'm using User.class
private User user;
private User loggedInUser;
private SearchParameters searchParameters;
public UserController(
User user,
User loggedInUser,
SearchParameters searchParameters, {
this.user = user;
this.loggedInUser = loggedInUser;
this.searchParameters = searchParameters;
}
#GetMapping(value = "${apiVersion.v_1}" + "/users")
public ResponseEntity getUsers(
#RequestParam("userEmail") String userEmail,
#RequestParam("direction") String direction,
#RequestParam("limit") String limit) {
Jws<Claims> jwsClaims = (Jws<Claims>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
loggedInUser.setUserEmail(jwsClaims.getBody().getSubject()); //From a JWT the logged in user's e-mail is picked up. In this case joe#example.com
log.info("loggedInUser.getUserEmail #1: " + loggedInUser.getUserEmail());
user.setUserEmail(userEmail); // From the request parameters the email is that will be used for the search is picked up. In this case smith#example.com
searchParameters.setDirection(direction); //Can be "u" or "d" that corresponds to "SELECT * FROM user_tbl WHERE < user.getEmail()" or "SELECT * FROM user_tbl WHERE > user.getEmail()" in the SQL that will run in another class
searchParameters.setLimit(limit); //An integer that will limit the number of returned results from the user_tbl
log.info("loggedInUser.getUserEmail #2: " + loggedInUser.getUserEmail());
//The search is done in another class that is taking user.getEmail() as an argument and returns a List of users
return (new ResponseEntity(users, headers, HttpStatus.OK));
}
It gives me the following output.
loggedInUser.getUserEmail #1: joe#example.com
loggedInUser.getUserEmail #2: smith#example.com
I would have thought that user and loggedInUser are two separate objects since they have different names and that the dependency injection is instantiate a new object each time but it seems like user is overwriting loggedInUser. What is it I'm missing here?

Reading blob type image from mysql database in Spring mvc with jdbcTemplate

ProductController.java
#RequestMapping(value = "/adminWelcome", method = RequestMethod.GET)
public String getAdminWelcomePage(Model model) {
System.out.println("Product List:" + productService.getAllProducts());
model.addAttribute("productList", productService.getAllProducts());
return "adminHomepage";
}
ProductService.java
public List<Map<String, Object>> getAllProducts() {
String sql = "SELECT * FROM products LIMIT 3";
List<Map<String, Object>> products = jdbcTemplate.queryForList(sql);
return products;
}
Basically, this sql return the list of 3 products which are looks like
Product List:[{id=1, name=Twitter-minimal, userId=0, image=[B#96a7858, price=1213322.0, dateManufacture=2017-02-07, dateAdded=2017-02-07 15:50:12.0, category=Clothing, description=ramedadadadad}].
This is the sample of the result which I fetched from MySql database with jdbcTemplate. I upload the image using Spring MVC4 in the database. Now I want to retrieve or read the Blobimage type so that I can display those images to my jsp pages. How can I convert this Blob image so that I can properly display to pages?
The image type was defined as MultipartFile image in the domain class.
yo need resource mapping in dispatcher-servlet.xml
and
add this in your jsp page..
where static as i have defined is /WEB-INF/assets/

How can I compare request.getParameter(string) in Controller class with MySQL database?

I'm currently working on a (relatively) basic web application that functions as a time clock for a fictional employer. Currently, the application implements HTML, JavaScript, Java, MySQL, the Spring Framework and xml. I have a log in page, and it takes the user input for the Username and Password and stores the information. The problem is, I can't seem to figure out how to take that information and compare it with the MYSQL database to successfully log in. I can post examples of code, if necessary and thanks in advance for the assistance.
This is a piece of the LoginController:
#RequestMapping(value = "/jsp/login")
public ModelAndView existUser(HttpServletRequest request) {
return new ModelAndView("UserPrint.jsp", hashmap.makeHashMap());
}
#RequestMapping(value = "userLogin")
public ModelAndView loginUser(HttpServletRequest request,
HttpSession session) {
String strLoginJsp = "login.jsp";
String strSessionErrorAttribute = "errors";
User sessionUser = getUserFromSession(session);
if (request.getHeader("referer") == null
|| request.getHeader("referer").contains("AddNewUser.html")) {
session.setAttribute(SESSION_USER_ATTRIBUTE, new User());
session.setAttribute(strSessionErrorAttribute, "");
return new ModelAndView(strLoginJsp, hashmap.makeHashMap());
}
User requestUser = new User();
String requestedUserName = request.getParameter("userName");
requestUser.setUserName(requestedUserName);
String requestedPassword = request.getParameter("password");
requestUser.setPassword(requestedPassword);
session.setAttribute(strSessionErrorAttribute, "");
// Check if username and password is in DB
User loginUser = userDao.login(requestUser);
if (loginUser == null) {
// Either the username doesn't exist, or the password was bad.
if (userDao.userNameExist(requestedUserName)) {
// user entered bad password
if (sessionUser.getUserName() != null
&& sessionUser.getUserName().equals(
requestUser.getUserName())) {
} else {
sessionUser.setUserName(requestUser.getUserName());
}
}
} else {// username does not exist in db
session.setAttribute(strSessionErrorAttribute,
"Please register account.");
Here's a piece of the UserDao:
#SuppressWarnings("unchecked")
#Transactional
public List<User> getAllUsers() {
Query query = em.createNamedQuery("fetchAllUsers");
return query.getResultList();
}
public User login(User user) {
Query query = em.createNamedQuery("userLogin");
query.setParameter("userName", user.getUserName());
query.setParameter("password", user.getPassword());
List<User> currentUsers = query.getResultList();
if (currentUsers.size() > 0) {
return (User) currentUsers.get(0);
}
return null;
}
#SuppressWarnings("unchecked")
#Transactional
public Boolean userNameExist(String userName) {
Query query = em.createNamedQuery("getUserWithUsername");
query.setParameter("userName", userName);
List<User> existUser = query.getResultList();
if (existUser.size() > 0) {
return true;
}
return false;
}
To expand on dm03514 's answer - yes you should "sanitize" user input by using prepared statement objects in Java JDBC.
If you're using Spring then you should use spring-security. They have pretty much done this for you already and you just have to configure it.
Normally you would take your login and password and search for a user
String queryStr = "SELECT * FROM users WHERE login='"+sanitize(userLogin)+"' AND password='"+sanitize(userPass)"'";
This is not actual code just psuedo code. I do not know how java or spring handles sanitation but it is of utmost importance that you dont' trust anything input by the user when you are building a query string.
The idea is if this results in 1 user the user is valid, if it returns none the user is not valid!
Using paramaterized queries could be the best approach
Yes, please, post some code.
What exactly is the issue?
On the most basic level you should be able to:
pass the username and password as parameters in the HttpServletRequest object
Retrieve said parameters by "name" from the HSR object in the Controller.
Pass them to the SQL query for comparison against the database field.
Which of the above steps failed?

Categories