Registration user using JSF, JPA, how to hash password? - md5

I want to create users in database with md5 password, but I don't have idea, how to do it best. I am using JSF (+PrimeFaces) and JPA.
Pieces of code:
registration.xhml:
<p:password id="password" value="#{userBean.password}" match="repeatPassword" required="true" label="Password"> <f:validateLength minimum="8" /> </p:password>
UserBean:
#ManagedBean
#RequestScoped
public class UserBean {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void register(){
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setPassword(password);
dao.addUser(user);
}
User
#Entity
#Table(name = "users")
public class User implements Serializable {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

Related

DynamoDB NullPointerException Error on save

Im trying to save info to DynamoDB but im currently getting the error java.lang.NullPointerException: null when using "save" on the AccountHelper class.
I followed the starter guide found on Github; https://github.com/derjust/spring-data-dynamodb
Here is my Model Class;
#DynamoDBTable(tableName = "Users")
public class User {
// #Id
private String _id;
private String bloodGroup;
private String firstName; // DO NOT change this, needs to stay firstName
private String surname;
private String email;
private String password;
private String addressline;
private String postcode;
private String latitude;
private String longitude;
public User() {}
// More Constructors, Getters & Setters
DynamoDB Config Class;
#EnableDynamoDBRepositories(includeFilters = {#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {DynamoDBRepo.class})})
#Configuration
public class DynamoDBConfig {
#Value("${amazon.aws.accesskey}")
private String amazonAWSAccessKey;
#Value("${amazon.aws.secretkey}")
private String amazonAWSSecretKey;
public AWSCredentialsProvider amazonAWSCredentialsProvider() {
return new AWSStaticCredentialsProvider(amazonAWSCredentials());
}
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
#Primary
#Bean
public DynamoDBMapperConfig dynamoDBMapperConfig() {
return DynamoDBMapperConfig.DEFAULT;
}
#Bean
public DynamoDBMapper dynamoDBMapper(AmazonDynamoDB amazonDynamoDB, DynamoDBMapperConfig config) {
return new DynamoDBMapper(amazonDynamoDB, config);
}
#Bean
public AmazonDynamoDB amazonDynamoDB() {
return AmazonDynamoDBClientBuilder.standard().withCredentials(amazonAWSCredentialsProvider())
.withRegion(Regions.US_EAST_1).build();
}
}
Here is the method/class where i am getting the error;
#Service
public class AccountHelper {
private DynamoDBRepo dynamoDBRepo;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public User create(String bloodGroup, String firstname, String surname, String email, String password, String addressline, String postcode) {
// Getting the error here
return dynamoDBRepo.save(new User(bloodGroup, firstname, surname, email, bCryptPasswordEncoder.encode(password), addressline, postcode));
}
// More methods below that i am not adding to keep this question to a minimum.
Here is my controller;
#Controller
#Component
public class AccountController {
#Autowired
private AccountHelper Service_functions;
#ResponseBody // Works
#PostMapping(value = "/create/{bloodGroup}/{firstname}/{surname}/{email}/{password}/{addressline}/{postcode}")
public String create( #PathVariable String bloodGroup , #PathVariable String firstname, #PathVariable String surname, #PathVariable String email, #PathVariable String password, #PathVariable String addressline, #PathVariable String postcode){
User CreateUser = Service_functions.create(bloodGroup, firstname, surname, email, password, addressline, postcode);
System.out.println("this is working");
return CreateUser.toString();
}
account properties;
spring.application.name=account-service
server.port=8020
eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
amazon.aws.accesskey="" // i removed the keys
amazon.aws.secretkey=""
Any Suggestions/Help would be greatly on where i am going wrong.
Two things you need to fix here based on your details provided.
Add #Autowired annotation on your dynamoDBRepo variable so that it can be recognised as spring managed bean.
Based on your comment
i.e. error saying that it cannot find
com.bdonor.accountservice.Repository.DynamoDBRepo
You need to include com.bdonor.accountservice.Repository package as JPA repository package and enable jpa repository scan in your configuration.

Solr 7 with Spring data and basic authentication not working

#SpringBootApplication
public class SpringDataSolarApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataSolarApplication.class, args);
}
#Bean
SolrTemplate solrTemplate() {
return new SolrTemplate(solrClientFactory());
}
#Bean
SolrClientFactory solrClientFactory() {
Credentials credentials = new UsernamePasswordCredentials("solr", "SolrRocks");
return new HttpSolrClientFactory(solrClient(), credentials , "BASIC");
}
#Bean
SolrClient solrClient() {
return new HttpSolrClient.Builder("http://localhost:8983/solr").build();
}
}
public interface EmployeeRepository extends SolrCrudRepository{
Employee findByName(String name);
}
#RestController
public class EmployeeController {
#Autowired
private EmployeeRepository repository;
#PostConstruct
public void addEmployees() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("373", "Basant", new String[] { "Bangalore", "BTM" }));
employees.add(new Employee("908", "Santosh", new String[] { "Hyderbad", "XYZ" }));
employees.add(new Employee("321", "Sagar", new String[] { "Pune", "PQR" }));
repository.saveAll(employees);
}
#GetMapping("/getALL")
public Iterable<Employee> getEmployees() {
return repository.findAll();
}
#GetMapping("/getEmployee/{name}")
public Employee getEmployeeByName(#PathVariable String name) {
return repository.findByName(name);
}
}
the getALL operation is working fine but the save operation failed with this error. Please help
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:225) ~[httpclient-4.5.7.jar:4.5.7]
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185) ~[httpclient-4.5.7.jar:4.5.7]
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) ~[httpclient-4.5.7.jar:4.5.7]
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) ~[httpclient-4.5.7.jar:4.5.7]
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) ~[httpclient-4.5.7.jar:4.5.7]
... 63 common frames omitted
Came across same issue and solved with extending HttpSolrClient and applying same backend approach with recommended way mentioned on Solr docs but getting credentials from constructor not setting on each request.
class CustomSolrClient extends HttpSolrClient {
#Nullable
private final String username;
#Nullable
private final String password;
CustomSolrClient(Builder builder, String username, String password) {
super(builder);
this.username = username;
this.password = password;
}
#Override
public NamedList<Object> request(SolrRequest request, ResponseParser processor, String collection) throws SolrServerException, IOException {
HttpRequestBase method = createMethod(request, collection);
if (username != null && password != null) {
String userPass = username + ":" + password;
String encoded = Base64.byteArrayToBase64(userPass.getBytes(UTF_8));
method.setHeader(new BasicHeader("Authorization", "Basic " + encoded));
}
return executeMethod(method, processor, request instanceof V2Request || request.getPath().contains("/____v2"));
}
}
And create bean using that:
#Bean
public SolrClient solrClient() {
return new CustomSolrClient(new HttpSolrClient.Builder(properties.getHost()), properties.getUsername(), properties.getPassword());
}
This may seem as an ugly approach but if you check HttpSolrClientFactory sources it's even more uglier which actually accesses private field of HttpClient belongs to Solr client.

