Restkit - Matching a Path with ? and = - restkit

I've set up a response descriptor like this:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:exhibitMapping method:RKRequestMethodAny pathPattern:#"?json=exhibits/get_exhibits" keyPath:#"d.exhibits" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
And made the request like so:
[[RKObjectManager sharedManager] getObjectsAtPath:#"?json=exhibits/get_exhibits" parameters:nil success:
But I get this error:
2014-03-17 11:14:39.856 MuseumMap[6135:60b] E app:ExhibitTableViewController.m:49 Load failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded." UserInfo=0x8fb69f0 {NSErrorFailingURLStringKey=http://exhibits.wpengine.com/?json=exhibits/get_exhibits, NSLocalizedFailureReason=A 200 response was loaded from the URL 'http://exhibits.wpengine.com/?json=exhibits/get_exhibits', which failed to match all (1) response descriptors:
<RKResponseDescriptor: 0x9480270 baseURL=http://exhibits.wpengine.com/ pathPattern=?json=exhibits/get_exhibits statusCodes=200-299> failed to match: response path '?json=exhibits/get_exhibits' did not match the path pattern '?json=exhibits/get_exhibits'., NSLocalizedDescription=No response descriptors match the response loaded., keyPath=null, NSErrorFailingURLKey=http://exhibits.wpengine.com/?json=exhibits/get_exhibits, NSUnderlyingError=0x8fb6990 "No mappable object representations were found at the key paths searched."}
My thought is that there is a problem matching because of either the ? or the = in the pathPattern but I've tried escaping those and it doesn't seem to make a difference. Anyone have any ideas why this wouldn't match? The error message being response path '?json=exhibits/get_exhibits' did not match the path pattern '?json=exhibits/get_exhibits'. seems a bit off.

The problem was with the way the URL was formed. I changed my site to use permalinks instead of the ?json query parameters and that seemed to work. The path matching eliminates the query parameters before it matches so those cannot be used to match in restkit.
http://wordpress.org/plugins/json-api/other_notes/#1.1.-Requests

Related

illegal characters at line 1 and col 1 in xml response in jmeter

I am trying to validate the xml response from an REST API using JMETER. I am using xml schema assertion to validate the response using xsd.
I am getting the following error on XML Schema Assertion
Assertion error: true
Assertion failure: false
Assertion failure message: fatal: line=1 col=1 Content is not allowed in prolog.
When i see the response that i have received i see there are some illegal characters that is added at the beginning of the response xml.
enter image description here
I have tried to modify jmeter.properties file and changed the following values
jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.data_type=true
jmeter.save.saveservice.label=true
jmeter.save.saveservice.response_code=true
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_name=true
Please help me in understanding how to remove the illegal characters in the response and allow the xsd validation to pass through.
These characters indicate Byte Order Mark so you can use BOMInputStream from the JSR223 PostProcessor in order to remove them from the response and replace the response data with "sanitized" XML.
Add JSR223 PostProcessor as a child of the HTTP Request sampler where you want to remove this BOM
Put the following code into "Script" area:
def is = new ByteArrayInputStream(prev.getResponseData())
def bOMInputStream = new org.apache.commons.io.input.BOMInputStream(is)
def bom = bOMInputStream.getBOM()
def charsetName = bom == null ? 'UTF-8' : bom.getCharsetName()
def reader = new InputStreamReader(new BufferedInputStream(bOMInputStream), charsetName)
prev.setResponseData(org.apache.commons.io.IOUtils.toByteArray(reader, 'UTF-8'))
That's it, your assertion shouldn't be failing anymore.
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Service Now : transform map stopped due to error: java.lang.NumberFormatException

The transform is getting aborted but only if I marked the checkbox copy empty fields and also the rest of the entry of the Import set is getting stuck at pending, also I verified the transform script but no luck.
Below is the error :
Import set: ISETxxxxxxx transform stopped due to error: java.lang.NumberFormatException
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:596)
at java.math.BigDecimal.<init>(BigDecimal.java:383)
at java.math.BigDecimal.<init>(BigDecimal.java:806)
at com.glide.script.glide_elements.GlideNumber.getSafeBigDecimal(GlideNumber.java:42)
at com.glide.currency.GlideElementCurrency.coerceAmount(GlideElementCurrency.java:406)
at com.glide.currency.GlideElementCurrency.cleanAmount(GlideElementCurrency.java:389)
at com.glide.currency.GlideElementCurrency.setDisplayValue(GlideElementCurrency.java:136)
at com.glide.currency.GlideElementCurrency.setValue(GlideElementCurrency.java:89)
at com.glide.db.impex.transformer.TransformerField.copyEmptyFields(TransformerField.java:202)
at com.glide.db.impex.transformer.TransformerField.setValue(TransformerField.java:130)
at com.glide.db.impex.transformer.TransformerField.transformField(TransformerField.java:84)
at com.glide.db.impex.transformer.TransformRow.transformCurrent(TransformRow.java:100)
at com.glide.db.impex.transformer.TransformRow.transform(TransformRow.java:69)
at com.glide.db.impex.transformer.Transformer.transformBatch(Transformer.java:150)
at com.glide.db.impex.transformer.Transformer.transform(Transformer.java:76)
at com.glide.system_import_set.ImportSetTransformerImpl.transformEach(ImportSetTransformerImpl.java:239)
at com.glide.system_import_set.ImportSetTransformerImpl.transformAllMaps(ImportSetTransformerImpl.java:91)
at com.glide.system_import_set.ImportSetTransformer.transformAllMaps(ImportSetTransformer.java:64)
at com.glide.system_import_set.ImportSetTransformer.transformAllMaps(ImportSetTransformer.java:50)
at com.snc.automation.ScheduledImportSetJob.runImport(ScheduledImportSetJob.java:55)
at com.snc.automation.ScheduledImportJob.execute(ScheduledImportJob.java:45)
at com.glide.schedule.JobExecutor.execute(JobExecutor.java:83)
at com.glide.schedule.GlideScheduleWorker.executeJob(GlideScheduleWorker.java:207)
at com.glide.schedule.GlideScheduleWorker.process(GlideScheduleWorker.java:145)
at com.glide.schedule.GlideScheduleWorker.run(GlideScheduleWorker.java:62)
I'm guessing you have a field that required that is a decimal or similar.
The error java.lang.NumberFormatException indicates it's failing to convert an empty string to 0.0.
Use a source script line to convert this, something along the lines of this
answer = (function transformEntry(source) {
if (source.u_number_field.nil())
return 0.0;
})(source);

