Unable to pass URL params into api request - ruby-on-rails

I'm working with the Bing API and when I am making a SOAP request to acquire my campaign stats I'm having trouble passing URL params for date (provided by bootstrap datepicker) to the request.
I keep receiving the following error -
(a:DeserializationFailed) The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter https://adcenter.microsoft.com/v8:ReportRequest. The InnerException message was 'There was an error deserializing the object of type Microsoft.AdCenter.Advertiser.Reporting.Api.DataContracts.Request.ReportRequest. The value '' cannot be parsed as the type 'Int32'.'. Please see InnerException for more details.
It seems to me as though it is not able to receive the values I have set as the start/end date in the params. It is working when the params[:start]/[:end] values are nil
Here is the controller code setting up the date params (datepicker works fine for all other requests):
#Start Bing Reporting Code - set date for request ID
if params[:start].nil?
bing_start_date = DateTime.parse((Date.today - 7).to_s).strftime("%Y-%m-%d")
yearstart = bing_start_date[0,4]
monthstart = bing_start_date[5..6]
daystart = bing_start_date[8..9]
bing_end_date = DateTime.parse((Date.today - 1).to_s).strftime("%Y-%m-%d")
yearend = bing_end_date[0,4]
monthend = bing_end_date[5..6]
dayend = bing_end_date[8..9]
else
bing_start_date = params[:start]
yearstart = bing_start_date[2,4]
monthstart = bing_start_date[5..6]
daystart = bing_start_date[8..9]
bing_end_date = params[:end]
yearend = bing_end_date[2,4]
monthend = bing_end_date[5..6]
dayend = bing_end_date[8..9]
end
Here is the SOAP request body where I set the custom date range (using Savon gem):
soap.body = "<CustomDateRangeEnd i:nil=\"false\"><Day>#{dayend}</Day><Month>#{monthend}</Month><Year>#{yearend}</Year></CustomDateRangeEnd><CustomDateRangeStart i:nil=\"false\"><Day>#{daystart}</Day><Month>#{monthstart}</Month><Year>#{yearstart}</Year></CustomDateRangeStart></Time></ReportRequest>"
It works fine If I just set the yearend/start, monthend/start, dayend/start variables manually like so:
yearstart = '2014'
monthstart = '01'
daystart = '01'
#this would set the start date properly to Jan 1 2014

Foolish mistake. I used the same start index/length and ranges for the 'if' statement as I did for the 'else'. As a result it was throwing and empty string to <day>
The date output for the 'if' was "2014-01-13" and the output for the else was "20140113"
Therefore, I needed to adjust the index/length and ranges like so:
bing_start_date = params[:start]
yearstart = bing_start_date[0,4]
monthstart = bing_start_date[4..5]
daystart = bing_start_date[6..7]

Related

Calling expand entity from SAP Gateway Client

