JPAQL concat operation - jpa-2.1

I am trying to do following to get output like 'MASTHANVALI - Technical Writer'
Query query = em.createQuery("select concat(upper(ename) , \" - \", deg )from employee");
But having following error.
Exception in thread "main" java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: Exception Description: Syntax error parsing [select concat(upper(ename) , " - ", deg )from employee].
[20, 25] The encapsulated expression is not a valid expression.
[37, 40] The expression 'deg' is not valid expression.
[54, 54] An identification variable must be provided for a range variable declaration.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)
at com.tutorialspoint.eclipselink.service.ScalarandAggregateFunctions.main(ScalarandAggregateFunctions.java:14) Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.JPQLException
Any idea how to do this?

try replacing the double quotes with single qoutes and add a space after the closing bracket
Query query =
em.createQuery("select concat(upper(ename) , ' - ', deg ) from employee");

Related

DynamoDB update_item: Increase values for existing items or use 1 for new item

I try to use updateitem as according to the wiki it works for updating existing & creating new items:
"Edits an existing item's attributes, or adds a new item to the table
if it does not already exist."
I want to store:
the first time someone opened a item
the last time someone opened a item
the number of openings of a item
I have following code:
table.update_item(
Key={'item':"NEW"},
UpdateExpression="SET opens = if_not_exists(opens + :var1, :var0), last_open = :var2, first_open = if_not_exists(first_open, :var3)",
ExpressionAttributeValues={
':var0': "0",
':var1': "1",
':var2': '2020-04-01',
':var3': '1999-01-01'
},
ReturnValues="UPDATED_NEW"
)
runs into error for new & existing items and says
An error occurred (ValidationException) when calling the UpdateItem
operation: Invalid UpdateExpression: Syntax error; token: \"+\", near:
\"opens + :var1\""
Following works for existing items but throws an error for new ones:
table.update_item(
Key={'item':"NEW"},
UpdateExpression="SET opens = opens + :var1, last_open = :var2, first_reachout = if_not_exists(first_open, :var3)",
ExpressionAttributeValues={
':var1': "1",
':var2': '2020-04-01',
':var3': '1999-01-01'
},
ReturnValues="UPDATED_NEW"
)
Error for only new ones:
"An error occurred (ValidationException) when calling the UpdateItem operation: The provided expression refers to an attribute that does not exist in the item"
I guess it means the contacts attribute, but including it into "if_not_exists" also does not work....
You can find the documentation for the UpdateExpression syntax in https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET. The relevant part for your question is the following:
value ::=
operand
| operand '+' operand
| operand '-' operand
operand ::=
path | function
Which means, the "+" can only be at the top level of the expression, it cannot be inside the function's parameters.
Luckily, there is an easy workaround for you. Instead of the if_not_exists(opens + :var1, :var0) which you tried, try" :var1 + if_not_exists(opens, :var0).

SQL query error or missing database shows syntax error using LIKE query

I have a syntax error that I don't know how to solve. Here is the code:
fun allSearchData(searchStringRaw: String): Cursor{
val searchString = "% $searchStringRaw %"
val query = "Select * from $MARKER_TABLE where $KEY_NAME like $searchString"
val c = mySpotsDatabase!!.rawQuery(query, null)
c.moveToFirst()
return c
}
and it is giving me this error:
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "%": syntax error (code 1): , while compiling: Select * from my_locations_table where Name like % h %)
If I remove the spaces as follows it makes no difference.
val searchString = "%$searchStringRaw%"
and this just changes the error line to the following, so I know its not the space in the string issue.
(near "%": syntax error (code 1): , while compiling: Select * from my_locations_table where Name like %h%)
I can not see the syntax error. Any help would be appreciated.
You need to enclose the argument for the LIKE clause in single quotes.
e.g. val searchString = "'% $searchStringRaw %'"
However, you would be better of using the second parameter of the rawQuery method to pass the arguments, in which case they will be properly escaped and you gain the advantage of protecting against SQL Injection.
Thanks To #MikeT who saw the issue.
Here is the correct code:
fun allSearchData(searchStringRaw: String): Cursor{
val searchString = "'%$searchStringRaw%'"
val query = "Select * from $MARKER_TABLE where $KEY_NAME like $searchString"
val c = mySpotsDatabase!!.rawQuery(query, null)
c.moveToFirst()
return c
}
It now works perfectly

python creation json with plone object