Client-side validation of Elasticsearch query string

I have an application that uses NEST (Elasticsearch .NET client) to communicate with an Elasticsearch cluster. The integration allows the user to specify input for the "query_string" portion of a query.
The user may input an invalid query. Say "AND", which is invalid because the predicate is incomplete. But the error message that comes back from Elasticsearch is exceedingly verbose, and contains terminology that isn't very user-friendly, like "all shards failed".
Is there a way I can offer the user a more meaningful error message (say - "bad predicate"). Ideally, the users search string would be validated without an Elasticsearch round-trip, but I'll settle for a simpler error message however I can get it.
The error message returned by Elasticsearch is verbose but for parsing errors like these, Elasticsearch throws a QueryParsingException. If you examine the error message closely, you'll find the string QueryParsingException towards the end of the entire error message. This is the exception (and its message) you are interested in. For example, when I spelt must as mus2t in a search request, I get a huge error message by Elasticsearch and below is the last part of the error message.
QueryParsingException[[<index name>] bool query does not support [mus2t]]; }]
I got this when I spelt must as mus2t. You can parse and extract out this error message.
You can use validation api.
For following query
var validateResponse = client.Validate<Document>(descriptor => descriptor
.Explain()
.Query(query => query
.QueryString(qs => qs
.OnFields(f => f.Name)
.Query("AND"))));
you will get
org.elasticsearch.index.query.QueryParsingException: [indexname]
Failed to parse query [AND];
org.apache.lucene.queryparser.classic.ParseException: Cannot parse
'AND': Encountered " <AND> "AND "" at line 1, column 0. Was expecting
one of:
<NOT> ...
"+" ...
"-" ...
<BAREOPER> ...
"(" ...
"*" ...
<QUOTED> ...
<TERM> ...
<PREFIXTERM> ...
<WILDTERM> ...
<REGEXPTERM> ...
"[" ...
"{" ...
<NUMBER> ...
<TERM> ...
"*" ...
Still not so perfect for end user and it requires round-trip to ES, but maybe it will be helpful.

Path pattern matching /