Azure AD B2C with Graph API - how to get/set user's email?

I add users to Azure AD B2C with Graph API but I don't get it how to store users' email (the primary one). Which field here is the user's primary email address?
As I read here on SO there's no way to populate values in Authentication contact info. It this correct?
Here's how I do it:
public async Task<AdUser> GetUserByObjectId(Guid objectId)
{
string userJson = await SendGraphGetRequest("/users/" + objectId, null);
JObject jUser = JObject.Parse(userJson);
return new AdUser(jUser);
}
internal AdUser(JObject jUser)
{
AccountEnabled = jUser["accountEnabled"].Value<bool>();
CompanyName = jUser["companyName"].Value<string>();
Department = jUser["department"].Value<string>();
DisplayName = jUser["displayName"].Value<string>();
FirstName = jUser["givenName"].Value<string>();
JobTitle = jUser["jobTitle"].Value<string>();
LastName = jUser["surname"].Value<string>();
MailNickname = jUser["mailNickname"].Value<string>();
Mobile = jUser["mobile"].Value<string>();
ObjectId = new Guid(jUser["objectId"].Value<string>());
List<string> mailList = new List<string>(jUser["otherMails"].Count());
mailList.AddRange(jUser["otherMails"].Select(mail => mail.Value<string>()));
OtherMails = mailList.AsReadOnly();
Phone = jUser["telephoneNumber"].Value<string>();
List<(string type, string value)> signInNames = jUser["signInNames"].Select(jToken => (jToken["type"].Value<string>(), jToken["value"].Value<string>())).ToList();
SignInNames = signInNames.AsReadOnly();
UserPrincipalName = jUser["userPrincipalName"].Value<string>();
UserType = jUser["userType"].Value<string>();
}
and here's the Email property of the AdUser:
public string Email
{
get
{
if (SignInNames.Count > 0 && SignInNames[0].type == "emailAddress")
return SignInNames[0].value;
if (OtherMails.Count > 0)
return OtherMails[0];
throw new InvalidOperationException("Don't know where to get user Email");
}
}
You need to make a PATCH request to the users endpoint
{baseurl}/{tenantId}/users?api-version={apiVersion}
Don't forget you access token in the auth header:
Authorization: Bearer {accessToken}
Here's an example model (Java) with methods for calculating and setting the sign-in email on a user object:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
#JsonIgnoreProperties(ignoreUnknown = true)
public class GraphApiUserExample{
#JsonProperty("objectId")
private String id;
private Boolean accountEnabled;
private PasswordProfile PasswordProfile;
private List<SignInName> signInNames;
private String surname;
private String displayName;
private String givenName;
#JsonProperty("userPrincipalName")
private String userPrincipalName;
public String getId(){
return id;
}
public void setId(final String id){
this.id = id;
}
public Boolean getAccountEnabled(){
return accountEnabled;
}
public void setAccountEnabled(final Boolean accountEnabled){
this.accountEnabled = accountEnabled;
}
public PasswordProfile getPasswordProfile(){
return passwordProfile;
}
public void setPasswordProfile(final PasswordProfile passwordProfile){
this.passwordProfile = passwordProfile;
}
public List<SignInName> getSignInNames(){
return signInNames;
}
public void setSignInNames(final List<SignInName> signInNames){
this.signInNames = signInNames;
}
public String getSurname(){
return surname;
}
public void setSurname(final String surname){
this.surname = surname;
}
public String getDisplayName(){
return displayName;
}
public void setDisplayName(final String displayName){
this.displayName = displayName;
}
public String getGivenName(){
return givenName;
}
public void setGivenName(final String givenName){
this.givenName = givenName;
}
public String getUserPrincipalName(){
return userPrincipalName;
}
public void setUserPrincipalName(final String userPrincipalName){
this.userPrincipalName = userPrincipalName;
}
#JsonIgnore
public String getSignInEmail(){
String email = "";
if(signInNames != null){
for(SignInName signInName : signInNames){
if(signInName.getType().equals("emailAddress")){
email = signInName.getValue();
break;
}
}
}
return email;
}
#JsonIgnore
public void setSignInEmail(String signInEmail){
if(signInNames == null){
signInNames = new ArrayList<>();
signInNames.add(new SignInName("emailAddress", signInEmail));
return;
}
for(SignInName signInName : signInNames){
if(signInName.getType().equals("emailAddress")){
signInName.setValue(signInEmail);
break;
}
}
}
}
SignInName:
public class SignInName {//userName or emailAddress
private String
type,
value;
public String getType(){
return type;
}
public void setType(final String type){
this.type = type;
}
public String getValue(){
return value;
}
public void setValue(final String value){
this.value = value;
}
}
PasswordProfile:
#JsonIgnoreProperties(ignoreUnknown = true)
public class PasswordProfile {
private String password;
private Boolean forceChangePasswordNextLogin;
public String getPassword(){
return password;
}
public void setPassword(final String password){
this.password = password;
}
public Boolean getForceChangePasswordNextLogin(){
return forceChangePasswordNextLogin;
}
public void setForceChangePasswordNextLogin(final Boolean forceChangePasswordNextLogin){
this.forceChangePasswordNextLogin = forceChangePasswordNextLogin;
}
}