I've a json file with plone objects and there is one field of the objects giving me an error:
UnicodeDecodeError('ascii', '{"id":"aluminio-prata", "nome":"ALUM\xc3\x8dNIO PRATA", "num_demaos":0, "rendimento": 0.0, "unidade":"litros", "url":"", "particular":[], "profissional":[], "unidades":[]},', 36, 37, 'ordinal not in range(128)') (Also, the following error occurred while attempting to render the standard error message, please see the event log for full details: 'NoneType' object has no attribute 'getMethodAliases')
I already know witch field is, is the "title" from title = obj.pretty_title_or_id(), when I remove it from here its ok:
json += '{"id":"' + str(id) + '", "nome":"' + title + '", "num_demaos":' + str(num_demaos) + ', "rendimento": ' + str(rendimento) + ', "unidade":"' + str(unidade) + '", "url":"' + link_produto + '", "particular":' + arr_area_particular + ', "profissional":' + arr_area_profissional + ', "unidades":' + json_qtd + '},
but when I leave it I've got this error.
UnicodeDecodeError('ascii', '{"id":"aluminio-prata", "nome":"ALUM\xc3\x8dNIO PRATA", "num_demaos":0, "rendimento": 0.0, "unidade":"litros", "url":"", "particular":[], "profissional":[], "unidades":[]},', 36, 37, 'ordinal not in range(128)') (Also, the following error occurred while attempting to render the standard error message, please see the event log for full details: 'NoneType' object has no attribute 'getMethodAliases')
I'm going to assume that the error occurs when you're reading the JSON file.
Internally, Plone uses Python Unicode strings for nearly everything. If you read a string from a file, it will need to be decoded into Unicode before Plone can use it. If you give no instructions otherwise, Python will assume that the string was encoded as ASCII, and will attempt its Unicode conversion on that basis. It would be similar to writing:
unicode("ALUM\xc3\x8dNIO PRATA")
which will produce the same kind of error.
In fact, the string you're using was evidently encoded with the UTF-8 character set. That's evident from the "\xc3", and it also makes sense, because that's the character set Plone uses when it sends data to the outside world.
So, how do you fix this? You have to specify the character set that you wish to use when you convert to Unicode:
"ALUM\xc3\x8dNIO PRATA".decode('UTF8')
This gives you a Python Unicode string with no error.
So, after you've read your JSON file into a string (let's call it mystring), you will need to explicitly decode it by using mystring.decode('UTF8'). unicode(mystring, 'UTF8') is another form of the same operation.
As Steve already wrote do title.decode('utf8')
An Example illustrate the facts:
>>> u"Ä" == u"\xc4"
True # the native unicode char and escaped versions are the same
>>> "Ä" == u"\xc4"
False # the native unicode char is '\xc3\x84' in latin1
>>> "Ä".decode('utf8') == u"\xc4"
True # one can decode the string to get unicode
>>> "Ä" == "\xc4"
False # the native character and the escaped string are
# of course not equal ('\xc3\x84' != '\xc4').
I find this Thread very helpfull for Problems and Understanding with Encode/Decode of UTF-8.

org.springframework.validation.Errors.rejectValue doesn't escape values

I am trying to add escaped values to an error message in a Spring MVC Validator
final Object[] vatErrorArray = new String[2];
vatErrorArray[0] = "aaa";
vatErrorArray[1] = "bbb";
errors.rejectValue("vatfield", "vendor.vat.number.invalid.pattern.generic", vatErrorArray, "Invalid VAT");
where vendor.vat.number.invalid.pattern.generic is as follows:
vendor.vat.number.invalid.pattern.generic=VAT Number's pattern is invalid for {0}. Valid pattern: {1}.
Unfortunately, the displayed error message doesn't contain the escaped values:
VAT Numbers pattern is invalid for {0}. Valid pattern: {1}.
What am I doing wrong?
PS I am using Spring MVC version 4.2.1.RELEASE
I think you need to change the single quote in Number's to two single quotes ('').
I haven't tried it myself but am basing this mostly on the content of this question, and the MessageFormat docs it links to, plus the fact that your single quote seems to be disappearing.

escaping string for json result in asp.net server side operation

I have a server side operation manually generating some json response. Within the json is a property that contains a string value.
What is the easiest way to escape the string value contained within this json result?
So this
string result = "{ \"propName\" : '" + (" *** \\\"Hello World!\\\" ***") + "' }";
would turn into
string result = "{ \"propName\" : '" + SomeJsonConverter.EscapeString(" *** \\\"Hello World!\\\" ***") + "' }";
and result in the following json
{ \"propName\" : '*** \"Hello World!\" ***' }
First of all I find the idea to implement serialization manually not good. You should to do this mostla only for studying purpose or of you have other very important reason why you can not use standard .NET classes (for example use have to use .NET 1.0-3.0 and not higher).
Now back to your code. The results which you produce currently are not in JSON format. You should place the property name and property value in double quotas:
{ "propName" : "*** \"Hello World!\" ***" }
How you can read on http://www.json.org/ the double quota in not only character which must be escaped. The backslash character also must be escaped. You cen verify you JSON results on http://www.jsonlint.com/.
If you implement deserialization also manually you should know that there are more characters which can be escaped abbitionally to \" and \\: \/, \b, \f, \n, \r, \t and \u which follows to 4 hexadecimal digits.
How I wrote at the beginning of my answer, it is better to use standard .NET classes like DataContractJsonSerializer or JavaScriptSerializer. If you have to use .NET 2.0 and not higher you can use Json.NET.
You may try something like:
string.replace(/(\\|")/g, "\\$1").replace("\n", "\\n").replace("\r", "\\r");

Resources