Steps to connec to a odata provider using odata4j - odata4j

I have tried to consume a odata service , but iam getting an error while trying to get entities .
String serviceUrl = "http://services.odata.org/(S(mvnfyllpw41mbzvkme0o0zug))/ODataOData.svc/";
ODataConsumer consumer = ODataConsumers.create(serviceUrl);
// list category names
for (OEntity category : consumer.getEntities("Categories").execute()) {
String categoryName = category.getProperty("Name", String.class).getValue();
System.out.println("Category name: " + categoryName);
}

Related

Spring AMQP + RabbitMQ RPC How to execute/delegate different methods in a class

I spent the entire day trying to get this to work. I've been following the tutorial 5 & 6 for Spring AMQP in the RabbitMQ tutorials page.
Is it possible for a single class to execute a different method based on some property? E.g. Routing key?
I've tried this so far to no avail:
#RabbitListener(bindings = #QueueBinding(
value = #Queue(value = "requests"),
exchange = #Exchange(value = "ourexchange"),
key = "doFunc1")
)
public String func1(long id) {
System.out.println("func1 " + id);
return "func1 " + id;
}
#RabbitListener(bindings = #QueueBinding(
value = #Queue(value = "requests"),
exchange = #Exchange(value = "ourexchange"),
key = "doFunc2")
)
public String func2(long id) {
System.out.println("func2 " + id);
return "func2 " + id;
}
In my client I did this:
public void send() {
System.out.println(" [x] Get func1( account_id: " + accountId + ")");
String response = (String) template.convertSendAndReceive
("ourexchange", "doFunc1", accountId);
System.out.println(" [.] Got '" + response + "'");
System.out.println(" [x] Get func2( account_id: " + accountId + ")");
String response = (String) template.convertSendAndReceive
(exchange.getName(), "doFunc2", accountId);
System.out.println(" [.] Got '" + response + "'");
}
I've got it "somewhat" to work but it appears to work in a round-robin fashion where the first method is called then the next one.
I've already considered the explanation here: Single Queue, multiple #RabbitListener but different services
But since the signatures of both methods look identical I'm not sure it's possible.
Do note that I'm a beginner to the concepts of AMQP (like I've just read about the basics today). Am I doing this right or am I misunderstanding the usage?
The #RabbitListener infrastructure doesn't perform routing based on the routing key. You should use a different queue for each method and let RabbitMQ do the routing at the exchange level.
Alternatively, if you must use a single queue for some reason, you can pass the RECEIVED_ROUTING_KEY as a #Header parameter to your listener and delegate to different methods from the listener.
I've got it "somewhat" to work but it appears to work in a round-robin fashion where the first method is called then the next one.
That's because RabbitMQ sees 2 consumers and will round-robin the messages. You need to use 2 queues or a single method and do the routing therein.

Crunchbase Data API v3.1 to Google Sheets

I'm trying to pull data from the Crunchbase Open Data Map to a Google Spreadsheet. I'm following Ben Collins's script but it no longer works since the upgrade from v3 to v3.1. Anyone had any luck modifying the script for success?
var USER_KEY = 'insert your API key in here';
// function to retrive organizations data
function getCrunchbaseOrgs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Organizations');
var query = sheet.getRange(3,2).getValue();
// URL and params for the Crunchbase API
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
var json = getCrunchbaseData(url,query);
if (json[0] === "Error:") {
// deal with error with fetch operation
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([json]);
}
else {
if (json[0] !== 200) {
// deal with error from api
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([["Error, server returned code:",json[0]]]);
}
else {
// correct data comes back, filter down to match the name of the entity
var data = json[1].data.items.filter(function(item) {
return item.properties.name == query;
})[0].properties;
// parse into array for Google Sheet
var outputData = [
["Name",data.name],
["Homepage",data.homepage_url],
["Type",data.primary_role],
["Short description",data.short_description],
["Country",data.country_code],
["Region",data.region_name],
["City name",data.city_name],
["Blog url",data.blog_url],
["Facebook",data.facebook_url],
["Linkedin",data.linkedin_url],
["Twitter",data.twitter_url],
["Crunchbase URL","https://www.crunchbase.com/" + data.web_path]
];
// clear any old data
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
// insert new data
sheet.getRange(6,1,12,2).setValues(outputData);
// add image with formula and format that row
sheet.getRange(5,2).setFormula('=image("' + data.profile_image_url + '",4,50,50)').setHorizontalAlignment("center");
sheet.setRowHeight(5,60);
}
}
}
This code no longer pulls data as expected.
I couldn't confirm about the error messages when you ran the script. So I would like to show about the clear difference point. It seems that the endpoint was changed from https://api.crunchbase.com/v/3/ to https://api.crunchbase.com/v3.1/. So how about this modification?
From :
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
To :
var url = 'https://api.crunchbase.com/v3.1/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
Note :
From your script, I couldn't also find query. So if the script doesn't work even when you modified the endpoint, please confirm about it. You can see the detail of API v3 Compared to API v3.1 is here.
References :
API v3 Compared to API v3.1
Using the API
If this was not useful for you, I'm sorry.

How does ibm - mobile first get mobile number from security context?

