Spring MongoDB mongoOperations.exists(query, User.class) some problems - spring

In my project https://github.com/thomas-meyer-57647/Hurricane
I have encountered a few problems for which I have not found any solutions.
#Indexd(unique=true)
I use in my model in different places e.g. https://github.com/thomas-meyer-57647/Hurricane/blob/main/Hurricane/src/main/java/com/tmt/hurricane/user/model/User.java #Indexd(unique=true) this seems not to work.
For this reason, I am currently forced in the associated service class https://github.com/thomas-meyer-57647/Hurricane/blob/main/Hurricane/src/main/java/com/tmt/hurricane/user/service/UserService.java in the function public User createUser(User creator, User user) use the following line alternative
if ( existsUserByEmail(user.getEmail()) )
throw new DuplicateException("UserService::createUser(" + creator + ", " + user + "): EMail (" + user.getEmail() + ") allready exists");
to use
2
. mongoOperations.exists(query, User.class)
The function mongoOperations.exists(query, User.class) of von https://github.com/thomas-meyer-57647/Hurricane/blob/main/Hurricane/src/main/java/com/tmt/hurricane/user/service/UserService.java
does not seem to work correctly, because e.g. the associated test UserServiceTest.java https://github.com/thomas-meyer-57647/Hurricane/tree/main/Hurricane/src/test/java/com/tmt/hurricane/user/service in the function testExistsUserByEmail() at line 1326 it fails, instead of true, because the above mongoOperations.exists(query, User.class) returns false instead of true.
In the class CountryService https://github.com/thomas-meyer-57647/Hurricane/blob/main/Hurricane/src/main/java/com/tmt/hurricane/country/service/CountryService.java in the function existsCountryByNameOrCode the commented out query would not work, for this reason this place is currently still replaced as
return this.existsCountryByName(country_name) || this.existsCountryByCode(code);
Anyone suggestions for correcting these problems? Any comments?

Related

How to store id generated by post rest assured

I'm trying to get the id generated when I make the post and use it in the future (maybe when testing the delete), but I'm not getting it.
My method that tests POST:
#Test
public void givenData_WhenPost_Then200() throws Exception {
String path = given()
.body("{\r\n"
+ " \"nome\":\"teste\",\r\n"
+ " \"valor\": 2.5\r\n"
+ "}")
.contentType(ContentType.JSON)
.when()
.post("/acessorios")
.then()
.log().all()
.assertThat()
.statusCode(200).extract().jsonPath().getString("nome");
System.out.println(path);
}
This code returns:
Failed to parse the JSON document.
And at last: is possible to use the id generate in others methods even its not global?
If you'd like to use id from response in other tests, you can create static field id in the test class and assign value of response.jsonPath.getString("id");
The first thing you need to do is to make sure response is actually in json format.
You can add accept header in your chain of methods like:
String path = given()
.body("{\r\n"
+ " \"nome\":\"teste\",\r\n"
+ " \"valor\": 2.5\r\n"
+ "}")
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.when()
.post("/acessorios")
.then()
.log().all()
.assertThat()
.statusCode(200).extract().jsonPath().getString("$.id");

I want to know about spring hateoas

I am working on spring boot. I don't know what is spring hateoas why we go for spring hateoas.
#RequestMapping(value= "/accounts/{id}/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Resource<AccountHolder> findAccountHolderById(#PathVariable("id") Long id, #PathVariable("userId") int i) {
logger.info("accounts findAccountHolderById() invoked: " + id);
Account account = accountRepository.getAccount(id.toString());
AccountHolder accountHolder = account.getAccountHolder();
Resource<AccountHolder> resource = new Resource<AccountHolder>(accountHolder);
resource.add(linkTo(methodOn(AccountController.class).byId(account.getAccountId())).withRel("account"));
logger.info("accounts findAccountHolderById() found: " + account);
return resource;
}
HATEOAS means that a REST webservice not only provides the answer you asked for (e.g. the account) but also links to related data like the customer or subaccounts of that account. You can also provide links to actions like "disable account". That way the clients can navigate through the data more easily.
See https://spring.io/understanding/HATEOAS or https://en.wikipedia.org/wiki/HATEOAS
P.S.: When copy & pasting code, use the "{}" symbol in the edit box to format it correctly.

Kinvey-Xamarin: How to recieve Data from a User instance?

I'm working on a Kinvey project right now, and I'm having some Problems with reading the Username or special Attributes from a User instance. I first tried it the same way getting _User.ID by calling _User.UserName, but this didnt return anything(But ID did curiously). I also searched on Google, but there weren't any articles about it. Hope you can help, would be greatly appreciated!
For special attributes, use the .Attributes array on the User class.
Like this code:
Console.WriteLine ("custom attribute is: " + kinveyClient.User ().Attributes["myAttribute"]);
For username, try .UserName() but it seems you must do an explicit retrieval of the User object before this field is populated
User retrieved;
try {
retrieved = await kinveyClient.User().RetrieveAsync();
} catch (Exception e) {
Console.WriteLine("{0} caught exception: ", e);
retrieved = null;
}
Console.WriteLine ("logged in as: " + retrieved.Username );
Console.WriteLine ("custom attribute is: " + retrieved.Attributes["myAttribute"]);
Documentation: http://devcenter.kinvey.com/xamarin/guides/users#UserClass
(answer applies to SDK version 1.6.11)

