Spring Social with Spring Boot not getting user email id - spring-boot

I am new as developer, trying hands on Spring social facebook integration. Followed this link
I am getting data like user's name', 'gender', 'locale'. Which can be given as constructor value to User class(see took help).
But I want to get user "email-id", somehow that's not possible the way i am getting data for 'name', 'locale' and 'gender.
We need to use method getEmail() as per docs. But I am not able to do it.
("A simple app with OAuth security implemented")
Here is the snippet....
My controller class code is
#Controller
#RequestMapping("/")
public class HelloController {
private Facebook facebook;
private ConnectionRepository connectionRepository;
public HelloController(Facebook facebook, ConnectionRepository connectionRepository) {
this.facebook = facebook;
this.connectionRepository = connectionRepository;
}
#GetMapping
public String helloFacebook(Model model) {
if (connectionRepository.findPrimaryConnection(Facebook.class) == null) {
return "redirect:/connect/facebook";
}
String [] fields = {"name", "gender", "locale"};
User userProfile = facebook.fetchObject("me", User.class, fields);
model.addAttribute("feed", userProfile);
//String email = facebook.getEmail();
/*this above one "facebook.getEmail()" gives Internal server error 500 */
return "hello";
}
}
Model class is ...
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h3>Hello, <span th:text="${feed.name}">Some User</span>!</h3>
<h4>Your gender is : <span th:text="${feed.gender}"></span></h4>
<h4>Your locale is : <span th:text="${feed.locale}"></span></h4>
<h4>Your email is : <span th:text="${feed.getEmail()}"></span></h4>
</body>
</html>
Main class is as...
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Any help is appreciated. Thanks.

Related

Springboot homepage after login