I am following "isRegistered" api from this sample code. I did not understand how we get phone number from security context.
The API that I want to use is:
#Path("/isRegistered")
#GET
#Produces("application/json")
#OAuthSecurity(enabled = true)
#ApiOperation(value = "Check if a phone number is registered",
notes = "Check if a phone number is registered",
httpMethod = "GET",
response = Boolean.class
)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "OK",
response = String.class),
#ApiResponse(code = 401, message = "Not Authorized",
response = String.class),
#ApiResponse(code = 500, message = "Cannot check if phone number is registered",
response = String.class)
})
public Boolean isRegistered() {
//Getting client data from the security context
ClientData clientData = securityContext.getClientRegistrationData();
if (clientData == null) {
throw new InternalServerErrorException("This check allowed only from a mobile device.");
}
String number = clientData.getProtectedAttributes().get(SMSOTPSecurityCheck.PHONE_NUMBER);
return number != null && !number.trim().equals("");
}
How does the security context have the client phone number?
There is a client project as well in this sample. Please refer to the complete sample.
Within the client side logic here, the user is asked to provide the phone number , which is sent to the server in an adapter call:
MainViewController.codeDialog("Phone Number", message: "Please provide your phone number",isCode: true) { (phone, ok) -> Void in
if ok {
let resourseRequest = WLResourceRequest(URL: NSURL(string:"/adapters/smsOtp/phone/register/\(phone)")!, method:"POST")
.....
Now in the adapter code path #Path("/register/{phoneNumber}") notice the following code:
clientData.getProtectedAttributes().put(SMSOTPSecurityCheck.PHONE_NUMBER, phoneNumber);
securityContext.storeClientRegistrationData(clientData);
This is how the phone number made it to the security context.
Run the sample and use a tool such as Wireshark to analyze the data flow between client and server.

Posting related entities in WCF Rest

I have developed a sample WCF REST service that accepts that creates an "Order" object, the method implementation is as shown below:
[Description("Updates an existing order")]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Orders")]
[OperationContract]
public void UpdateOrder(Order order)
{
try
{
using (var context = new ProductsDBEntities())
{
context.Orders.Attach(order);
context.ObjectStateManager.ChangeObjectState(order, System.Data.EntityState.Modified);
context.SaveChanges();
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Order updated successfully.";
}
}
catch (Exception ex)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message + " " + ((ex.InnerException != null) ? ex.InnerException.Message : string.Empty);
}
}
I am trying to consume this service in a client using the "WCF Rest Starter Kit" assemblies. The client side code to consume the service is as below:
var order = new Order(){
OrderId = Convert.ToInt32(ddlCategories.SelectedItem.Value)
};
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
var content = HttpContentExtensions.CreateJsonDataContract<Order>(order);
var updateResponse = client.Post("Orders", content);
The below line
var updateResponse = client.Post("Orders", content);
throws the following error:
Server Error in '/' Application.
Specified argument was out of the range of valid values.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value
I have a similar logic to create an order and its working fine.
I also tried by removing the following lines
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
but still the same error.
Please help me solve this issue.
I have also tried serializing the Order object to XML and changing the RequestFormat of UpdateOrder method to XML. In this case I am getting the following error, if any related entities are populated.
Server Error in '/' Application.
Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException: Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Source Error:
Line 102:
Line 103: var content = HttpContentExtensions.CreateDataContract<Order> (order);
Line 104: var updateResponse = client.Post("Orders", content);
Line 105:
Line 106:
I want to "Update" an order along with the related "Products" through the "Order_X_Products" mapping table.
There is a post here http://smehrozalam.wordpress.com/2010/10/26/datacontractserializer-working-with-class-inheritence-and-circular-references/ that talks about how to deal with circular references when using the DataContractSerializer.

Parsing result from WCF WebHttp Service

I have a very simple WCF service running which returns the following (from a basic new project) xml:
<ArrayOfSampleItem xmlns="http://schemas.datacontract.org/2004/07/WcfRestService1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<SampleItem>
<Id>1</Id>
<StringValue>Hello</StringValue>
</SampleItem>
</ArrayOfSampleItem>
I am then consuming this in a Windows Phone 7 app. The result is coming back fine however I'm having problems parsing the xml. This is the code I am using on the callback after completion of the request:
XDocument xmlDoc = XDocument.Parse(e.Result);
itemsFetched.ItemsSource = from item in xmlDoc.Descendants("SampleItem")
select new Product()
{
Id = item.Element("Id").Value,
StringValue = item.Element("StringValue").Value
};
The collection is not populated with this, when I try adding the namespace:
XNamespace web = "http://schemas.datacontract.org/2004/07/WcfRestService1";
XDocument xmlDoc = XDocument.Parse(e.Result);
itemsFetched.ItemsSource = from item in xmlDoc.Descendants(web + "SampleItem")
The item is found but I get a null exception when it attempts to get the Id value.
Any help would be much appreciated.
Well the xmlns="..." puts the elements and all its descendants in the namespace so you need to use your XNamespace object web anywhere where you access elements:
XDocument xmlDoc = XDocument.Parse(e.Result);
XNamespace web = "http://schemas.datacontract.org/2004/07/WcfRestService1";
itemsFetched.ItemsSource = from item in xmlDoc.Descendants(web + "SampleItem")
select new Product()
{
Id = item.Element(web + "Id").Value,
StringValue = item.Element(web + "StringValue").Value
};