Spring's LdapTemplate search: PartialResultException: Unprocessed Continuation Reference(s); remaining name '/'

I add users through LDAP for a certain application, made with spring.
While this works for most of the cases, in some cases, it does not work...
The retrieve the users I use:
public class LdapUserServiceImpl implements ILdapUserService {
#Override
public List<LdapUserVO> getUserNamesByQuery(String query) {
return ldapTemplate.search(
query().countLimit(15)
.where("objectClass").is("user")
.and("sAMAccountName").isPresent()
.and(query()
.where("sAMAccountName").like("*" + query + "*")
.or("sAMAccountName").is(query)
.or("displayName").like("*" + query + "*")
.or("displayName").is(query))
,
new AttributesMapper<LdapUserVO>() {
public LdapUserVO mapFromAttributes(Attributes attrs) throws NamingException {
LdapUserVO ldapUser = new LdapUserVO();
Attribute attr = attrs.get(ldapUserSearch);
if (attr != null && attr.get() != null) {
ldapUser.setUserName(attr.get().toString());
}
attr = attrs.get("displayName");
if (attr != null && attr.get() != null) {
ldapUser.setDisplayName(attr.get().toString());
}
return ldapUser;
}
});
}
}
So this works in most of the cases, but sometimes I get the following error:
unprocessed continuation reference(s); remaining name "/"
I've searched a lot about this, and I explicitly set
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(ldapUrl);
ctxSrc.setReferral("follow");
Some more info:
Search-query "admin_a" works, but "admin_ah" does not
Spring version is 4.2.5.RELEASE
Spring ldap-core version is 2.0.2.RELEASE
I think it strange that the remaining name is the root directory... Does someone has any ideas how to fix this, or even where to start looking?
Thanks in advance!
This may be related with the Active Directory being unable to handle referrals automatically. Please take a look at the LdapTemplate javadoc.
If this is the case, set the ignorePartialResultException property to true in your ldapTemplate configuration.
The reason for this error in my case was that the structure of the new AD had changed (userPrincipleName was now the emailaddress instead of login). Because of this the authentication to the AD worked fine, but no entry could be found that matched the filter, and as such didn't return any result.
So the PartialResultException was only an indication, not the reason. the reason is the lack of any result in the method searchForSingleEntryInternal of the SpringSecurityLdapTemplate class.
In my case, I had to make sure I used the correct userPrincipleName and configure the correct domain and baseDN in my ActiveDirectoryLdapAuthenticationProvider.

Can I switch use of 'entities.SingleOrDefault' ==> 'entities.Find' without hazards?

In my WCF service's business logic, most of the places when I need to locate an entity, I use this syntax:
public void UpdateUser(Guid userId, String notes)
{
using (ProjEntities entities = new ProjEntities())
{
User currUser = entities.SingleOrDefault(us => us.Id == userId);
if (currUser == null)
throw new Exception("User with ID " + userId + " was not found");
}
}
I have recentely discovered that the DbContext has the Find method, and I understand I can now do this:
public void UpdateUser(Guid userId, String notes)
{
using (ProjEntities entities = new ProjEntities())
{
User currUser = entities.Find(userId);
if (currUser == null)
throw new Exception("User with ID " + userId + " was not found");
}
}
Note : the 'userId' property is the primary key for the table.
I read that when using Find method entity framework checks first to see if the entity is already in the local memory, and if so - brings it from there. Otherwise - a trip is made to the database (vs. SingleOrDefault which always makes a trip to the database).
I was wondering if I now will convert all my uses of SingleOrDefault to Find is there any potential of danger?
Is there a chance I could get some old data that has not been updated if I use Find and it fetches the data from memory instead of the database?
What happens if I have the user in memory, and someone changed the user in the database - won't it be a problem if I always use now this 'memory' replica instead of always fetching the latest updated one from the database?
Is there a chance I could get some old data that has not been updated
if I use Find and it fetches the data from memory instead of the
database?
I think you have sort of answered your own question here. Yes, there is a chance that using Find you could end up having an entity returned that is out of sync with your database because your context has a local copy.
There isn't much more anyone can tell you without knowing more about your specific application; do you keep a context alive for a long time or do you open it, do your updates and close it? obviously, the longer you keep your context around the more susceptible you are to retrieving an up to date entity.
I can think of two strategies for dealing with this. The first is outlined above; open your context, do what you need and then dispose of it:
using (var ctx = new MyContext())
{
var entity = ctx.EntitySet.Find(123);
// Do something with your entity here...
ctx.SaveChanges();
}
Secondly, you could retrieve the DbEntityEntry for your entity and use the GetDatabaseValues method to update it with the values from the database. Something like this:
var entity = ctx.EntitySet.Find(123);
// This could be a cached version so ensure it is up to date.
var entry = ctx.Entry(entity);
entry.OriginalValues.SetValues(entry.GetDatabaseValues());

Resources