I just want to display the homepage and the users name after login but I keep getting a 404 not found error.
here is the index.html page
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:action="#{/index}">Hello<h1 th: th:text="${name}"></h1> </h1>
</body>
</html>
And here is my controller
#Controller
#AllArgsConstructor
public class UserController {
private final UserService userService;
private final ConfirmationTokenService confirmationTokenService;
#GetMapping("/sign-in")
String signIn() {
return "sign-in";
}
#GetMapping("/sign-up")
String signUpPage(User user) {
return "sign-up";
}
#PostMapping("/sign-up")
String signUp(User user) {
userService.signUpUser(user);
return "redirect:/sign-in";
}
#GetMapping("/sign-up/confirm")
String confirmMail(#RequestParam("token") String token) {
Optional<ConfirmationToken> optionalConfirmationToken = confirmationTokenService.findConfirmationTokenByToken(token);
optionalConfirmationToken.ifPresent(userService::confirmUser);
return "redirect:/sign-in";
}
#RequestMapping(value = {"/index"}, method = RequestMethod.GET)
public String welcome(User user, Model model) {
model.addAttribute("Name", user.getName());
return "index";
}
I've been trying this for a while now and I don't know what I'm doing wrong. The websecurity config is configured so that the default succesuful URL is index.html
Try changing the request mapping to
#RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
Also, try calling localhost:9090/index (without the .html) as Eleftheria Stein-Kousathana said.

Getting Error while bootstraping the Spring-boot Application

Well i am developing a spring boot application by choosing view technology as jsp.But when am trying to bootstraping the spring-boot application i am getting white level error page.
Model Class
public class Person {
private String p_first_name;
private String p_last_name;
private int age;
private String city;
private String state;
private String country;
public Person(String p_first_name, String p_last_name, int age, String city, String state, String country) {
super();
this.p_first_name = p_first_name;
this.p_last_name = p_last_name;
this.age = age;
this.city = city;
this.state = state;
this.country = country;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public String getP_first_name() {
return p_first_name;
}
public void setP_first_name(String p_first_name) {
this.p_first_name = p_first_name;
}
public String getP_last_name() {
return p_last_name;
}
public void setP_last_name(String p_last_name) {
this.p_last_name = p_last_name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Controller Class
#Controller
public class PersonController {
private static ArrayList<Person> persons = new ArrayList<Person>();
static {
persons.add(new Person("kumar", "bikash", 28, "bangalore", "karnataka", "india"));
persons.add(new Person("kumar", "pratap", 24, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "ravi", 29, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "mangalam", 65, "delhi", "delhi", "india"));
}
#RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
public String index(Model model) {
String message = "Hello" + "Spring Boot implementation with jsp Page";
model.addAttribute("message", message);
return "index";
}
#RequestMapping(value = "/personList", method = RequestMethod.GET)
public String getPersonList(Model model) {
model.addAttribute("persons", persons);
return "personList";
}
}
application.properties
# VIEW RESOLVER CONFIGURATION
spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp
jsp file
index.jsp
=========
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Integration of Spring Boot with jsp page</title>
</head>
<body>
<h1>Welcome to Spring boot</h1>
<p>This project is an Example of how to integrate Spring Boot with
jsp page.</p>
<h2>${message} </h2>
</body>
</html>
personList.jsp
==============
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Person List content Present here</title>
</head>
<body>
<h1>Person List</h1>
<div>
<table border="1">
<tr>
<th>FirstName:</th>
<th>LasttName:</th>
<th>Age:</th>
<th>city:</th>
<th>State:</th>
<th>Country:</th>
</tr>
<c:forEach items="${persons}" var=person>
<tr>
<td>${person.firstname}</td>
<td>${person.lastname}</td>
<td>${person.age }</td>
<td>${person.city }</td>
<td>${person.state }</td>
<td>${person.country }</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Error page
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 07 23:41:57 IST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
well please review the below code.Help me to resolve thing where i am
getting wrong?
Are you looking to enable your own errorpage disabling the white level error page? May be this can help you.
If you do not specify any custom implementation in the configuration,
BasicErrorController bean is automatically registered in Spring Boot. You can add your implementation of ErrorController.
#Controller
public class MyErrorController implements ErrorController {
#RequestMapping("/error")
public String handleError() {
//do something like logging
return "error";
}
#Override
public String getErrorPath() {
return "/error";
}
}
1) I would suggest trying the #RestController annotation to make sure that you get at least the JSON response. (Only for Debugging)
2) After the first part is figured out, you can go back to your #Controller annotation and make sure that the string you return in the request mapping method is available as a jsp file. I would recommend trying with a single endpoint initially ("/") and having the appropriate jsp page for it.
3) If it still produces the same issue, you can refer to this post
Spring Boot JSP 404.Whitelabel Error Page
4) You can also disable and customize the default error page by following this link https://www.baeldung.com/spring-boot-custom-error-page

Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'

