I get the following error Operator '==' cannot be applied to operands of type 'int' and 'string' password == "55555" is marked as an error - operator-keyword

namespace if4
{
class Program
{
static void Main(string[] args)
{
string username;
int password = new int();
string userValue;
userValue = Console.ReadLine();
Console.WriteLine("Enter your username:");
userValue = Console.ReadLine();
Console.WriteLine("Enter your password: ");
if (username == "code" && password == "55555")
{
Console.WriteLine("Access allowed! ");
Console.ReadLine();
}
else
{
Console.WriteLine("Access denied! ");
}
Console.ReadLine();
}
}
}

You can't compare int with string, you need to declare password as string, not int, or convert "55555" to int, or password == 555555

Related

Mirth: Evaulating SWITCH versus IF Statement

I'm using a product called Mirth (version 3.6) to execute transform code. It doesn't seem to have an interactive debugger so can anyone explain why the following code in a destination transform will only log from the IF statement and not from the SWITCH statement? Works perfectly from regular java running in Eclipse but this code is executing inside a JavaScript engine that Mirth uses (Rhino if I'm not mistaken).
for each (node in msg['PID'].children())
{
if(node.name() == "PID.3")
{
logger.info("IF Succeeded");
}
switch(node.name())
{
case "PID.3":
logger.info("SWITCH Succeeded"); // This line never logs
break;
}
}
This is a common issue with Mirth Connect since it uses Rhino as it's engine (uses java as well as javascript).
The Switch statement doesn't work with a Java String object
The simple solution is to convert any unknown string type to a native JS string by concatenating an empty string to the questionable string (i.e. str + '')
// See in action
for each (node in msg['PID'].children())
{
var nodeName = node.name();
if (nodeName != "PID.3")
{
continue;
}
var type = typeof(nodeName);
logger.debug('NodeName: ' + nodeName + '; Type: ' + type);
if (type == 'object') {
logger.debug('Type is object');
if (nodeName instanceof String) {
logger.debug('Object is Java String instance');
} else {
logger.debug('Object is not Java String instance');
}
} else if (type === 'string') {
logger.debug('Type is JS string.');
} else {
logger.debug('Type is not object or string. Type: ' + type);
}
// Works with String object or JS string
if (nodeName == "PID.3")
{
logger.info("IF Succeeded");
}
// Only works with JS string
switch (nodeName)
{
case "PID.3":
logger.info("SWITCH Succeeded"); // This line never logs
break;
default:
logger.info("SWITCH not matched: " + nodeName);
break;
}
logger.debug('Convert to JS string');
nodeName = nodeName + '';
type = typeof(nodeName);
logger.debug('Converted Type: ' + type);
if (type == 'object') {
logger.debug('Converted Type is object');
if (nodeName instanceof String) {
logger.debug('Converted Object is String instance');
} else if (nodeName instanceof string) {
logger.debug('Converted Object is string instance');
} else {
logger.debug('Converted Object is not Java String instance');
}
} else if (type === 'string') {
logger.debug('Converted Type is JS string.');
} else {
logger.debug('Converted Type is not object or string. Type: ' + type);
}
switch(nodeName)
{
case "PID.3":
logger.info("SWITCH with js string Succeeded");
break;
default:
logger.info("SWITCH with js string not matched: " + nodeName);
break;
}
break;
}

_Context.SaveChangesAsync() is not executing in command line

I have used _Context.SaveChangesAsync() in a lot of places in my project and it work fine, except here
//hash the password change the bool to false set the salt save
await TryUpdateModelAsync<User>(user);
Hash hash = new Hash();
string salt = hash.CreateSalt();
user.Salt = salt;
user.Password = hash.HashPassword(NewPassword, salt);
user.ChangePassword = false;
await _Context.SaveChangesAsync();
The Model state is true, and it should be working fine but even in the command line (Microsoft.EntityFrameworkCore.Database.Command) it doesn't show at all and the database is not updating, no error or exception is being thrown
any idea ?
this is the whole class
public class ChangePasswordModel : PageModel
{
public string CurrentPassword { set; get; }
public string NewPassword { set; get; }
public User user { set; get; }
private readonly PROJECTDATABASE_MDFContext _Context;
public ChangePasswordModel(PROJECTDATABASE_MDFContext databasecontext)
{
_Context = databasecontext;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync()
{
int TempId = 0;
try
{
TempId = Convert.ToInt32(User.FindFirst(claim => claim.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value);
}
catch { }
if (TempId > 0)
{
user = new User();
user = await _Context.User.AsNoTracking().Include(m => m.Role).FirstOrDefaultAsync(m => m.UserId == TempId);
if (user != null)
{
CurrentPassword = Request.Form["CurrentPassword"];
NewPassword = Request.Form["NewPassword"];
//if the password is hashed
if (user.ChangePassword == false)
{
Hash hash = new Hash();
CurrentPassword = hash.HashPassword(CurrentPassword, user.Salt);
}
if (user.Password == CurrentPassword)
{
if(NewPassword.Length >= 8)
{
//hash the password change the bool to false set the salt save
await TryUpdateModelAsync<User>(user);
Hash hash = new Hash();
string salt = hash.CreateSalt();
user.Salt = salt;
user.Password = hash.HashPassword(NewPassword, salt);
user.ChangePassword = false;
await _Context.SaveChangesAsync();
if (user.Role.RoleName == "Student")
{
return RedirectToPage("Users/StudentProfile", new { id = user.UserId });
}
else
{
return RedirectToPage("Users/StaffMemberProfile", new { id = user.UserId });
}
}
else
{
ModelState.AddModelError("NewPassword", "Password Must be at least 8 characters!");
return Page();
}
}
else
{
ModelState.AddModelError("CurrentPassword", "Password is not Correct!");
return Page();
}
}
}
return Page();
}
}
before the save the user is populated correctly with the updated values so the problem is not in the hash method
The problem is in the line where you load User entity:
user = await _Context.User.AsNoTracking().Include(m => m.Role).FirstOrDefaultAsync(m => m.UserId == TempId);
You use AsNoTracking() extension call which tells Entity Framework not to track any changes for returned entity. So to fix the problem just remove unnecessary AsNoTracking() call:
user = await _Context.User.Include(m => m.Role).FirstOrDefaultAsync(m => m.UserId == TempId);

How to construct a dynamic where filter in EF.Core to handle equals, LIKE, gt, lt, etc

Please how do we construct a dynamic where filter in EF.Core to handle:
Query.Where(fieldName, compareMode, value)
I basically Expect to use it like below:
[HttpGet(Name = nameof(GetStaff))]
public IActionResult GetStaffAsync([FromQuery] QueryParams p)
{
var s = db.Staff.AsNoTracking()
.Where(p.filter_field, p.filter_mode, p.filter_value)
.OrderByMember(p.sortBy, p.descending);
var l = new Pager<Staff>(s, p.page, p.rowsPerPage);
return Ok(l);
}
//Helpers
public class QueryParams
{
public bool descending { get; set; }
public int page { get; set; } = 1;
public int rowsPerPage { get; set; } = 5;
public string sortBy { get; set; }
public onject filter_value { get; set; }
public string filter_field { get; set; }
public string filter_mode { get; set; }
}
public class Pager<T>
{
public int pages { get; set; }
public int total { get; set; }
public IEnumerable<T> Items { get; set; }
public Pager(IEnumerable<T> items, int offset, int limit)
{
Items = items.Skip((offset - 1) * limit).Take(limit).ToList<T>();
total = items.Count();
pages = (int)Math.Ceiling((double)total / limit);
}
}
Assuming all you have is the entity type and strings representing the property, comparison operator and the value, building dynamic predicate can be done with something like this:
public static partial class ExpressionUtils
{
public static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, string comparison, string value)
{
var parameter = Expression.Parameter(typeof(T), "x");
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.Property);
var body = MakeComparison(left, comparison, value);
return Expression.Lambda<Func<T, bool>>(body, parameter);
}
private static Expression MakeComparison(Expression left, string comparison, string value)
{
switch (comparison)
{
case "==":
return MakeBinary(ExpressionType.Equal, left, value);
case "!=":
return MakeBinary(ExpressionType.NotEqual, left, value);
case ">":
return MakeBinary(ExpressionType.GreaterThan, left, value);
case ">=":
return MakeBinary(ExpressionType.GreaterThanOrEqual, left, value);
case "<":
return MakeBinary(ExpressionType.LessThan, left, value);
case "<=":
return MakeBinary(ExpressionType.LessThanOrEqual, left, value);
case "Contains":
case "StartsWith":
case "EndsWith":
return Expression.Call(MakeString(left), comparison, Type.EmptyTypes, Expression.Constant(value, typeof(string)));
default:
throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
}
}
private static Expression MakeString(Expression source)
{
return source.Type == typeof(string) ? source : Expression.Call(source, "ToString", Type.EmptyTypes);
}
private static Expression MakeBinary(ExpressionType type, Expression left, string value)
{
object typedValue = value;
if (left.Type != typeof(string))
{
if (string.IsNullOrEmpty(value))
{
typedValue = null;
if (Nullable.GetUnderlyingType(left.Type) == null)
left = Expression.Convert(left, typeof(Nullable<>).MakeGenericType(left.Type));
}
else
{
var valueType = Nullable.GetUnderlyingType(left.Type) ?? left.Type;
typedValue = valueType.IsEnum ? Enum.Parse(valueType, value) :
valueType == typeof(Guid) ? Guid.Parse(value) :
Convert.ChangeType(value, valueType);
}
}
var right = Expression.Constant(typedValue, left.Type);
return Expression.MakeBinary(type, left, right);
}
}
Basically building property accessor (with nested property support), parsing the comparison operator and calling the corresponding operator/method, dealing with from/to string and from/to nullable type conversions. It can be extended to handle EF Core specific functions like EF.Functions.Like by adding the corresponding branch.
It can be used directly (in case you need to combine it with other predicates) or via custom extension method like this:
public static partial class QueryableExtensions
{
public static IQueryable<T> Where<T>(this IQueryable<T> source, string propertyName, string comparison, string value)
{
return source.Where(ExpressionUtils.BuildPredicate<T>(propertyName, comparison, value));
}
}
based on Ivans answer this is what i came up with
public static class ExpressionUtils
{
public static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, string comparison, object value)
{
var parameter = Expression.Parameter(typeof(T));
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var body = MakeComparison(left, comparison, value);
return Expression.Lambda<Func<T, bool>>(body, parameter);
}
static Expression MakeComparison(Expression left, string comparison, object value)
{
var constant = Expression.Constant(value, left.Type);
switch (comparison)
{
case "==":
return Expression.MakeBinary(ExpressionType.Equal, left, constant);
case "!=":
return Expression.MakeBinary(ExpressionType.NotEqual, left, constant);
case ">":
return Expression.MakeBinary(ExpressionType.GreaterThan, left, constant);
case ">=":
return Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, left, constant);
case "<":
return Expression.MakeBinary(ExpressionType.LessThan, left, constant);
case "<=":
return Expression.MakeBinary(ExpressionType.LessThanOrEqual, left, constant);
case "Contains":
case "StartsWith":
case "EndsWith":
if (value is string)
{
return Expression.Call(left, comparison, Type.EmptyTypes, constant);
}
throw new NotSupportedException($"Comparison operator '{comparison}' only supported on string.");
default:
throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
}
}
}
and some tests
public class Tests
{
[Fact]
public void Nested()
{
var list = new List<Target>
{
new Target
{
Member = "a"
},
new Target
{
Member = "bb"
}
};
var result = list.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<Target>("Member.Length", "==", 2))
.Single();
Assert.Equal("bb", result.Member);
}
[Fact]
public void Field()
{
var list = new List<TargetWithField>
{
new TargetWithField
{
Field = "Target1"
},
new TargetWithField
{
Field = "Target2"
}
};
var result = list.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<TargetWithField>("Field", "==", "Target2"))
.Single();
Assert.Equal("Target2", result.Field);
}
[Theory]
[InlineData("Name", "==", "Person 1", "Person 1")]
[InlineData("Name", "!=", "Person 2", "Person 1")]
[InlineData("Name", "Contains", "son 2", "Person 2")]
[InlineData("Name", "StartsWith", "Person 2", "Person 2")]
[InlineData("Name", "EndsWith", "son 2", "Person 2")]
[InlineData("Age", "==", 13, "Person 2")]
[InlineData("Age", ">", 12, "Person 2")]
[InlineData("Age", "!=", 12, "Person 2")]
[InlineData("Age", ">=", 13, "Person 2")]
[InlineData("Age", "<", 13, "Person 1")]
[InlineData("Age", "<=", 12, "Person 1")]
public void Combos(string name, string expression, object value, string expectedName)
{
var people = new List<Person>
{
new Person
{
Name = "Person 1",
Age = 12
},
new Person
{
Name = "Person 2",
Age = 13
}
};
var result = people.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<Person>(name, expression, value))
.Single();
Assert.Equal(expectedName, result.Name);
}
}
I modified the answer I found here: Linq WHERE EF.Functions.Like - Why direct properties work and reflection does not?
I chucked together a version for those using NpgSQL as their EF Core provider as you will need to use the ILike function instead if you want case-insensitivity, also added a second version which combines a bunch of properties into a single Where() clause:
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName, string searchTerm)
{
// Check property name
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
// Check the search term
if(string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var property = typeof(T).GetProperty(propertyName);
if (property == null)
{
throw new ArgumentException($"The property {typeof(T)}.{propertyName} was not found.", nameof(propertyName));
}
// Check the property type
if(property.PropertyType != typeof(string))
{
throw new ArgumentException($"The specified property must be of type {typeof(string)}.", nameof(propertyName));
}
// Get expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the property expression and return it
Expression selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, IEnumerable<string> propertyNames, string searchTerm)
{
// Check property name
if (!(propertyNames?.Any() ?? false))
{
throw new ArgumentNullException(nameof(propertyNames));
}
// Check the search term
if (string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var properties = propertyNames.Select(p => typeof(T).GetProperty(p)).AsEnumerable();
if (properties.Any(p => p == null))
{
throw new ArgumentException($"One or more specified properties was not found on type {typeof(T)}: {string.Join(",", properties.Where(p => p == null).Select((p, i) => propertyNames.ElementAt(i)))}.", nameof(propertyNames));
}
// Check the property type
if (properties.Any(p => p.PropertyType != typeof(string)))
{
throw new ArgumentException($"The specified properties must be of type {typeof(string)}: {string.Join(",", properties.Where(p => p.PropertyType != typeof(string)).Select(p => p.Name))}.", nameof(propertyNames));
}
// Get the expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the expression and return it
Expression selectorExpression = null;
foreach (var property in properties)
{
var previousSelectorExpression = selectorExpression;
selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
if(previousSelectorExpression != null)
{
selectorExpression = Expression.Or(previousSelectorExpression, selectorExpression);
}
}
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}

How to store user sql where clause, and how to apply it on a select?

I am using JPA / Eclipselink / PostgreSQL within my application.
I have a model that list some data, and I would like to let the user of the application to create his own where clause parameters.
How can I store theses parameters ? as plain sql string ?
Then how can I apply the where clause ? as a simple string concatenation ? (I don't like this idea at all).
Bests regards.
Ok, so I solved my problem.
For information : I have created a recursive JSON representation of every where clause parameters possibility.
And I have created a query using criteria api by decoding the pojo structure from json.
The json class look like that :
public class JSonSearchCriteria
{
public static enum CriteriaType
{
asc,
desc,
count,
countDistinct,
and,
or,
not,
equal,
notEqual,
between,
gt,
ge,
lt,
le,
like,
notLike;
}
#Expose
public CriteriaType type;
#Expose
public List<JSonSearchCriteria> sub;
#Expose
public String what = null;
#Expose
public List<Integer> integerValue = null;
#Expose
public List<Long> longValue = null;
#Expose
public List<Boolean> booleanValue = null;
#Expose
public List<String> stringValue = null;
#Expose
public List<DateTime> datetimeValue = null;
public JSonSearchCriteria()
{
}
public JSonSearchCriteria(final CriteriaType type)
{
this.type = type;
}
public JSonSearchCriteria(final CriteriaType type, final String what)
{
this(type);
this.what = what;
}
public JSonSearchCriteria(final CriteriaType type, final String what, final String... values)
{
this(type, what);
for(final String value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Long... values)
{
this(type, what);
for(final Long value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Integer... values)
{
this(type, what);
for(final Integer value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final DateTime... values)
{
this(type, what);
for(final DateTime value : values)
{
value(value);
}
}
public void add(final JSonSearchCriteria subCriteria)
{
if(sub == null)
{
sub = new ArrayList<>();
}
sub.add(subCriteria);
}
public void value(final String value)
{
if(stringValue == null)
{
stringValue = new ArrayList<>();
}
stringValue.add(value);
}
public void value(final Long value)
{
if(longValue == null)
{
longValue = new ArrayList<>();
}
longValue.add(value);
}
public void value(final Integer value)
{
if(integerValue == null)
{
integerValue = new ArrayList<>();
}
integerValue.add(value);
}
public void value(final DateTime value)
{
if(datetimeValue == null)
{
datetimeValue = new ArrayList<>();
}
datetimeValue.add(value);
}
#SuppressWarnings(
{
"unchecked", "rawtypes"
})
#Transient
public Predicate buildPredicate(final CriteriaBuilder builder, final Root<Record> root, Join<Record, RecordInfo> infos)
{
switch(type)
{
case and:
case or:
final Predicate[] preds = new Predicate[sub.size()];
int cpt = 0;
for(final JSonSearchCriteria s : sub)
{
preds[cpt] = s.buildPredicate(builder, root, infos);
cpt++;
}
if(type == CriteriaType.and)
{
return builder.and(preds);
}
else if(type == CriteriaType.or)
{
return builder.or(preds);
}
break;
case equal:
case lt:
case gt:
case between:
final Path p;
if(what.startsWith("infos."))
{
p = infos.get(what.substring(6));
}
else
{
p = root.get(what);
}
if(stringValue != null && !stringValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, stringValue.get(0));
}
}
else if(longValue != null && !longValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, longValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, longValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, longValue.get(0));
}
}
else if(integerValue != null && !integerValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, integerValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, integerValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, integerValue.get(0));
}
}
else if(booleanValue != null && !booleanValue.isEmpty())
{
return builder.equal(p, booleanValue.get(0));
}
else if(datetimeValue != null && !datetimeValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, datetimeValue.get(0));
}
else if(type == CriteriaType.between && datetimeValue.size() > 1)
{
return builder.between(p, datetimeValue.get(0), datetimeValue.get(1));
}
}
break;
}
System.err.println(type + " - not implemented");
return null;
}
}
And it is used like that :
final SearchTemplate templ = DBHelper.get(SearchTemplate.class, 100);
final Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeJsonAdapter()).create();
final JSonSearchCriteria crits = gson.fromJson(templ.getTemplate(), JSonSearchCriteria.class);
final CriteriaBuilder critBuilder = DBHelper.getInstance().em().getCriteriaBuilder();
final CriteriaQuery<Record> critQuery = critBuilder.createQuery(Record.class);
final Root<Record> root = critQuery.from(Record.class);
final Join<Record, RecordInfo> infos = root.join("infos");
critQuery.where(crits.buildPredicate(critBuilder, root, infos));
final TypedQuery<Record> query = DBHelper.getInstance().em().createQuery(critQuery);
final List<Record> result = query.getResultList();
for(final Record rec : result)
{
System.err.println(rec.toString());
}