Persisted objects overwrite the last record instead of creating a new one with Spring MVC, Google App Engine, JDO3

I'm using Spring MVC 3.1.2 with Google App Engine. I have a problem with persisting objects in the data store using JDO3. The weird problem is that whenever I persist objects (during a short period of time) the last added object doesn't get persisted in a new record it just overwrites the last record keeping the same id (the id of the last record). Here are the files that could be concerned.
User.java
#Component
#PersistenceCapable
public class User {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
private String firstName;
#Persistent
private String lastName;
#Persistent
private String email;
#Persistent
private String password;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDaoImpl.java
#Repository
public class UserDaoImpl implements UserDao {
private static PersistenceManager pm;
#Override
public void add(User user) {
if (pm == null || pm.isClosed()) {
pm = PMF.get().getPersistenceManager();
}
try {
pm.makePersistent(user);
} finally {
pm.close();
}
}
}
PMF.java
public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF() {}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
UserController.java
#Controller
public class UserController {
#Autowired
UserService userService;
#Autowired
User user;
#RequestMapping(value="/adduser", method=RequestMethod.GET)
String adduser(){
return "adduser";
}
#RequestMapping(value="/adduser.do", method=RequestMethod.POST)
String saveUserr(#RequestParam String firstname,#RequestParam String lastname, #RequestParam String email, #RequestParam String password){
this.user.setFirstName(firstname);
this.user.setLastName(lastname);
this.user.setEmail(email);
this.user.setPassword(password);
userService.add(user);//this invokes the UseDaoImpl add(user)
}
}
jdoconfig.xml
<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig_3_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig http://java.sun.com/xml/ns/jdo/jdoconfig_3_0.xsd">
<persistence-manager-factory name="transactions-optional">
<property name="javax.jdo.PersistenceManagerFactoryClass"
value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="appengine"/>
<property name="javax.jdo.option.NontransactionalRead" value="true"/>
<property name="javax.jdo.option.NontransactionalWrite" value="true"/>
<property name="javax.jdo.option.RetainValues" value="true"/>
<property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
<property name="datanucleus.appengine.singletonPMFForName" value="true"/>
</persistence-manager-factory>
</jdoconfig>
What I feel is you are not initializing the User Object, instead of Autowired annotation try the following code.
#RequestMapping(value="/adduser.do", method=RequestMethod.POST)
String saveUser(#RequestParam String firstname,#RequestParam String lastname, #RequestParam String email, #RequestParam String password){
User user = new User();
user.setFirstName(firstname);
user.setLastName(lastname);
user.setEmail(email);
user.setPassword(password);
userService.add(user);//this invokes the UseDaoImpl add(user)
}

Children are not fetch with Parent in jdo

i am using gwt with jdo datanucleus. i have requirement to get child with parent. but i am not getting child when access parent.
my code is as following
my parent class is
#PersistenceCapable(identityType = IdentityType.APPLICATION, table = "user")
public class User implements Serializable {
private static final long serialVersionUID = 2660867968471555842L;
#PrimaryKey
#Persistent
private String email;
#Persistent(defaultFetchGroup = "true",mappedBy="user")
private UserProfile profile;
public User() {}
public User(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public UserProfile getProfile() {
return profile;
}
public void setProfile(UserProfile profile) {
this.profile = profile;
}
}
and my child class is
#PersistenceCapable(identityType = IdentityType.APPLICATION,table = "user_profile")
public class UserProfile implements Serializable {
private static final long serialVersionUID = -6818036410894395030L;
#PrimaryKey
#Persistent(defaultFetchGroup="true")
private User user;
#Persistent
private String name;
public UserProfile() {}
public UserProfile(User user) {
this.user = user;
user.setProfile(this);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
i am fetching data by following query
PersistenceManager pm = PMF.get().getPersistenceManager();
User user=null;
try{
String userId ="abc#abc.com";
Query userQuery = pm.newQuery(User.class);
userQuery.setFilter("email == '" + userId + "'");
userQuery.setUnique(true);
user = (User) userQuery.execute();
} catch (Exception e) {
throw new IllegalAccessError("Failed to get the User..");
}finally{
pm.close();
}
but i am getting userprofile null in object user.
where is the problem ?
how to load children with parent ?
I'm not sure if you found your answer, but for those that stumble across this I just wanted to share how I got it working.
#PersistenceCapable(detachable = "true")
#FetchGroup(name = "fooGroup", members = { #Persistent(name = "list") })
public class ParentClass {
#Persistent(mappedBy = "parent")
#Element(dependent = "true") //can not exist without parent
private List<ChildClass> list;
}
#PersistenceCapable(detachable = "true")
public class ChildClass {
#Persistent
private ParentClass parent;
}
and then to do the fetching:
PersistenceManager pm = PMF.get("eventual-reads-shortdeadlines").getPersistenceManager();
pm.setDetachAllOnCommit(true);
pm.getFetchPlan().addGroup("fooGroup");
Transaction tx = pm.currentTransaction();
try {
tx.begin();
Query query = pm.newQuery(ParentClass.class);
list = (List<ParentClass>) query.execute();
tx.commit();
} catch (Exception ex) {
...
} finally {
if (pm != null) {
if(pm.currentTransaction().isActive()){
pm.currentTransaction().rollback();
}
pm.close();
}
}
Your ParentClass's should now have all the ChildClass's for each. Hope that helps!

Resources