Extra JSON value to display in Objective C - objective-c

In my app, I get the following response for a failed user login:
{
"non_field_errors": [
"User account is disabled."
]
}
Is there a way to get this in Objective-C to only display: User account is disabled.?
When I do the following, it displays:
(
"User account is disabled."
)
Code:
NSLog(#"%#",[JSONValue objectForKey:#"non_field_errors"]);
How can I remove the parentheses and double quotes?

Parentheses is there because you are getting response in such a way. you can access your data using following way.
JSONValue[#"non_field_errors"][0] // This will return User account is disabled.

That is because the value for key non_field_errors is a JSON Array (Notice the square brackets). So use this :
NSArray *arr = [JSONValue objectForKey:#"non_field_errors"];
NSLog(#"%#",[arr firstObject]);
or just cram it all in one line
[(NSArray*)[JSONValue objectForKey:#"non_field_errors"] firstObject];

Related

Karate Api : check if a phrase is available response object array

I've a response
{ errors: [
{
code: 123,
reason: "this is the cause for a random problem where the last part of this string is dynamically generated"
} ,
{
code: 234,
reason: "Some other error for another random reason"
}
...
...
}
Now when I validate this response
I use following
...
...
And match response.errors[*].reason contains "this is the cause"
This validation fails, because there is an equality check for complete String for every reason ,
I all I want is, to validate that inside the errors array, if there is any error object, which has a reason string type property, starting with this is the cause phrase.
I tried few wild cards but didn't work either, how to do it ?
For complex things like this, just switch to JS.
* def found = response.errors.find(x => x.reason.startsWith('this is the cause'))
* match found == { code: 123, reason: '#string' }
# you can also do
* if (found) karate.log('found')
Any questions :)

Data validation with One of range rule in Google Sheets API

I'm trying to implement data validation where the rule is one of the range using Google Sheets API.
In sheet1, I have a master list where one column needs to be in one of the values. The possible dropdown values are in a separate sheet called dropdown.
What is the error in my conditional value for one_of_range?
dropdown_action = {
'setDataValidation':{
'range':{
'startRowIndex':1,
'startColumnIndex':4,
'endColumnIndex':5
},
'rule':{
'condition':{
'type':'ONE_OF_RANGE',
'values': [
{ "userEnteredValue" : "dropdown!A1:B2"
}
],
},
'inputMessage' : 'Choose one from dropdown',
'strict':True,
'showCustomUi': True
}
}
}
request = [dropdown_action]
batchUpdateRequest = {'requests': request}
SHEETS.spreadsheets().batchUpdate(spreadsheetId = id,
body = batchUpdateRequest).execute()
However, I encountered into http error. I was able to get it working if I choose one of list instead of one_of_range. But I prefer to use one_of_range so that I can maintain the possible values in the same spreadsheet.
HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/id:batchUpdate?alt=json returned "Invalid requests[1].setDataValidation: Invalid ConditionValue.userEnteredValue: dropdown!A1:B2">
As Sam Berlin suggested, the solution is to add '=' in the range.
"=dropdown!A1:B2" will work with one_in_range data validation rule.
Nothing could work for me, and then I saw this subject
Google Spreadsheet API setDataValidation with Regex , where ZektorH mark that "Your expression needs to be escaped".

How to pass same parameter with different value

I am trying the following API using Alamofire, but this API has multiple "to" fields. I tried to pass an array of "to" emails as parameters. It shows no error but did not send to all emails. API is correct, I tested that from terminal. Any suggestions will be cordially welcomed.
http -a email:pass -f POST 'sampleUrl' from="email#email.com" to="ongkur.cse#gmail.com" to="emailgmail#email.com" subject="test_sub" bodyText="testing hello"
I am giving my code:
class func sendMessage(message:MessageModel, delegate:RestAPIManagerDelegate?) {
let urlString = "http://localhost:8080/app/user/messages"
var parameters = [String:AnyObject]()
parameters = [
"from": message.messageFrom.emailAddress
]
var array = [String]()
for to in message.messageTO {
array.append(to)
}
parameters["to"] = array
for cc in message.messageCC {
parameters["cc"] = cc.emailAddress;
}
for bcc in message.messageBCC {
parameters["bcc"] = bcc.emailAddress;
}
parameters["subject"] = message.messageSubject;
parameters["bodyText"] = message.bodyText;
Alamofire.request(.POST, urlString, parameters: parameters)
.authenticate(user: MessageManager.sharedInstance().primaryUserName, password: MessageManager.sharedInstance().primaryPassword)
.validate(statusCode: 200..<201)
.validate(contentType: ["application/json"])
.responseJSON {
(_, _, jsonData, error) in
if(error != nil) {
println("\n sendMessage attempt json response:")
println(error!)
delegate?.messageSent?(false)
return
}
println("Server response during message sending:\n")
let swiftyJSONData = JSON(jsonData!)
println(swiftyJSONData)
delegate?.messageSent?(true)
}
}
First of all if you created the API yourself you should consider changing the API to expect an array of 'to' receivers instead of multiple times the same parameter name.
As back2dos states it in this answer: https://stackoverflow.com/a/1898078/672989
Although POST may be having multiple values for the same key, I'd be cautious using it, since some servers can't even properly handle that, which is probably why this isn't supported ... if you convert "duplicate" parameters to a list, the whole thing might start to choke, if a parameter comes in only once, and suddendly you wind up having a string or something ...
And I think he's right.
In this case I guess this is not possible with Alamofire, just as it is not possible with AFNetworking: https://github.com/AFNetworking/AFNetworking/issues/21
Alamofire probably store's its POST parameter in a Dictionary which doesn't allow duplicate keys.

JavaCC: Defining a *password* token or grammar rule

I'm using JavaCC do simulate a small part of SQL grammars, and I'm having a problem with defining a password.
I'm writting grammar rules for a
CREATE USER user_name IDENTIFIED BY a_password
statement, and I'm stuck. Since a password can match with ANYTHING like asdkj*!##, or !#%^%ASDjnkj, _ASDJLJK##& etc. Note that in Oracle, it's totally legal to input your password without single quote mark ('). I could solve this problem easily if the quote marks are compulsory, but unfortunately they're not.
I've tried many ways to define a token/grammar rule for this password, but it didn't work as I expected, the latest rule I've tried is:
TOKEN : {
< S_PASSWORD: ( < DIGIT > | < LETTER > |< S_PASSCHAR >)+ >
| <#S_PASSCHAR : "!"|"#"|"#"|"$"|"%"|"^"|"&"|"*" >
| <#LETTER: ["a"-"z", "A"-"Z", "_"]>
| <#DIGIT: ["0" - "9"]>
}
But since < S_PASSWORD > can match ANYTHING, any other token that I defined earlier will be match with it, and I always get a JavaCC warning like this:
Warning: "#" cannot be matched as a string literal token at line 33515, column 13. It will be matched as < S_PASSWORD >.
There are similar suggestions from my friends, but they didn't work either.
Can someone help me with this?
Assuming there is some lexical way to tell where the password begins and ends, you can use lexical states. For example, if the sequence IDENTIFIED BY is only ever followed by spaces that are followed by a password, you make a state machine so that IDENTIFIED transitions from DEFAULT to S0. In S0 spaces are skipped and BY transitions to S1. In S1 spaces are skipped and a sequence of password characters is a PASSWORD token; the PASSWORD token transitions back to DEFAULT. Of course this only works if IDENTIFIED BY can only ever be followed by a password. Also in S0 you need to by able to deal with all the normal stuff, so most of your token rules should apply in both states S0 and DEFAULT but transition to DEFAULT. See the FAQ for more on lexical states.
If BY is only ever followed by a password, then it is even easier, as you don't need S0.
Edit
Here are some example rules. If the keyword BY is only ever followed by a password, you only need two states
TOKEN : { <BY : "BY"> : S1>
<S1> TOKEN : { <PASSWORD : ( <PASSWORDCHAR> )+ } : DEFAULT }
<DEFAULT, S1> : SKIP { " " } // Stays in the same state.
If you can use IDENTIFIED followed by BY then you need three states
<DEFAULT, S0> TOKEN : { <CREATE : "CREATE"> : DEFAULT } // And similar for most token rules.
<DEFAULT, S0> TOKEN : { <IDENTIFIED : "IDENTIFIED"> : S1 }
<S0> TOKEN : { <BY : "BY"> : S1> // BYs that follow IDENTIFIED
<DEFAULT> TOKEN : { <BY : "BY"> : DEFAULT } BYs that don't follow IDENTIFIED.
<S1> TOKEN : { <PASSWORD : ( <PASSWORDCHAR> )+ } : DEFAULT }
<DEFAULT, S0, S1> : SKIP { " " } // Stays in the same state.

Applescript from Mac App says "Expected end of line but found \U201c\"\U201d."

I am trying to perform a copy/paste for my to the the last active app, here's my code:
NSString *appleScriptSource = [NSString stringWithFormat:#"\ntell application \"%#\" to activate\ntell application \"System Events\" to tell process \"%#\"\nkeystroke \"v\" using command down\nend tell", [lastApp localizedName], [lastApp localizedName]];
NSDictionary *error;
NSAppleScript *aScript = [[NSAppleScript alloc] initWithSource:appleScriptSource];
NSAppleEventDescriptor *aDescriptor = [aScript executeAndReturnError:&error];
The problem is that on some computers it works just fine, but on others it fails. My error output from error that is returned by executeAndReturnError is:
2012-06-13 17:43:19.875 Mini Translator[1206:303] (null) (error: {
NSAppleScriptErrorBriefMessage = "Expected end of line but found \U201c\"\U201d.";
NSAppleScriptErrorMessage = "Expected end of line but found \U201c\"\U201d.";
NSAppleScriptErrorNumber = "-2741";
NSAppleScriptErrorRange = "NSRange: {95, 1}";
})
I can't seem to figure out what it means or why it happens.
We tried copying the generated apple-script code into the Apple Script editor, and here it works just fine.
My App is sandboxed - i have added the bundle identifiers for the key "com.apple.security.temporary-exception.apple-events" for the apps i want to support.
Any suggestions?
I am guessing that the \u201c and \u201d are red herrings and just represent smart quotes around a double quote in the error message produced by apple script, and your issue lies with the localized name of the last application you are formatting into the script. I am not sure why you might see this on one machine and not another.
For example if the name was 'Some " App' then the double quotes would end up mismatched as it would end up injected into the middle of a double quoted string. You might want to try and replace any double quotes in the name with '\"' which will escape them.
e.g.
NSString *esc = [[lastApp localizedName] stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];