I try to call a GET_EXPANDED_ENTITYSET method of SRA020_PO_TRACKING Project, po tracking project. The following is the method:
METHOD /iwbep/if_mgw_appl_srv_runtime~get_expanded_entityset.
DATA: lv_ponumber TYPE bapiekko-po_number,
lv_leading_msg TYPE boolean.
DATA: lo_api TYPE REF TO cl_sra020_po_tracking_api.
DATA: ls_po_details TYPE cl_sra020_po_tracking_api=>ts_podetails,
lt_return TYPE bapirettab,
lo_msgcontainer TYPE REF TO /iwbep/if_message_container.
DATA: lt_poitem_details TYPE cl_sra020_po_tracking_api=>tt_poitemdetail.
FIELD-SYMBOLS: <fs_return> TYPE bapiret2,
<fs_key_tab> TYPE /iwbep/s_mgw_name_value_pair.
lo_api = cl_sra020_po_tracking_api=>get_instance( ).
*========================================================================================
* Read Entities key values within oData service URL
*========================================================================================
IF it_key_tab IS NOT INITIAL.
LOOP AT it_key_tab ASSIGNING <fs_key_tab>.
CASE <fs_key_tab>-name.
WHEN if_sra020_po_tracking_constant=>cc_po_number.
lv_ponumber = <fs_key_tab>-value.
ENDCASE.
ENDLOOP.
ENDIF.
TRY.
CASE iv_entity_set_name.
WHEN if_sra020_po_tracking_constant=>cc_podetaileddatas.
CALL METHOD lo_api->get_po_details
EXPORTING
iv_item_additional_data = 'X' "#EC NOTEXT
iv_po_number = lv_ponumber
IMPORTING
es_po_details = ls_po_details
et_return = lt_return.
IF NOT lt_return IS INITIAL.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception.
ENDIF.
lt_poitem_details = ls_po_details-poitemdetaildatas.
no_cache( ).
* Return the expanded clauses
APPEND cl_sra020_po_tracking_mpc=>gc_poitemdocflow TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_accounting TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_pricingconditions TO et_expanded_tech_clauses.
APPEND cl_sra020_po_tracking_mpc=>gc_confirmation TO et_expanded_tech_clauses.
CALL METHOD copy_data_to_ref
EXPORTING
is_data = lt_poitem_details
CHANGING
cr_data = er_entityset.
ENDCASE.
CATCH /iwbep/cx_mgw_busi_exception.
lo_msgcontainer = me->mo_context->get_message_container( ).
LOOP AT lt_return ASSIGNING <fs_return> WHERE type EQ 'E' OR type EQ 'A'. "#EC NOTEXT
IF <fs_return>-id EQ 'SRA020'.
lv_leading_msg = abap_true.
ELSE.
lv_leading_msg = abap_false.
ENDIF.
lo_msgcontainer->add_message(
iv_msg_type = <fs_return>-type
iv_msg_id = <fs_return>-id
iv_msg_number = <fs_return>-number
iv_msg_text = <fs_return>-message
iv_msg_v1 = <fs_return>-message_v1
iv_msg_v2 = <fs_return>-message_v2
iv_msg_v3 = <fs_return>-message_v3
iv_msg_v4 = <fs_return>-message_v4
iv_is_leading_message = lv_leading_msg
).
ENDLOOP.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING
textid = /iwbep/cx_mgw_busi_exception=>business_error
message_container = lo_msgcontainer.
ENDTRY.
ENDMETHOD.
Where
if_sra020_po_tracking_constant=>cc_po_number = PONumber
if_sra020_po_tracking_constant=>cc_podetaileddatas = PODetailedDatas
and PODetailedData entity has navigation properties of POItemDetailDatas,POItems,and POList
I try to call the method from Gateway Service Client by executing
/sap/opu/odata/SAP/SRA020_PO_TRACKING_SRV/PODetailedDatas?$expand=POItemDetailDatas,POItems,POList
However I got status code 400 Bad Request instead. What did I miss?
regards
Edit:
The message in the Bad Request says: Error while reading Purchase Order
edit 2:
association screen shot:
navigation screen shot:
Turns out I have to provide PONumber, so that:
PODetailedDatas(PONumber='4500000039')?$expand=POItems
works fine

I get this error, how would i fix it?

