Realm java nested query on same ArrayObject - realm

Current code:
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email", a#a.com, Case.INSENSITIVE)
.equalTo("checklistParticipants.type", 0)
.findAll();
which returns me result of similar to ANY record.
I want to check in nested query, only return record if and if both condition fulfilled. likewise in nested query, record email must be a#a.com and type=0
i tried below approach but ended up in same result.
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.findAll()
.where()
.equalTo("checklistParticipants.type", 0)
.findAll();
Below screenshot shows 2 child items,
email= a#a.com & type = 1
email= x#x.com & type = 0
Realm checking for both value in either-or approach.
Also tried:
mRealm.where(AdditionalData.class)
.equalTo("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.and()
.equalTo("checklistParticipants.type", 0)
.findAll()
classpath "io.realm:realm-gradle-plugin:5.8.0"
UPDATE
class AdditionalData {
String name;
RealmList<ChecklistParticipants> checklistParticipants;
}
class ChecklistParticipants{
String email;
String type;
String field3;
}

as #EpicPandaForce said you need to use LinkingObjects
class AdditionalData {
String name;
#LinkingObjects(ChecklistParticipants.rlAdditionalData)
final RealmResults<ChecklistParticipants> linkedChecklistParticipants = null;
public RealmResults<RealmDocumentLines> getLinkedChecklistParticipants() {
return linkedChecklistParticipants ;
}
}
ChecklistParticipants
class ChecklistParticipants{
String email;
String type;
String field3;
AdditionalData rlAdditionalData;
public AdditionalData getAdditionalData() {
return rlAdditionalData;
}
public void setAdditionalData(AdditionalData additionalData) {
this.rlAdditionalData = additionalData ;
}
}
Then query
RealmResult<ChecklistParticipants> result = mRealm.where(ChecklistParticipants.class)
.contains("email", a#a.com, Case.INSENSITIVE)
.equalTo("type", 0)
.findAll();
then loop over the result and use getAdditionalData() from each item

Related

WebFlux returning http.okay vice http.notFound

New to WebFlux, reactive, and handlers. I've got things "working", but am not understanding why following code is returning "okay" with empty body, vice "not found".
Clarification: The issue-of-concern is in the final return statement of DemoPOJOHandler.getById(). The "short-circuit" code works as expected (i.e., returns "Bad Request" status), but the "switchIfEmpty" path of the final return statement does not appear to get exercised if a DemoPOJORepo.getById(int) returns Mono.empty().
(Note: I've hacked up a list-based "repo" to avoid dealing with database while figuring out handlers and http return types.)
Router implementation ("/v1" is a set of annotation based RESTful endpoints)...
#Configuration
public class DemoPOJORouter {
#Bean
public RouterFunction<ServerResponse> route(DemoPOJOHandler requestHandler) {
return nest(path("/v2"),
nest(accept(APPLICATION_JSON),
RouterFunctions.route(RequestPredicates.GET("/DemoPOJO"), requestHandler::getAll)
.andRoute(RequestPredicates.GET("/DemoPOJO/{id}"), requestHandler::getById)
.andRoute(RequestPredicates.POST("/DemoPOJO"), requestHandler::add)));
}
}
Handler implementation has been "stripped down" to only the code in question. I have a feeling that much of the style is "still imperative", but I've attempted to put the reactive stuff where it "makes the most sense".
If I supply a bad value on the URI (i.e., "foo"), then I get the http "bad request" returned. But, never seem to get the "not found" that should be generated by "switchIfEmpty" if a validly formatted int value is supplied, but it does not map to an entry in the repo.
#Component
public class DemoPOJOHandler {
public static final String PATH_VAR_ID = "id";
private DemoPOJORepo repo = null;
public Mono<ServerResponse> getById(ServerRequest request) {
Mono<DemoPOJO> monoDemoPOJO = null;
Map<String, String> pathVariables = request.pathVariables();
int id = -1;
checkRepoRef(); // part of the list hack
// short-circuit if request doesn't contain id (should never happen)
if ((pathVariables == null)
|| (!pathVariables.containsKey(PATH_VAR_ID))) {
return ServerResponse.badRequest().build();
}
// short-circuit if bad id value
try {
id = Integer.parseInt(pathVariables.get(PATH_VAR_ID));
} catch(NumberFormatException e) {
return ServerResponse.badRequest().build();
}
// get entity by keyValue
monoDemoPOJO = repo.getById(id);
return monoDemoPOJO
.flatMap(demoPOJO -> ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.syncBody(demoPOJO)
.switchIfEmpty(ServerResponse.notFound().build()));
}
}
Hack of a list-based repo to avoid dealing with data/APIs while working on handlers and http return types.
// local hack to avoid a database for testing
public class DemoPOJORepo {
private static DemoPOJORepo fpRepo = null;
private static int NUM_ROWS = 100;
private Map<Integer, DemoPOJO> fooPOJOMap;
private DemoPOJORepo() {
initMap();
}
public static DemoPOJORepo getInstance() {
if (fpRepo == null) {
fpRepo = new DemoPOJORepo();
}
return fpRepo;
}
public Mono<DemoPOJO> getById(int id) {
Mono<DemoPOJO> monoDP;
if (fooPOJOMap.containsKey(id)) {
monoDP = Mono.just(fooPOJOMap.get(id));
} else {
monoDP = Mono.empty();
}
return monoDP;
}
private Mono<Void> initMap() {
fooPOJOMap = new TreeMap<Integer, DemoPOJO>();
int offset = -1;
for(int ndx=0; ndx<NUM_ROWS; ndx++) {
offset = ndx + 1;
fooPOJOMap.put(offset, new DemoPOJO(offset, "foo_" + offset, offset+100));
}
return Mono.empty();
}
}
Your brackets are in the wrong place causing the swithIfEmpy to apply to the ServerResponse.ok() publisher not the monoDemoPOJO, replace the return with this and it should work:
return monoDemoPOJO
.flatMap(demoPOJO -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).syncBody(demoPOJO))
.switchIfEmpty(ServerResponse.notFound().build());
As I can see the code is right. The response code is Bad request because you are trying to convert "foo" to Integer, and when it throws an exception you are returning a Bad request response, so I think it works perfectly fine.
If you use an Integer id that is not present in your database then the answer must be a not found response

Custom get and set on attribute

I am trying to setup a product key system in my application, but I want to ensure the attribute has the right size (16 characters).
I tried the following
public class ProductKey
{
public const int ProductKeyLength = 16;
[StringLength(ProductKeyLength, MinimumLength = ProductKeyLength)]
private string _value;
[Required]
[Index(IsUnique = true)]
public string Value {
get
{
var temp = Regex.Replace(this._value, ".{4}", "$0-");
return temp.Trim('-');
}
set { this._value = value.Replace("-", "");}
}
}
I want to enable the user to insert the key with our without hyphen. I get the following error with above code:
Column 'Value' in table 'dbo.ProductKeys' is of a type that is invalid for use as a key column in an index.
As I understood, I need to set a limit to Value so it can be used as a unique key. But, _value has a limit and _value is the actual representation of Value in the database.
Is there a way to set the limit correctly in this case?
Thanks in advance.
You are getting the error because without a StringLength attribute on the Value field, the database column gets created as VARCHAR(MAX) which cannot be used as a key. You need a [StringLength] on the field being used as a key. However, as your getter is returning the key formatted with dashes, you need the key length to be 19:
public class ProductKey
{
public const int ProductKeyLength = 19;
private string _value { get; set; }
[Key]
[Required]
[StringLength(ProductKeyLength, MinimumLength = ProductKeyLength)]
[Index(IsUnique = true)]
public string Value
{
get
{
var temp = Regex.Replace(this._value, ".{4}", "$0-");
return temp.Trim('-');
}
set { this._value = value.Replace("-", ""); }
}
}
You might be better off doing your format conversion in ViewModels and client-side code, as one problem you'll have here is searching - for example...
db.Keys.Add(new ProductKey { Value = "1234-5678-9012-3456" });
db.Keys.Add(new ProductKey { Value = "1234567890123455" });
db.SaveChanges();
Console.WriteLine(db.Keys.Count(k => k.Value.Contains("89"))); // 0
Console.WriteLine(db.Keys.Count(k => k.Value.Contains("8-9"))); // 2

aop.AopInvocationException: Null return value from

here is the repository:
#Query(value = "select u.balance from User u where u.name=:name")
float toGetBalance(#Param("name") String name);
and here is the DAO interface:
boolean checkBalance(String userName, float totalPrice);
and here is the service
#Transactional(readOnly = true)
#Override
public boolean checkBalance(String userName, float totalPrice) {
if (userRepository.toGetBalance(userName) < totalPrice) {
return false;
} else {
return true;
}
}
and here is the error info:
org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)
and the type of balance is float!
what's wrong?
Change the signature of your repository to
#Query(value = "select u.balance from User u where u.name=:name")
Float toGetBalance(#Param("name") String name);
And it will simply return null if there is no such user in database with given name
#Query(value = "select u.balance from User u where u.name=:name")'
'Float toGetBalance(#Param("name") String name);
This exception arise because name not exist OR balance = NULL fpr the selected record in the table
So the query results no output. Spring JPA not able to bind the result with Return type Float.
Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)

How to serialize dynamic field names using JSON parser

I am using JSON.Net to serialize my objects. For eg, if this is my object
Class MainData
{
[JsonProperty("keyValues")]
string val;
}
the data for 'val' is a key value pair string like this key1:value1.
I have a scenario where I should not get the above 'keyValues' name in my final serialized string and instead get a serialized string which looks like this
{
"key1":"value1"
}
Currently with my serializer I am getting this, which is not what I need
{
"keyValues":"key:value1"
}
Can somebody guide me to any documentation/solution to dynamically assign the name of the field instead of using the default variable name/JSONProperty Name defined inside the object?
Thanks a lot in advance.
I've been struggling with this all day, what I've done is used a dictionary object and serialised this
however I had an error message that was "cannot serialise dictionary", should have read the whole message, "cannot serialise dictionary when the key is not a string or object"
this now works for me and gives me a key/value pair
i have the following objects
public class Meal {
public int mealId;
public int value;
public Meal(int MealId, int Value) {
mealId = MealId;
value = Value;
} }
public class Crew
{
public Meal[] AllocatedMeals {
get {
return new Meal[]{
new Meal(1085, 2),
new Meal(1086, 1) }; } }
public int AllocatedMealTotal {
get {
return this.AllocatedMeals.Sum(x => x.value); } }
}
then the following code
Dictionary<string,string> MealsAllocated = crew.AllocatedMeals.ToDictionary(x => x.mealId.ToString(), x => x.value.ToString());
return new JavaScriptSerializer().Serialize(
new {
Allocated = new {
Total = crew.AllocatedMealTotal,
Values = MealsAllocated } )
to get
"Allocated":{"Total":3,"Values":{"1085":"2","1086":"1"}}

C# check value exist in constant

I have declared my c# application constant this way:
public class Constant
public struct profession
{
public const string STUDENT = "Student";
public const string WORKING_PROFESSIONAL = "Working Professional";
public const string OTHERS = "Others";
}
public struct gender
{
public const string MALE = "M";
public const string FEMALE = "F";
}
}
My validation function:
public static bool isWithinAllowedSelection(string strValueToCheck, object constantClass)
{
//convert object to struct
//loop thru all const in struct
//if strValueToCheck matches any of the value in struct, return true
//end of loop
//return false
}
During runtime, I will like pass in the user inputted value and the struct to check if the value exist in the struct. The struct can be profession and gender. How can I achieve it?
Example:
if(!isWithinAllowedSelection(strInput,Constant.profession)){
response.write("invalid profession");
}
if(!isWithinAllowedSelection(strInput,Constant.gender)){
response.write("invalid gender");
}
You probably want to use enums, not structs with constants.
Enums gives you a lot of possibilities, it is not so hard to use its string values to save it to the database etc.
public enum Profession
{
Student,
WorkingProfessional,
Others
}
And now:
To check existence of value in Profession by value's name:
var result = Enum.IsDefined(typeof(Profession), "Retired"));
// result == false
To get value of an enum as a string:
var result = Enum.GetName(typeof(Profession), Profession.Student));
// result == "Student"
If you really can't avoid using value names with whitespaces or other special characters, you can use DescriptionAttribute:
public enum Profession
{
Student,
[Description("Working Professional")] WorkingProfessional,
[Description("All others...")] Others
}
And now, to get description from Profession value you can use this code (implemented here as an extension method):
public static string Description(this Enum e)
{
var members = e.GetType().GetMember(e.ToString());
if (members != null && members.Length != 0)
{
var attrs = members.First()
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length != 0)
return ((DescriptionAttribute) attrs.First()).Description;
}
return e.ToString();
}
This method fetches description defined in attribute and if there's none, returns value name. Usage:
var e = Profession.WorkingProfessional;
var result = e.Description();
// result == "Working Professional";

Resources