I am writing a service for forwarding our sensor data to Cumulocity platform. I designed the structure so that all the data is first sent to our main tenant and then device data for each customer is forwarded to corresponding tenants with Data Broker.
I can group devices manually and forward by group but I don't want to deal with it every time a new device is added.Sensor data contains customer name. Probably I can add customer name to device properties (like device_type) and use that as a filter but I want to avoid that if possible. So I thought, when a sensor data hits my endpoint, I do something like this:
Look if the device exists in the database.If it exists just publish measurement data.
If not look at the Group database(Just a key-value store containing customer names and managed Object Ids of the corresponding groups from Cumulocity) to see if there is entry for the customer.
If not add an entry and create a group with customer name.Then add the device to the group.
If it exists, just add the device to the group.
I tried adding devices to groups with REST and it works. The problem is I cannot create a device group with REST.
I looked at the Cumulocity API example requests and tried to tweak them a little.
I tried sending POST request to {{url}}/inventory/managedObjects as:
{
"name": "TestDeviceGroup",
"c8y_IsDeviceGroup": {}
}
It returns 201 created but I cannot see the group. When I try to get collection of groups I see it there as a managed object with a new Id.
I tried to add a new device to this object as a child asset.
{{url}}/inventory/managedObjects/{{GroupId}}/childAssets
{
"managedObject": "id:{{deviceId}}"
}
It returns 201 created but device GROUP is not updated.
If I recreate this scenario with a group created with UI and its Id everything works fine and device is added to the group.
As I understand what I create is not a legit device group and that is the main problem. So my question is How can I create device group with REST?
To create the group you were already on the right track you are just missing the correct type. Create your group like this:
POST /inventory/managedObjects
{
"name": "TestDeviceGroup",
"type": "c8y_DeviceGroup",
"c8y_IsDeviceGroup": {}
}
To assign your device to a particular group you can EITHER assign an existing device to an existing group like this (replace the placeholders in <> with your IDs):
POST /inventory/managedObjects/<groupId>/childAssets
{
"managedObject": {"id":"<deviceId>"}
}
Or you can directly create a new device into an existing group like this:
POST /inventory/managedObjects/<groupId>/childAssets
Content-Type: application/vnd.com.nsn.cumulocity.managedobject+json
{
"name": "my device",
"c8y_IsDevice": {}
}
Related
I've got the problem when two people at the same time tries to add each other to friends. So, at first when one person presses add to friends he checks, whether other user's groups doesn't have my ID. If he has, I don't need to create new group - I will just add this group's ID to my list, else - I will create new group. Now, when two people at the same time press that button, they both get the result that group doesn't exist thus they both create a new group. How to solve these kind of problems?
Structure:
"userGroups" : {
"myId1" : {
"generatedGroupId1" : "myFriendID1"
}
}
Update: I've managed to do it: basically in doTransaction I create group if it doesn't exist and then on onComplete I work with already created group. If two people start creating new group, one end up creating it, second one - reading it.
// function
ref.runTransaction(object : Transaction.Handler {
override fun doTransaction(currentData: MutableData): Transaction.Result {
// create group here if data is null
return Transaction.success(currentData)
}
override fun onComplete(
error: DatabaseError?,
committed: Boolean,
currentData: DataSnapshot?
) {
Log.d(TAG, "postTransaction:onComplete:" + error)
// continue doing stuff, group already exists at this point
}
})
}
It's hard to give specific without seeing your code, but the most likely options are (in order of my personal preference):
Base the group ID on the two users in it. If you do this correct, the two users will end up with the same group ID, and it doesn't matter who is first. Creating the groups then becomes a so-called idempotent operation, which means that if you run the same operation multiple times, it will have the same result. For an example of such group IDs, see Best way to manage Chat channels in Firebase
Use a transaction to ensure only one write makes it through. This would mean that the second user ends up reading the group created by the first user, and can then cancel their data creation.
Use a Cloud Function, which can perform more (non-atomic) read operations to check whether the group of users already exists, and reject the request from the second user.
I am creating notification on server side following way
String target = "oxyn"+notif.getTarget().getOid();
log.info("creating notification for target user {}",target);
NotificationFeed notifications= client.notificationFeed("notification",target);
notifications.addActivity(Activity.builder()
.actor(notif.getTarget().getName())
.verb("receive")
.object(notif.getOid()+"")
.foreignID(notif.getTarget().getName()+":"+notif.getOid())
.extraField("message", notif.getMessage())
.extraField("action", notif.getAction())
.extraField("sender", notif.getSender().getOid())
.extraField("oxyn", notif.getOxyn())
.build()).join();
and on client side, when new notification is sent I am calling
notification1 = client.feed('notification', ("oxyn"+me.oid));
notification1.get({mark_seen:false,mark_read:false})
.then(function(data) {
/* on success */
console.log("new : "+data.unseen);
})
.catch(function(reason) { /* on failure */
alert(reason);
});
problem is, my notifications get grouped and if there is more than one new notification (for example 3) properties unseen/unread count still say 1 instead of 3.
so the only workaround I found is to make sure each notification is unique within unique group so I make verb unique...
.verb("receive"++notif.getOid())
it seems to do the job, notifications do not get grouped, but I feel like this is a hack, so
my question is how do I get a correct number for unseen/unread if my notifications are grouped?
Unseen and Unread counts are based on the amount of groups that are unread/unseen, not on the individual activities. Notification feeds support the most common use-case out of the box: Facebook's notification feed.
What you want in this case is to aggregated activities by their id ({{ id }}). When you do that every group will always have 1 activity and every insert will increase the unseen/unread by one.
This is similar to what you are doing except that you don't have to hack the uniqueness on the verb. To do this you need to configure your notification feed group via Stream's Dashboard and change the aggregation format into {{ id }}.
After placing order for a storage in softlayer, I need to get that storage id for a particular order id.The api call i am using, is giving me a list of storage ID. But, if user orders for a storage, only one storage id the user should get right.
So, the api is not properly filtering and not getting a particularly storage id for a particular order id . The rest api, i am using is given below and please tell me what should be the proper filtering ,
"https://[username]:[apikey]#api.softlayer.com/rest/v3/SoftLayer_Account/getIscsiNetworkStorage.json?objectFilter={"networkStorage": {"billingItem": {"nasType": { "operation": "ISCSI"}, "orderItem": {"order": {"id":{"operation":"[orderID]"}}}}}} "
This api is provided by softlayer team
Regards,
Debartha
use this request:
GET https://api.softlayer.com/rest/v3/SoftLayer_Account/getIscsiNetworkStorage?objectMask=mask[billingItem[orderItem[order]]]&objectFilter={"iscsiNetworkStorage": {"billingItem": { "orderItem": {"order": {"id":{"operation":5208963}}}}}}
note: replace 5208963, with your orderID
Basically all the devices must have a billingItem and that billingItem should have orderItem.order.id property, so you can use this filter to get any device using the orderID property, you just to need to make sure that the "iscsiNetworkStorage" value, in the filter, has the same name as the method you are calling (in this case getIscsiNetworkStorage method ), but without the pre-fix "get" and it must start with lower case e.g.
getIscsiNetworkStorage -> iscsiNetworkStorage
Regards
I want to authorize a storage with VMs. For that I need to have all the VM ID's for a storage and those I get using the following call:
https://[username]:[apikey]#api.softlayer.com/rest/v3/SoftLayer_Network_Storage_Iscsi/9653497/getAllowableVirtualGuests?objectMask=mask[id,fullyQualifiedDomainName]
This gives me all the VM ID's corresponding to 9653497 (storage/order ID). However, I need to have all those storage ID's (like 9653497) which are not assigned to any of the VM's ID. I am using below call to get all storage ID:
https://[username]:[apikey]#api.softlayer.com/rest/v3/SoftLayer_Account/getNetworkStorage?objectMask=mask[id,username,nasType,storageType, billingItem[description,location[id,longName]]]&objectFilter={"networkStorage":{"nasType":{"operation":"ISCSI"},"billingItem":{"description":{"operation":"Endurance Storage"}}}}
the data that you are using for the filter probably are wrong, try to call the get object method GET /SoftLayer_Network_Storage/9653497/getObject?objectMask=mask[nasType,billingItem[description]] and see if the values of the request are the same as of your objectFilter
The filter in your request, gets Block Storage("nasType":{"operation":"ISCSI"}), maybe you need the File Storage. We can remove it to get more "Endurance" items (Block and File).
Please try the following removing some filters:
https://[username]:[apikey]#api.softlayer.com/rest/v3/SoftLayer_Account/getNetworkStorage?objectMask=mask[id,username,nasType,storageType, billingItem[description,location[id,longName]]]&objectFilter={ "networkStorage": { "billingItem": { "description": { "operation": "Endurance Storage" } } } }
Method: GET
if we don't want to get only Endurance, we can remove that filter too.
But when trying to add some properties using objectMasks to SoftLayer_Account::getNetworkStorage like allowableVirtualGuests, that property is not present in SoftLayer_Network_Storage.
For that reason the unique way to get “getAllowableVirtualGuests” is using SoftLayer_Network_Storage::getAllowableVirtualGuests
Question
How do I return different results for the same resource?
Details
I have been searching for some time now about the proper way to build a RESTful API. Tons of great information out there. Now I am actually trying to apply this to my website and have run into a few snags. I found a few suggestions that said to base the resources on your database as a starting point, considering your database should be structured decently. Here is my scenario:
My Site:
Here is a little information about my website and the purpose of the API
We are creating a site that allows people to play games. The API is supposed to allow other developers to build their own games and use our backend to collect user information and store it.
Scenario 1:
We have a players database that stores all player data. A developer needs to select this data based on either a user_id (person who owns the player data) or a game_id (the game that collected the data).
Resource
http://site.com/api/players
Issue:
If the developer calls my resource using GET they will receive a list of players. Since there are multiple developers using this system they must specify some ID by which to select all the players. This is where I find a problem. I want the developer to be able to specify two kinds of ID's. They can select all players by user_id or by game_id.
How do you handle this?
Do I need two separate resources?
Lets say you have a controller name 'Players', then you'll have 2 methods:
function user_get(){
//get id from request and do something
}
function game_get(){
//get id from request and do something
}
now the url will look like: http://site.com/api/players/user/333, http://site.com/api/players/game/333
player is the controller.
user/game are the action
If you use phil sturgeon's framework, you'll do that but the url will look like:
http://site.com/api/players/user/id/333, http://site.com/api/players/game/id/333
and then you get the id using : $this->get('id');
You can limit the results by specifying querystring parameters, i.e:
http://site.com/api/players?id=123
http://site.com/api/players?name=Paolo
use phil's REST Server library: https://github.com/philsturgeon/codeigniter-restserver
I use this library in a product environment using oauth, and api key generation. You would create a api controller, and define methods for each of the requests you want. In my case i created an entirely seperate codeigniter instance and just wrote my models as i needed them.
You can also use this REST library to insert data, its all in his documentation..
Here is a video Phil threw together on the basics back in 2011..
http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
It should go noted, that RESTful URLs mean using plural/singular wording e.g; player = singular, players = all or more than one, games|game etc..
this will allow you to do things like this in your controller
//users method_get is the http req type.. you could use post, or put as well.
public function players_get(){
//query db for players, pass back data
}
Your API Request URL would be something like:
http://api.example.com/players/format/[csv|json|xml|html|php]
this would return a json object of all the users based on your query in your model.
OR
public function player_get($id = false, $game = false){
//if $game_id isset, search by game_id
//query db for a specific player, pass back data
}
Your API Request URL would be something like:
http://api.example.com/player/game/1/format/[csv|json|xml|html|php]
OR
public function playerGames_get($id){
//query db for a specific players games based on $userid
}
Your API Request URL would be something like:
http://api.example.com/playerGames/1/format/[csv|json|xml|html|php]