//if day is sat/sun, set value to W. calendar.set(year,monthNumberForCalendar,dayOfMonth) if(contract.workingDays.id == mondayToFriday.id)
{
if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){ monthMap.put(dayOfMonth, "W")
URI
/oulhr/leaveView/show
Class
java.lang.NullPointerException
Message
Cannot get property 'id' on null object
//leaveMonths = this.getLeaveMonths(year)
def employeeContract = new Contract()
employeeContract = this.getCurrentContract(employee) leaveMonths = this.getLeaveMonths(year,employeeContract)
/*add leave days to month(e.g Jan). When jan is filled up, add to the following month(.e.g Feb) */
int monthNumber = 0;
The error message is clear.
This is happening because of either workingDays or mondayToFriday is null.
To confidently say:
contract.workingDays.id = mondayToFriday.id
You have to first make sure that contract, contract.workingDays, mondayToFriday are not null.

Json parsing from twitter user_timeline

I am trying to parse the json content from the twitter user_Stream api feed and tried using json.net and javascriptserializer but first need to understand the right format of the json. The file content keeps giving an error that there is some invalid closing or missed closing and I would like to know if someone knows what are the opening and closing tag for one post/activity in the twitter user_stream results. In this file the content begins as follows and ends with "retweeted":false}]
[{"created_at":"Tue May 08 10:30:05 +0000 2012","id":199808381991653377,
"id_str":"199808381991653377",
"text":"#waddehawk Sorry for the misinformation earlier, this should be tomorrow after 2pm.",
"source":"\u003cahref=\"http:\/\/www.awarenessnetworks.com\/home\/\"
"truncated":false,
"in_reply_to_status_id":199796940358156288,
"in_reply_to_status_id_str":"199796940358156288",
"in_reply_to_user_id":333905755,"in_reply_to_user_id_str":"333905755",
"in_reply_to_screen_name":"waddehawk",
"user":{"id":95310018,"id_str":"95310018",
"name":"DBS Bank","screen_name":"dbsbank","location":"Singapore",
"description":"The DBS official channel, we're here Mon-Fri, 9am-6pm. Otherwise, call us at 18001111111 or contact us via www.dbs.com\/contact",
"url":"http: \/\/www.dbs.com","protected":false,
"followers_count":1350,"friends_count":173,"listed_count":58,
"created_at":"Tue Dec 08 00:07:04 +0000 2009","favourites_count":0,"utc_offset":28800,
"time_zone":"Singapore","geo_enabled":false,
"verified":false,"statuses_count":306,"lang":"en",
"contributors_enabled":false,"is_translator":false,
"profile_background_color":"CC0000",
"profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/125391568\/twitter_bg.gif",
"profile_background_image_url_https":
"https:\/\/si0.twimg.com\/profile_background_images\/125391568\/twitter_bg.gif",
"profile_background_tile":false,
"profile_image_url":"http:\/\/a0.twimg.com\/profile_images \/1051424405\/dbslogo_e2_4c_r_normal.gif",
"retweeted":false}]
the different code attempts I have been trying:
Dim stringSplitter() As String = {"{"}
' split the f ile content based on the closing entry tag
sampleResults = Nothing
Try
sampleResults =
post.Split(stringSplitter, StringSplitOptions.RemoveEmptyEntries)
for each entry in sampleResults
Dim jreader2 As JsonTextReader = New JsonTextReader(New StringReader(entry))
entry = "{ " & entry & "}"
Dim js As New JavaScriptSerializer
Dim jrobj As Object = js.DeserializeObject(entry)
For Each crap As Object In CType(jrobj, Array)
Console.WriteLine(crap("id"))
Next
' Or try
Dim jobj As JObject = JObject.Parse(entry)
'Or try
dim jarr as Jarray = JArray.Parse(jarr)
Dim skipFlag As Boolean = False
Dim token As JToken = JObject.Parse(entry)
statid = token.SelectToken("id")
searchTerm = token.SelectToken("matching_rules")
Dim results As List(Of JToken) = jobj.Children().ToList
But the error I get is JsonToken EndArray is not valid for closing jsonType Object

Grails - illegal arguments for java.sql.Date

I'm trying to create an sql.Date by creating a Calendar object on the current date. This is driving me crazy, if i hardcode the date as a string every thing is fine:
def dat = java.sql.Date.valueOf("2011-01-31");
But, if I create the same string in code I'm getting an illegal argument error.
def currentDay = {
def today = Calendar.getInstance();
def dateYear = today.get(Calendar.YEAR);
def dateMonth = today.get(Calendar.MONTH) + 1;
def dateDay =today.get(Calendar.DATE);
def todayDate = (dateYear + "-" + dateMonth + "-" + dateDay);
def todayDateString = todayDate.toString();
def todayDate2 = java.sql.Date.valueOf(todayDateString);
[ today : todayDate2 ]
}
Running this is yielding this stacktrace:
java.lang.IllegalArgumentException
at java.sql.Date.valueOf(Date.java:138)
at java_sql_Date$valueOf.call(Unknown Source)
at samma.TapesController$_closure7.doCall(TapesController.groovy:178)
at samma.TapesController$_closure7.doCall(TapesController.groovy)
at java.lang.Thread.run(Thread.java:619)
I know I'm doing something completely stupid, but I cannot figure out what, nor what a workaround could be.
Thanks
Donald.
Replace all the code above with
def currentDay = {
def todayDate = new java.sql.Date(new Date().time)
todayDate.clearTime()
[today: todayDate]
}
Why are you converting to a string at all? Just make sure your Calendar has the field values that you want, and then call
new java.sql.Date(calendar.getTime().getTime());
Alternatively, given that you just need the millis to be right, I would try to use Joda Time if at all possible - it'll be easier than manipulating a calendar, IMO. You can convert from a Joda Time instant (or whatever) to a long value very easily.
java.sql.Date.valueOf(String date) throws an IllegalArgumentException if the date given is not in the JDBC date escape format (yyyy-mm-dd). The date you are providing has the format yyyy-m-dd, (only one digit month for 1-9) therefore it is invalid.
As a workaround, use SimpleDateFormat to get a two digit month or directly work with dates without intermediate String conversion like Jon Skeet suggests.

Send HTTPService Request in flex 3 with '-' in the URl Paramerters to get Google Feeds

I am developing application in flex 3 which interacts with the Google feeds to produce my results. The URL to which i want to send request is something like this
http://books.google.com/books/feeds/volumes?q=football+-soccer&start-index=11&max-results=10
Now i can send and receive results with q parameter, but in the next two parameters has a '-' (start-index and max-results). I am using HTTPService to send the requeset like this.
SearchService.url = "http://books.google.com/books/feeds/volumes";
SearchService.method = "GET";
SearchService.contentType = "application/x-www-form-urlencoded"
Here SearchService is the HTTPService
var params:Object = new Object();
params.q = searchText;
params.start-index = 11;
params.max-results = 100;
service.SearchService.send(params);
Now my flex IDE throws me a error stating 'Cannot assign a non-reference value'. Only if i send the request with this parameters, i could put pagination in my application. So how can i send HTTPService request with '-' in the URL parameters?
You can do:
var params:Object = new Object();
params["q"] = searchText;
params["start-index"] = 11;
params["max-results"] = 100;
service.SearchService.send(params);
Validated and tested to work properly! :)

Resources