How to get all versions of an object in Google cloud storage bucket? - google-cloud-storage

In a web page hosted in Google cloud storage, I will like to show revision history, which require listing all versions of the object.
Sending GET request to the bucket with ?versions parameter return list versions all objects. Is there any way to list all versions of a single object, as in gsutil ls -la, in javascript?

There is not. The closest you can do is to use versions=true and prefix=YOUR_OBJECT_NAME.
GCS will respond with a listing of objects beginning with all of the versions of your object and continuing on to any other objects that begin with YOUR_OBJECT_NAME. You'll have to check those items to see when the listing runs out of versions of your object and moves on to other objects.
If it so happens that only one object begins with YOUR_OBJECT_NAME (for example, your object is "foo.txt" and there are no files named, say, "foo.txt.backup", you will get exactly the files you want. You probably don't want to rely on this as a general practice, though.

Brondon's answer work with XML, but not with gapi client.
/**
* Get versions meta data of the object.
* #return {goog.async.Deferred} return history of the object.
*/
mbi.data.Object.prototype.history = function() {
var df = new goog.async.Deferred();
var use_gapi = true;
var name = this.getName();
if (use_gapi) {
// GAPI does not return result for versions request.
var params = {
'bucket': this.getBucketName(),
'versions': true,
'prefix': name
};
// console.log(params);
var req = gapi.client.rpcRequest('storage.buckets.get',
mbi.app.base.GAPI_STORAGE_VERSION, params);
req.execute(function(json, row) {
if (json) {
df.callback(json);
} else {
df.errback();
throw new Error(row);
}
});
} else {
var xm = mbi.data.Object.getXhr();
var uri = new goog.Uri(this.getUrl());
uri.setParameterValue('versions', 'true');
uri.setParameterValue('max-keys', '25');
uri.setParameterValue('prefix', name);
var url = uri.setPath('').setFragment('').toString();
xm.send(url, url, 'GET', null, {}, 1, function(e) {
var xhr = /** #type {goog.net.XhrIo} */ (e.target);
if (xhr.isSuccess()) {
var xml = xhr.getResponseXml();
// console.log(xml);
var json = mbi.utils.xml.xml2json(xml);
var items = json['ListBucketResult']['Version'];
var versions = goog.isArray(items) ? items : items ? [items] : [];
versions = versions.filter(function(x) {
return x['Key'] == name;
});
df.callback(versions);
} else {
df.errback(xhr.getStatus() + ' ' + xhr.getResponseText());
}
});
}
return df;
};
GAPI return as follow without version meta:
[
{
"id": "gapiRpc",
"result": {
"kind": "storage#bucket",
"id": "mbiwiki-test",
"name": "mbiwiki-test",
"timeCreated": "2013-08-20T01:18:46.957Z",
"metageneration": "9",
"owner": {
"entity": "group-00b4903a97262a358b97b95b39df60893ece79605b60280ad389c889abf70645",
"entityId": "00b4903a97262a358b97b95b39df60893ece79605b60280ad389c889abf70645"
},
"location": "US",
"website": {
"mainPageSuffix": "index.html",
"notFoundPage": "error404.html"
},
"versioning": {
"enabled": true
},
"cors": [
{
"origin": [
"http://static.mechanobio.info",
"http://mbinfo-backend.appspot.com",
"https://mbinfo-backend.appspot.com",
"http://localhost",
"chrome-extension://pbcpfkkhmlbicomenogobbagaaenlnpd",
"chrome-extension://mhigmmbegkpdlhjaphlffclbgkgelnbe",
"chrome-extension://jhmklemcneaienackijjhdikoicmoepp"
],
"method": [
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"PATCH"
],
"responseHeader": [
"content-type",
"Authorization",
"Cache-Control",
"x-goog-meta-reviewer"
]
}
],
"storageClass": "STANDARD",
"etag": "CAk="
}
}
]

Related

Can't access Nested array object flutter

I have set of data, with some details,when i try to display the the one value returns null,other 2 data is fine,but if i try to show other data it's shows null,if i try to add that to setState,everything become null,There is no problem when i get the "Description","imagepath" i can show it, but the data from the replys object doesn't show
JSON
{
"doc": {
"image": {
"Description": "tested",
"replay": " ",
"Image_Rating": 0,
"replay_status": 0,
"Report_Date": "1591228800",
"Status": 1,
"_id": "5ed88ae73025a4445568ece3",
"image_path": "http://xxx.xxx.xxx.xxx:xxx/area_images/1670281356001.jpg",
"Created_User_Id": "5ed22c2507a33e2c1cf3a3a5",
"Branch_Id": "5ed22bf807a33e2c1cf3a3a4",
"image_temp_path": "http://xxx.xxx.xxx.xxx:xxx/area_images_temp/1670281356001.jpg",
"Order_Id": 32425,
"reg_date": "1591249638163",
"Area_Id": "5dc11c4046c214298f85e2e0",
"Section_Id": "5dc1097546c214298f85e2ae",
"Report_Time_Type": 1,
"mapperId": "5ed22c4207a33e2c1cf3a3a6",
"Created_At": "Thursday, June 4th, 2020, 11:17:18 AM",
"__v": 0
},
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
}
}
Code
Future<String> getImageView(String imageid) async {
Future token = SharedPrefrence().getToken();
token.then((data) async {
var token = data;
var response = await http.post(Urls.Image_Details,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
},
body: json.encode({
"imageId": imageid,
}));
if (response.statusCode == 200) {
try {
var resp = response.body;
Map<String, dynamic> value = json.decode(resp);
var name = value['doc']['image'];
Description = name["Description"].toString();
image_path = name["image_path"].toString();
replay = name["replays"]["replay"].toString();
setState(() {
Description = name["Description"].toString();
image_path = name["image_path"].toString();
// replay = name["replays"]["replay"].toString();
});
} catch (e) {
e.toString();
}
}
});
}
"replays" is an array. Try this: name["replays"][0]["replay"].toString()
By adding [0] it will get your first object from that array.
EDIT:
After looking at your json some more I see that name is the wrong object.
"replays" is a member of "doc" not of "image".
I think this should work:
replay = value['doc']["replays"][0]["replay"].toString();
The problem is
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
This is a List of Maps. So as we access the first element in the list you should use
replay= value['doc']["replays"][0]["replay"].toString();
that is the zeroth element of the list.