MongoDB + Spring MVC

I have working a project which is combination of Spring MVC and Mongodb .
The Database Structure
{
"id": " 12214 -1",
"eRA": " 12214 -1",
"agreementId": null,
"agreementNumber": null,
"deviceTimestamp": null,
"tag": null,
"curentLocation": null,
"gps": "NO",
"grps": "NO",
"logs": {},
"isRead": "1.0",
"rptTime": "15:00",
"salut": "Mr",
"guestName": "Ritesh Arora",
"guestCompShortName": "mmi",
"vehNum": "KL22E2448",
"chauffName": "baba",
"rptDate": "40-83-2.01 15:00",
"rladdr": null,
"rentalType": "Local Run",
"addressRL": "Okhla",
"status": "Received from Carpro"
}
Bean Class Structre
#Document
public class Agreement {
#Id
private String id;
private String eRA;
private AgreementId agreementId; // /Aggrement No
private String agreementNumber;
private String RLAddr; // // RL
private String Salut; // // Salut
private String GuestName; // //GuestName ;
private String GuestCompShortName; // / Company;
private String VehNum; // / vechileNumber
private String ChauffName; // / Driver
private String RentalType; // / RentalType
private String AddressRL; // / reportingAddress
private String RptDate; // / RptDate + RptTime reportingDateTime
private String RptTime; // / RptDate + RptTime reportingDateTime
private String deviceTimestamp; // ///
private String tag;
private String curentLocation;
#Field("Status")
private String Status; // // eRAStatus
private String gps;
private String type;
private String grps;
private Map<String, Map<String, Double>> logs;
private String isRead;
private String name;
public String getType() {
return this.getStatus();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public String getIsRead() {
return isRead;
}
public void setIsRead(String isRead) {
this.isRead = isRead;
}
public String geteRA() {
this.id = this.id.replace("{ \"AgreementNo\" :", "")
.replace(" \"SubNo\" : ", "").replace("}", "")
.replace(",", "-");
return this.id;
}
public void seteRA(String eRA) {
this.eRA = eRA;
}
public AgreementId getAgreementId() {
return agreementId;
}
public void setAgreementId(AgreementId agreementId) {
this.agreementId = agreementId;
}
public String getRLAddr() {
return RLAddr;
}
public void setRLAddr(String rLAddr) {
RLAddr = rLAddr;
}
public String getSalut() {
return Salut;
}
public void setSalut(String salut) {
Salut = salut;
}
public String getGuestName() {
return GuestName;
}
public void setGuestName(String guestName) {
GuestName = guestName;
}
public String getGuestCompShortName() {
return GuestCompShortName;
}
public void setGuestCompShortName(String guestCompShortName) {
GuestCompShortName = guestCompShortName;
}
public String getVehNum() {
return VehNum;
}
public void setVehNum(String vehNum) {
VehNum = vehNum;
}
public String getChauffName() {
return ChauffName;
}
public void setChauffName(String chauffName) {
ChauffName = chauffName;
}
public String getRentalType() {
String rtype = null;
if (RentalType == "1" || RentalType.equalsIgnoreCase("1")) {
rtype = "Local Run";
} else if (RentalType == "2" || RentalType.equalsIgnoreCase("2")) {
rtype = "Out Station";
} else if (RentalType == "3" || RentalType.equalsIgnoreCase("3")) {
rtype = "Transfer";
} else if (RentalType == "4" || RentalType.equalsIgnoreCase("4")) {
rtype = "Package";
} else if (RentalType == "5" || RentalType.equalsIgnoreCase("5")) {
rtype = "self Drive";
} else if (RentalType == "6" || RentalType.equalsIgnoreCase("6")) {
rtype = "LTR";
}
return rtype;
}
public void setRentalType(String rentalType) {
RentalType = rentalType;
}
public String getAddressRL() {
return AddressRL;
}
public void setAddressRL(String addressRL) {
AddressRL = addressRL;
}
public String getRptDate() {
String d = RptDate.substring(4, 6) + "-" + RptDate.substring(6, 8)
+ "-" + RptDate.substring(0, 4);
return d + " " + RptTime;
}
public void setRptDate(String rptDate) {
RptDate = rptDate;
}
public String getRptTime() {
return RptTime;
}
public void setRptTime(String rptTime) {
RptTime = rptTime;
}
public String getDeviceTimestamp() {
return deviceTimestamp;
}
public void setDeviceTimestamp(String deviceTimestamp) {
this.deviceTimestamp = deviceTimestamp;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getCurentLocation() {
return curentLocation;
}
public void setCurentLocation(String curentLocation) {
this.curentLocation = curentLocation;
}
public String getStatus() {
String str = null;
if (Status == "1" || Status.equals("1")) {
Status = "Received from Carpro";
} else if (Status == "2" || Status.equals("2")) {
Status = "Complete Close";
} else if (Status == "3" || Status.equals("3")) {
Status = "Recall";
} else if (Status == "4" || Status.equals("4")) {
Status = "Accepted";
} else if (Status == "5" || Status.equals("5")) {
Status = "Start Journey";
} else if (Status == "6" || Status.equals("6")) {
Status = "Reached Pickup location";
} else if (Status == "7" || Status.equals("7")) {
Status = "Reached Drop off location";
} else if (Status == "8" || Status.equals("8")) {
Status = "Duty completed";
} else if (Status == "9" || Status.equals("9")) {
Status = "Expense Pending";
} else if (Status == "10" || Status.equals("10")) {
Status = "Didn't used";
} else if (Status == "11" || Status.equals("11")) {
Status = "Didn't arrive";
} else if (Status == "12" || Status.equals("12")) {
Status = "Break Down";
} else if (Status == "13" || Status.equals("13")) {
Status = "Exchange";
} else if (Status == "14" || Status.equals("14")) {
Status = "Dispatched to mobile";
} else if (Status == "15" || Status.equals("15")) {
Status = "Not Mapped or not delivered to mobilee";
} else if (Status == "16" || Status.equals("16")) {
Status = "Not Accepted";
} else if (Status == "17" || Status.equals("17")) {
Status = "Start Button Not Pressed";
} else if (Status == "18" || Status.equals("18")) {
Status = "Pickup Button not Pressed";
} else if (Status == "19" || Status.equals("19")) {
Status = "Closure status not received";
} else if (Status == "20" || Status.equals("20")) {
Status = "No GPRS";
} else if (Status == "21" || Status.equals("21")) {
Status = "No GPS";
} else if (Status == "22") {
Status = "Didn't communicate to fleet";
}
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getAgreementNumber() {
return agreementNumber;
}
public void setAgreementNumber(String agreementNumber) {
this.agreementNumber = agreementNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Map<String, Double>> getLogs() {
return logs;
}
public void setLogs(Map<String, Map<String, Double>> logs) {
this.logs = logs;
}
public String getGps() {
if (this.Status == "21" || this.Status.equalsIgnoreCase("21"))
return "YES";
else
return "NO";
}
public void setGps(String gps) {
this.gps = gps;
}
public String getGrps() {
if (this.Status == "20" || this.Status.equalsIgnoreCase("20"))
return "YES";
else
return "NO";
}
public void setGrps(String grps) {
this.grps = grps;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return RLAddr + " >>> " + Salut + ">>>>>>> " + id + "vdsvsdvs ";
}
}
but when is used
query1.addCriteria(Criteria.where("Status").is("constant"));
mongoTemplate.find(query1, Agreement.class, "eRA_live_v1");
I am getting following Error
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/avisweb] threw exception [Request processing failed; nested exception is o org.springframework.data.mapping.model.MappingException: No property status found on com.avis.bean.Agreement!] with root cause
org.springframework.data.mapping.model.MappingException: No property status found on com.avis.bean.Agreement!
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:228)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:206)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:194)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:714)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:605)
at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:152)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:113)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1515)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1506)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:532)
When You Make Entity Bean Class You Have #Column Name Where Write The Column Name Which You Declare In To Database And in the intial value you declare any name