Trying to change value inside my model class which contains a private String name and I wanted to change the name using Thymeleaf in HTML page then see the change in another url response body.
When I try to access my ("/myname") page in localhost I got the error:
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
Here is my Model:
public class Name {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is my Controller
#Controller
public class MainController {
#RequestMapping("/name")
#ResponseBody
public String showName() {
Name myname = new Name();
return myname.getName();
}
#RequestMapping("/myname")
public String setName() {
return "myname";
}
#RequestMapping(value = "myname", method = RequestMethod.POST)
public String showName(#ModelAttribute Name iko, BindingResult errors, Model model) {
return "name";
}
}
Here is my html thymeleaf pages:
myname.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Insert title here</title>
</head>
<body>
<form action="#" th:action="#{/myname}" th:object="${iko}" method="post">
<label>Enter the name</label><br/>
<input type="text" th:field="*{name}"/>
<button type="submit">SUBMIT</button>
</form>
</body>
</html>

Spring + Thymeleaf type Converter in a form

I'm trying to use a type converter in a Spring boot app and using Thymeleaf but I can't get it working. I've put some code on Github so you can see exactly what I'm trying to do. This is Spring 1.5.1 and Thymeleaf 3.0.3. https://github.com/matthewsommer/spring-thymeleaf-simple-converter
Basically this code is just trying to add a person to a comment object. The person object is null when it gets posted and I don't understand why.
Something that's odd is that the ID of the person isn't being added to the value attribute but it is if th:field="*{body}" is removed. I think it has to do with this: https://github.com/thymeleaf/thymeleaf/issues/495 but I'm currently trying to add BindingResult and it's not working...
My HTML is:
<body>
<div th:if="${personObject != null}" th:text="${personObject.name}"></div>
<form th:action="#{/}" th:object="${comment}" method="post">
<input type="hidden" th:if="${personObject != null}" th:value="${personObject.id}" th:field="*{person}" />
<textarea id="comment" placeholder="Comment..." th:field="*{body}"></textarea>
<button id="comment_submit" type="submit">Comment</button>
</form>
<div th:text="${comment.body}"></div>
</body>
My controller:
#Controller
public class HomeWebController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome(final HttpServletRequest request, final Map<String, Object> model, #ModelAttribute(value = "comment") Comment comment) {
model.put("personObject", new Person(1, "John Smith"));
return "Home";
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public String postHome(final HttpServletRequest request, final Map<String, Object> model, #ModelAttribute(value = "comment") Comment comment) {
model.put("commentBody", comment.getBody());
model.put("person", comment.getPerson());
return "Home";
}
}
And the converter:
#Component
public class StringToPersonConverter implements Converter<String, Person> {
#Autowired
public StringToPersonConverter() { }
#Override
public Person convert(String id) {
if(id == "1") {
Person person = new Person(1, "John Smith");
return person;
}
return null;
}
}
Hi finally I had to do some changes to make it work, but this is the result class by class.
ConvertorApplication:
#SpringBootApplication
#Configuration
#EnableWebMvc
public class ConvertorApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(ConvertorApplication.class, args);
}
//Add converter and configuration annotation
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToPersonConverter());
}
}
StringToPersonConverter:
#Override
public Person convert(String id) {
//Never compare String with == use equals, the "==" compares memory space not the values
if(id.equals("1")) {
Person person = new Person(1, "John Smith");
return person;
}
return null;
}
HomeWebController
#Controller
public class HomeWebController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome(final Map<String, Object> model, #ModelAttribute(value = "comment") Comment comment) {
//Initialize the comment with the person inside, no need of personObject object
model.put("comment", new Comment(new Person(1, "John Smith")));
return "Home";
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public String postHome(final Map<String, Object> model,
#ModelAttribute(value = "comment") Comment comment,
#RequestParam(value = "person.id") Person person) {
//from the view retrieve the value person.id which will be used by the converter to build the Person entity
comment.setPerson(person);
model.put("comment", comment);
return "Home";
}
}
Comment (Add empty constructor)
public Comment(){}
Person (Add empty constructor)
public Person(){}
Home.jsp (Basically remove personObject, not need)
<!DOCTYPE html>
<html xmlns:th="//www.thymeleaf.org">
<body>
<div th:text="${comment.person.name}"></div>
<form th:action="#{/}" th:object="${comment}" method="post">
<input type="hidden" th:field="*{person.id}" />
<textarea id="comment" placeholder="Comment..." th:field="*{body}"></textarea>
<button id="comment_submit" type="submit">Comment</button>
</form>
<div th:text="${comment.body}"></div>
</body>
</html>
That's would be everything to make it work.

Unable to bind checkboxes even after registering custom property editor

