Using JSONPath to check for Boolean values - jsonpath

I'm trying to write a JSONPath expression to check if active=true for this simple object.
{
"active": true
}
Is this possible in JSONPath? I can't seem to get it to work in any online JSONPath evaluator.

I think the following should work
final Configuration conf = Configuration.defaultConfiguration();
try {
Object returnObj = JsonPath.using(conf).parse(responseBody).read("$.active");
System.out.println(returnObj);
}
catch (PathNotFoundException e){
System.err.println("JsonPath not found : " + path);
}

Related

How do you retrieve the Exception number from DbUpdateException in Asp.net 5

I'd rather not do string comparison and it looks like my exeption number is in the InnerExeption number field but I get build errors if I try to access it directly.
try {
db.SaveChanges();
} catch (Microsoft.Data.Entity.DbUpdateException ex) {
// ex.InternalException.Number won't compile but appears to be there
// ex.InternalException.Message does compile but I think it seems less clean than a const comparison
}
Once I do get the number is there a const I can compare it with? I'm trying to check for duplicate key error.
Thanks
I found a way to do it.
db.User.Add(user);
try {
db.SaveChanges();
} catch (Microsoft.Data.Entity.DbUpdateException ex) {
if (((System.Data.SqlClient.SqlException)ex.InnerException).Number == 2627) {
return new HttpStatusCodeResult(409);
}
}

Web Performance Testing context paramters

I used the MSDN guide on creating Custom Extraction Rule, which presents this example (Extract method):
public override void Extract(object sender, ExtractionEventArgs e)
{
if (e.Response.HtmlDocument != null)
{
foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags(new string[] { "input" }))
{
if (String.Equals(tag.GetAttributeValueAsString("name"), Name, StringComparison.InvariantCultureIgnoreCase))
{
string formFieldValue = tag.GetAttributeValueAsString("value");
if (formFieldValue == null)
{
formFieldValue = String.Empty;
}
// add the extracted value to the web performance test context
e.WebTest.Context.Add("someNameHere", formFieldValue);
e.Success = true;
return;
}
}
}
// If the extraction fails, set the error text that the user sees
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found: {0}", Name);
}
However, I just don't know how to use access the someNameHere in the Web Test and add it to the QueryString as a parameter.
Any help would be greatly appreciated.
Right-click on the request in the web test and select "Add URL query string parameter". Alter the name as needed and into the value field enter {{someNameHere}}. The doubled curly braces call for a context parameter value to be inserted. The doubled curly braces can be used to insert the value of a context parameter into many other places in a web test. Note that strings such as text{{someNameHere}}moretext can be used to join context values to other strings.

sqlite jdbc setJournalMode

I running my first trials on SQLite (with JDBC) as pure memory database. As I need very fast inserts I tried to set the config accordingly. I could find out that the code below fails only at the setting for JournalMode. Please refer to the method shown below. The variables con and isConnected are defined as class vars and not shown here.
Thanks a lot
Rolf
public Boolean connect() {
try {
Class.forName("org.sqlite.JDBC"); // sqlitejdbc_3.7.2
// Set all pragmas
SQLiteConfig config = new SQLiteConfig();
// This statement (JournalMode setting) causes a fail
// Without that statement the connection can be established
// ==> java.sql.BatchUpdateException: batch entry 0: query returns results
config.setJournalMode(JournalMode.MEMORY);
config.setTempStore(TempStore.MEMORY);
config.setSynchronous(SynchronousMode.OFF);
config.enforceForeignKeys(false);
config.enableCountChanges(false);
con = DriverManager.getConnection("jdbc:sqlite::memory:", config.toProperties());
isConnected = true ;
return true ;
}
catch (Exception e) {
LogMessages.instance().print(0, LogMessages.MSG_SEVERITY.ERROR, e.getMessage() + "\n");
e.printStackTrace() ;
return false ;
}
}
I have the same issue, but there is an other way to disable it. After opening the connection you can execute this query :
PRAGMA journal_mode=MEMORY;

Validate a string to be json or not in asp.net

is there any way to validate a string to be json or not ? other than try/catch .
I'm using ServiceStack Json Serializer and couldn't find a method related to validation .
Probably the quickest and dirtiest way is to check if the string starts with '{':
public static bool IsJson(string input){
input = input.Trim();
return input.StartsWith("{") && input.EndsWith("}")
|| input.StartsWith("[") && input.EndsWith("]");
}
Another option is that you could try using the JavascriptSerializer class:
JavaScriptSerializer ser = new JavaScriptSerializer();
SomeJSONClass = ser.Deserialize<SomeJSONClass >(json);
Or you could have a look at JSON.NET:
http://james.newtonking.com/projects/json-net.aspx
http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
A working code snippet
public bool isValidJSON(String json)
{
try
{
JToken token = JObject.Parse(json);
return true;
}
catch (Exception ex)
{
return false;
}
}
Source
You can find a couple of regular expressions to validate JSON over here: Regex to validate JSON
It's written in PHP but should be adaptable to C#.

Alfresco: Custom Share Evaluator based on some custom repo webscripts

So I'd like to write a new set of evaluators in Share based on the result of some repository webscripts.
The current existing Share evaluators are usable through some XML configuration and are related to Alfresco usual meta-data.
But, I'd like to know how to write my own Java evaluator while re using most of the logic already here (BaseEvaluator).
Suppose I have a repository webscript that returns some JSON like {"result" : "true"}:
How do I access it from my custom Evaluator? Mainly how do I access the proxy URL to alfresco webapp from the Spring context?
Do I need to write my own async call in Java?
Where do I find this JSONObject parameter of the required evaluate method?
thanks for your help
See if this helps. This goes into a class that extends BaseEvaluator. Wire the bean in through Spring, then set the evaluator on your actions.
public boolean evaluate(JSONObject jsonObject) {
boolean result = false;
final RequestContext rc = ThreadLocalRequestContext.getRequestContext();
final String userId = rc.getUserId();
try {
final Connector conn = rc.getServiceRegistry().getConnectorService().getConnector("alfresco", userId, ServletUtil.getSession());
final Response response = conn.call("/someco/example?echo=false");
if (response.getStatus().getCode() == Status.STATUS_OK) {
System.out.println(response.getResponse());
try {
org.json.JSONObject json = new org.json.JSONObject(response.getResponse());
result = Boolean.parseBoolean(((String) json.get("result")));
} catch (JSONException je) {
je.printStackTrace();
return false;
}
} else {
System.out.println("Call failed, code:" + response.getStatus().getCode());
return false;
}
} catch (ConnectorServiceException cse) {
cse.printStackTrace();
return false;
}
return result;
}
In this example I am using a simple example web script that echoes back your JSON and switches the result based on the value of the "echo" argument. So when it is called with "false", the JSON returns false and the evaluator returns false.
I should probably point out the name collision between the org.json.simple.JSONObject that the evaluate method expects and the org.json.JSONObject I am using to snag the result from the response JSON.

Resources