How to traverse JSON model?

Image
Controller.js
item: function(evt) {
var list = sap.ui.getCore().byId('appListId');
var sItem = list.getSelectedItem();
var oBindingContext = sItem.getBindingContext('products');
var sPath = oBindingContext.sPath;
console.log(sPath); // get path /collection/0/App/0
var context = sap.ui.getCore().byId("appListId").getModel('products')
.getContext(sPath);
var start = sPath.lastIndexOf("/") + 1;
var appIndex = sPath.substring(start, sPath.length);
this.router.navTo("selectedAppRecord", {
catIndex : this.subCatIndex,
appIndex : appIndex
});
}
Path of JSON Array :
get this path /collection/0/App/0
I have an JSON array :
{
"collection": [{
"model": "08 Report Fraud",
"App": [{
"App": "COUNCIL001",
"description": "Benefit Fraud",
"module": "08 Report Fraud",
"iConClass": "icon-devil",
"UserSpecific": "Yes"
}]
}]
}
finally my goal is how to get this UserSpecific key in control side.
You can use the getProperty function of the BindingContext to get relative properties.
var oItem = sap.ui.getCore().byId('appListId').getSelectedItem();
oItem.getBindingContext('products').getProperty('UserSpecific');
In your handler function I would recommend to get the current item from the event:
oEvent.getSource() || oEvent.getSource().getSelectedItem()
Depending on the type of event (ListItem#select or List#selectionChange).

Rearrrange populated json result in mongoose

A simple json response for Post.find().populate("name") will return json result as follow. Note: The focus of the question is to rearrange the "name":"Alex" in json to the final structure as shown. Ignore the part that need hiding _id and __v. Thanks.
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"postedBy": {
"_id": "54cd6669d3e0fb1b302e54e4",
"name": "Alex",
"__v": 0
},
"__v": 0
},
...
]
How could i rearrange and display the entire json as follow?
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"name": "Alex"
},
...
]
You can use the lean() method to return a pure JSON object (not a mongoose document) that you can then manipulate using lodash helper methods such as map(), like in the following example:
Post.find()
.populate("name")
.lean().exec(function (err, result) {
if(result){
var posts = _.map(result, function(p) {
p.name = p.postedBy.name;
p.postedBy = undefined;
return p;
});
console.log(posts);
}
});
You can disable the "__v" attribute in your Schema definitions by setting the versionKey option to false. For example:
var postSchema = new Schema({ ... attributes ... }, { versionKey: false });
As follow-up to your question on rearranging the order of the properties in the JSON, JS does not define the order of the properties of an object. However, you
can use both the JSON.parse() and JSON.stringify() methods to change the order, for example
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
console.log(json);
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
console.log(k);
Check the demo below.
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
pre.innerHTML = "original: " + JSON.stringify(json, null, 4) + "</br>Ordered: " + JSON.stringify(changed, null, 4);
<pre id="pre"></pre>