I'm trying to build a response descriptor for calls to the Dropbox metadata API.
Using the DBMetadata class from the Dropbox OS X SDK, here is my mapping:
RKObjectMapping *metadataMapping;
metadataMapping = [RKObjectMapping mappingForClass:[DBMetadata class]];
[metadataMapping addAttributeMappingsFromDictionary:#{#"thumb_exists": #"thumbnailExists",
#"bytes" : #"totalBytes",
#"modified" : #"lastModifiedDate",
#"client_mtime": #"clientMtime",
#"path" : #"path",
#"is_dir" : #"isDirectory",
#"hash" : #"hash",
#"size" : #"humanReadableSize",
#"root" : #"root",
#"icon" : #"icon",
#"rev" : #"rev",
#"revision" : #"revision",
#"is_deleted" : #"isDeleted"}];
[metadataMapping addRelationshipMappingWithSourceKeyPath:#"contents"
mapping:metadataMapping];
Here is my Response Descriptor (As much as I'd like to, I can't use :root:path, see NOTE 1):
RKResponseDescriptor *metadataResponse;
metadataResponse = [RKResponseDescriptor responseDescriptorWithMapping:metadataMapping
method:RKRequestMethodGET
pathPattern:#"metadata/dropbox:path"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.manager addResponseDescriptor:metadataResponse];
The manager is setup as:
NSURL *baseAPIURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#://%#/%#/", kDBProtocolHTTPS, kDBDropboxAPIHost, kDBDropboxAPIVersion]];
self.manager = [RKObjectManager managerWithBaseURL:baseAPIURL];
self.manager.requestSerializationMIMEType = RKMIMETypeJSON;
The problem is that the #"metadata/dropbox:path" path pattern always fails:
DBMetadata *root;
root = [[DBMetadata alloc] initWithDictionary:#{#"root": #"dropbox",
#"path": #"/"}];
[self.manager getObject:root
path:#"metadata/dropbox/"
parameters:#{#"list": #"false"}
success:...
failure:...];
Result:
E restkit.network:RKObjectRequestOperation.m:213 GET
'https://api.dropbox.com/1/metadata/dropbox/?list=false' (200 OK / 0
objects) [request=0.0957s mapping=0.0000s total=0.0968s]: Error
Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response
descriptors match the response loaded." UserInfo=0x6000000ee900
{NSLocalizedFailureReason=A 200 response was loaded from the URL
'https://api.dropbox.com/1/metadata/dropbox/?list=false', which failed
to match all (0) response descriptors:,
NSErrorFailingURLStringKey=https://api.dropbox.com/1/metadata/dropbox/?list=false,
NSErrorFailingURLKey=https://api.dropbox.com/1/metadata/dropbox/?list=false,
NSUnderlyingError=0x6000000569b0 "No mappable object representations
were found at the key paths searched.", keyPath=null,
NSLocalizedDescription=No response descriptors match the response
loaded.}
But if I set the path pattern in the response descriptor to a static string (#"metadata/dropbox/"), it works:
I restkit.network:RKObjectRequestOperation.m:220 GET
'https://api.dropbox.com/1/metadata/dropbox/?list=false' (200 OK / 1
objects) [request=0.1027s mapping=0.0014s total=0.1034s]
Is it not possible to pass "/" as a path pattern parameter?
I also noticed that the error says that the response failed to match all (0) response descriptors. Shouldn't it be (1) in this case?

Trouble Parsing XML using Ruby XML Parser

I am having trouble parsing some returned XML using this command: XML::Parser.string(xml_string).parse
Here is the XML I am trying to parse:
<div style=\"border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;\">
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: HTTP_USER_AGENT</p>
<p>Filename: test</p>
<p>Line Number: test</p>
</div><?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
<review>
<reviewer><![CDATA[test]]></reviewer>
<ip><![CDATA[test]]></ip>
rating><![CDATA[test]]></rating>
<content><![CDATA[test.]]></content>
<date><![CDATA[test]]></date>
</review>
</response>
I get this error:
Fatal error: XML declaration allowed only at the start of the document at :10.Fatal error: Extra content at the end of the document at :11.
LibXML::XML::Error: Fatal error: Extra content at the end of the document
What is going on here?
Your string is not a valid XML document; it appears to be two documents concatenated together. (The first one is a "<div>" the second one is a "<response>".)
Try separating them into two strings and parsing each of them separately.
When you are fetching xml_string, I believe you need to set the user agent. You are not providing a user agent so the server serving the XML is choking.
Use this code to add a user agent to your request:
resp = http.post(path, query, {'User-Agent' => "Ruby"})

Resources