I've the following sequence of steps to register a team:
Select Team - This will display the list of players of this team as check boxes (JSP page below)
User can select one or more players displayed
newdTeam request handler method should be called setting the selected players from step 2 above. The handler is being called but the players set is empty even if I've selected players in step 2. Not sure where the issue is.
I doesn't see the property editor invoked. Any help is appreciated.
Team
#NodeEntity
public class Team
{
#GraphId
private Long nodeId;
#GraphProperty
#Indexed (unique = true)
private String name;
#Fetch
#RelatedTo (type = "PLAYED_WITH_TEAM", direction = Direction.INCOMING)
private final Set<Player> players = new HashSet<Player>();
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = StringUtil.capitalizeFirstLetter(name);
}
public Long getNodeId()
{
return nodeId;
}
public Collection<Player> getPlayers()
{
return players;
}
public void setPlayers(Set<Player> plyrs)
{
System.err.println("called set plrs");
players.addAll(plyrs);
}
}
Player
#NodeEntity
public class Player
{
#GraphId
private Long nodeId;
#Indexed (unique = true)
private String name;
#GraphProperty
#Indexed
private String firstName;
#GraphProperty
private String email;
//getters and setters
}
Controller
#Controller
#RequestMapping ("/registration")
public class RegistrationController
{
private transient final Logger LOG = LoggerFactory.getLogger(getClass());
#Autowired
private LeagueRepository leagueRepo;
#Autowired
private TeamRepository teamRepo;
#RequestMapping (method = RequestMethod.GET)
public String get()
{
return "/registration/start";
}
#Transactional
#RequestMapping (value = "/start", method = RequestMethod.POST)
public String hasParticipatedEarlier(#RequestParam boolean participatedInEarlierLeague, Model model)
{
if (participatedInEarlierLeague)
{
LOG.debug("Participated in earlier leagues. Retrieving the past league teams.");
Iterable<League> allLeagues = leagueRepo.findAll();
Set<League> sortedLeagues = new TreeSet<League>();
for (League l: allLeagues)
{
sortedLeagues.add(l);
}
LOG.debug("Past leagues sorted by start date {}", sortedLeagues);
model.addAttribute("pastLeagues", sortedLeagues);
}
else
{
LOG.debug("Did not participate in earlier leagues. Redirecting to register the new one.");
}
return "/registration/leagues";
}
#RequestMapping (value = "/selectTeam", method = RequestMethod.POST)
public String selectTeam(#RequestParam Long selectedTeam, Model model)
{
LOG.debug("Participated as team {} in previous league", selectedTeam);
Team team = teamRepo.findOne(selectedTeam);
model.addAttribute("team", team);
model.addAttribute("players", team.getPlayers());
return "registration/players";
}
#RequestMapping (value = "/newTeam", method = RequestMethod.POST)
public String newdTeam(#ModelAttribute Team team, Model model)
{
LOG.debug("Selected players from existing list {}", team.getPlayers());
return "registration/registrationConfirmation";
}
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Player.class, new PlayerPropertyEditor());
}
}
PlayerPropertyEditor
public class PlayerPropertyEditor extends PropertyEditorSupport
{
#Autowired
PlayerRepository playerRepo;
#Override
public String getAsText()
{
System.err.println("get as txt");
return ((Player) getValue()).getNodeId().toString();
}
#Override
public void setAsText(String incomingId) throws IllegalArgumentException
{
System.err.println(incomingId);
Player player = playerRepo.findOne(Long.valueOf(incomingId));
setValue(player);
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%# taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Players of ${team.name}</title>
</head>
<body>
<f:form action="newTeam" method="post" modelAttribute="team">
<f:checkboxes items="${players}" path="players" itemLabel="name" itemValue="nodeId" delimiter="<br/>"/>
<input type="submit" value="Submit">
</f:form>
</body>
</html>
One issue that I see is that you inject PlayerRepository inside PlayerPropertyEditor, which has no effect, since it is not in a Spring context. You should pass it through a constructor. And then inject it in the Controller
PlayerPropertyEditor
public class PlayerPropertyEditor extends PropertyEditorSupport
{
private PlayerRepository playerRepo;
public PlayerPropertyEditor(PlayerRepository playerRepo) {
this.playerRepo = playerRepo;
}
// other methods
}
inside Controller
#Autowired
private PlayerRepository playerRepo;
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Player.class, new PlayerPropertyEditor(playerRepo));
}
Secondly, and I guess that this is the main issue, is that you should override equals and hashCode for your Player class. I haven't tested that, but I rely on this answer

Resources