jsTree: with lazy loading the plugin "dnd" is not working

I'm using jsTree (latest version) in my web app. I have a lot of nodes to display in the tree, so I am using lazy loading otherwise I would run into a time out.
When the tree is loaded, the user can pick values from a second tree and move them into the lazy loaded tree (jsTree plugin "dnd"). Both tree have the jsTree plugin "dnd" installed. But I can not drop a element into the lazy loaded tree, when I try to do so the node to be dropped is having an icon with a red cross (indication: not allowed here).
This is the code for the lazy loaded tree:
$('#target_tree').jstree({
'core' : {
'data' : {
"url" : "get_current_hierachy",
"data" : function (node) {
return {'p_parent_id': node.id};
},
"dataType": "json",
"check_callback": true
}
},
"plugins" : ["dnd"]
});
When I load some data in the first tree without the lazy loading, the drag'n'drop is working as expected.
When I load data in the first tree with lazy loading, the drag'n'drop is not working any more.
Any help would be greatly appreciated.
Try this ...
$(document).ready(function () {
$('#target_tree').jstree({
'core': {
'data': {
"url": function (node) {
var url;
if (node.id == '#') {
url = "getRootNode";
} else {
var id = $(node).data("id");
url = "getChildNode?nodeid=" + id;
}
return url;
},
"data": function (node) {
return { "id": node.id };
},
"type": "GET",
"dataType": "json",
"contentType": "application/json charset=utf-8",
},
'check_callback': true,
},
"plugins": ["dnd"]
});
});
I think you need to prepare url

Getting series and values from CSV data in Zingchart

While creating mixed chart in Zingchart we can pass the type attribute values with values array. But I'm not sure when reading data from CSV how this can be achieved.
I want to create mixed chart as on fiddle link below but data is to be read from a csv file.
var myConfig =
{
"type":"mixed",
"series":[
{
"values":[51,53,47,60,48,52,75,52,55,47,60,48],
"type":"bar",
"hover-state":{
"visible":0
}
},
{
"values":[69,68,54,48,70,74,98,70,72,68,49,69],
"type":"line"
}
]
}
zingchart.render({
id : 'myChart',
data : myConfig,
height: 500,
width: 725
});
<script src="https://cdn.zingchart.com/zingchart.min.js"></script>
<div id="myChart"></div>
I put together a demo for you using the sample data you provided in one of your related questions. If you go to this demo page and upload the CSV you originally provided, you should get this chart:
ZingChart includes a CSV parser for basic charts, but a more complex case like this requires a bit of preprocessing to get your data where it needs to be. I used PapaParse for this demo, but there are other parsing libraries available.
Here's the JavaScript. I'm using a simple file input in the HTML to get the CSV.
var csvData;
var limit = [],
normal = [],
excess = [],
dates = [];
var myConfig = {
theme: "none",
"type": "mixed",
"scale-x": {
"items-overlap":true,
"max-items":9999,
values: dates,
guide: {
visible: 0
},
item:{
angle:45
}
},
"series": [{
"type": "bar",
"values": normal,
"stacked": true,
"background-color": "#4372C1",
"hover-state": {
"visible": 0
}
}, {
"type": "bar",
"values": excess,
"stacked": true,
"background-color": "#EB7D33",
"hover-state": {
"visible": 0
}
}, {
"type": "line",
"values": limit
}]
};
/* Get the file and parse with PapaParse */
function parseFile(e) {
var file = e.target.files[0];
Papa.parse(file, {
delimiter: ",",
complete: function(results) {
results.data.shift(); //the first array is header values, we don't need these
csvData = results.data;
prepChart(csvData);
}
});
}
/* Process the results from the PapaParse(d) CSV and populate
** the arrays for each chart series and scale-x values
*/
function prepChart(data) {
var excessVal;
//PapaParse data is in a 2d array
for (var i = 0; i < data.length; i++) {
//save reference to your excess value
//cast all numeric values to int (they're originally strings)
var excessVal = parseInt(data[i][4]);
//date, limit value, and normal value can all be pushed to their arrays
dates.push(data[i][0]);
limit.push(parseInt(data[i][1]));
normal.push(parseInt(data[i][3]));
/* we must push a null value into the excess
** series if there is no excess for this node
*/
if (excessVal == 0) {
excess.push(null);
} else {
excess.push(excessVal);
}
}
//render your chart
zingchart.render({
id: 'myChart',
data: myConfig,
height: 500,
width: 725
});
}
$(document).ready(function() {
$('#csv-file').change(parseFile);
});