d3.json getting data is undefined - javascript

I am using URL in d3.json function, the data is showing undefined.
My code here
==============
var jsonURL = "http://192.168.7.102:8080/restful/traffic/json/get";
d3.json(jsonURL, function(error, data){
alert(data);
});
When it is executed data is showing undefined. I created restful web service application to get the data using above URL it returns JSONArray.
Application Code
#GET
#Path("/json/get")
#Produces(MediaType.APPLICATION_JSON)
public JSONArray startReading() throws JSONException {
String json = null;
String newJson = null;
try {
URL url = new URL("http://192.168.7.102:3000/data/traffic");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((json = br.readLine()) != null) {
newJson = json;
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray(newJson);
return array;
}
When I access the URL in the browser data is displaying. But in d3.json function it is showing undefined instead of data. Due to that, I am not able to display the graph in the browser. Please guide me where I was doing wrong.

var data;
d3.json("http://192.168.7.102:8080/restful/traffic/json/get", function(error, json) {
if (error) return console.warn(error);
data = json;
visualizeit();
});
Have a look at - https://github.com/mbostock/d3/wiki/Requests

Related

Queries can not be applied to a response content of type 'System.Net.Http.StreamContent'. The response content must be an ObjectContent

I am trying to download a file using knockout v3.2.0, webapi, odata and get this error when I try to return the file as HttpResponseMessage.
Here is my controller code:
[EnableQuery]
public HttpResponseMessage GetAttachment([FromODataUri] int key)
{
try
{
DataAccess.Attachment a = db.Attachments.Where(x => x.AttachmentId == key).FirstOrDefault();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream memStream = new MemoryStream();
memStream.Write(a.AttachmentData, 0, a.AttachmentData.Length);
result.Content = new StreamContent(memStream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition.FileName = a.AttachmentName;
return result;
//return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception exception)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception.Message);
return null;
}
}
That's how I am trying to download from JavaScript:
self.downloadDocument = function (attachmentId) {
var serviceRequestUrl = dbhdd.buildUrl.buildSPContextUrl("/api/Attachments(" + 1 + ")");
window.location.href = serviceRequestUrl;
};
Which gives me this error- Queries can not be applied to a response content of type 'System.Net.Http.StreamContent'. The response content must be an ObjectContent.
I am relatively new to this. Any guidance in fixing this/alternate approach will be highly appreciated.
So I removed [EnableQuery] and it worked both in IE and Chrome!

How to send PDF blob to MVC controller

I've generated a PDF report using JSRepoprts library. The output result is a blob that can be downloaded to the "Downloads" folder. What I need to do is to save the blob in a specific folder on the server. I tried to send the blob using XMLHttpRequest, but I'm receiving the request with empty content in the controller.
The code I wrote is the following
jsreports.export({
format: 'pdf',
report_def: def,
datasets: data_sources,
outputHandler: function (pdfBlob) {
$('.report-output-pdf').attr('src', URL.createObjectURL(pdfBlob));
var xhr = new XMLHttpRequest();
xhr.open('GET', '/reports/saveReport', true);
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send(pdfBlob);
}
});
On the server side (MVC Controller) the code is:
public ActionResult saveReport()
{
try
{
var r = Request;
int l = Request.ContentLength; // Received 0
byte[] ba = r.BinaryRead(r.ContentLength);
return Json(r, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
Result as shown in debugger
Any one have an idea that help me saving the pdf blob to specific directory using the correction of the code above or any other idea?

Unable to open pdf file in new tab

I have one requirement where in html page if user click on button then javascript function gets called and in that function ajax call will fetch content of the pdf file from server.
Please find the rest controller as below
#RequestMapping(value = UriMapping.GET_PDF_PATH, method = RequestMethod.POST)
public #ResponseBody WebServiceResponse getPdfPath(HttpServletRequest req,
#RequestParam String fileName, HttpServletResponse response) {
WebServiceResponse res = new WebServiceResponse();
FileInputStream fis = null;
try {
if(!CommonUtil.isBlank(fileName)) {
String filePath = FieldConstant.PDF_PATH + fileName;
File f = new File(filePath);
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline;filename=" + f.getName() );
fis = new FileInputStream(f);
DataOutputStream os = new DataOutputStream(response.getOutputStream());
response.setHeader("Content-Length", String.valueOf(f.length()));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
fis.close();
} else {
res.setSucess(false);
res.setReturnMessage("Something Went Wrong While opening file path !");
}
} catch (Exception e) {
LOGGER.error(e.toString());
res.setSucess(false);
res.setReturnMessage("Something Went Wrong While opening file path !");
}
LOGGER.info("Response" + res.toString());
return res;
}
FieldConstant.PDF_PATH is fixed path at server where all pdf files resides.
Below is the client side jquery function where in I have used window.open() function to open pdf in new tab.
function test(count){
var fileName = pdfGlobal[count].name;
if(fileName != undefined && fileName != "") {
var param = {
"fileName" :fileName
}
$.ajax({
url : '../content/getPdfPath',
type : 'post',
dataType : "json",
data : param,
error : function(error,jqXHR, exception) {
errorMessage(exception);
},
success : function(data) {
if (data) {
window.open(data,'_blank');
} else{
errorMessage(data.returnMessage);
}
}
});
}
}
I am getting parsing error like below
Now as the error suggest I found the % in first place of the response !
Please help me with this.. I know this is not a big issue but I am confused about what goes wrong. Simply not able to find the root cause ...
Thanks in advance.
The ajax is expecting a JSON in return, there is no need for you to use ajax, you can just use window.open, sending fileName by get
window.open('../content/getPdfPath?fileName='+fileName,'_blank');
So you have to change your controller to
#RequestMapping(value = UriMapping.GET_PDF_PATH, method = RequestMethod.GET)

Send image from one device to another through node.js in android

I want to send image from one device to another so i have created that thing through node.js. i have converted the image into base64 and then into string and then send it to node.js server and decoded that string into another device and everythig works perfect. I have used socket.io. Now the problem arises as i have received the string as json response from node.js the full response is not getting half of response is being trimmed somewhere. So basically i am not getting full JSONRESPONSE. Here is my node.js code.
onLine[data.to].emit('newPrivateMessage1',{from:name, img:data.img.toString('base64'), type:'Private Msg1'})
And here is my first device from where i am sending image.
JSONObject json1 = new JSONObject();
String filepath = Environment.getExternalStorageDirectory().toString()+"/1.png";
File file = new File(filepath);
String itemname = getIntent().getStringExtra("itemname");
try {
#SuppressWarnings("resource")
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
Log.e("TAG", "IMAGEFATABYTE:::" + imageData);
imageInFile.read(imageData);
String imageDataString = android.util.Base64.encodeToString(imageData, 0);
json1.put("img", imageDataString);
json1.put("to", itemname);
Log.e("TAG", "MESSAGE:::" + json1);
socket.emit("privateMessage1", json1);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Here is my second device to get response from json
String josn = getIntent().getStringExtra("pvtjson");
Log.e("TAG5", "IMAGEJSON" + josn);
try {
JSONObject jobj = new JSONObject(josn);
jobj.get("img");
byte[] decodedString = Base64.decode(jobj.get("img").toString(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
iv.setImageBitmap(decodedByte);
} catch (JSONException e) {
e.printStackTrace();
}

generate csv from mvc web api httpresponse and receive it by angularjs for download

I am trying to generate a CSV file from my web api and receive that file through angularjs. I have an API controller like below:
[HttpPost]
public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
{
var output = new byte[] { };
if (fieldParams!= null)
{
using (var stream = new MemoryStream())
{
this.Serialize(fieldParams, stream);
stream.Flush();
output = stream.ToArray();
}
}
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(output) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Fields.csv"
};
return result;
}
In my angularjs, i have this:
$scope.save = function () {
var csvInput= extractDetails();
// File is an angular resource. We call its save method here which
// accesses the api above which should return the content of csv
File.save(csvInput, function (content) {
console.log(content);
// only creates a csv file with "[object Object]" written in it
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURI(content.Parameters);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.csv';
hiddenElement.click();
});
};
Lets say for example, in my API controller, the content of response is
output
{byte[152]}
[0]: 83
[1]: 101
[2]: 44
[3]: 67
[4]: 10
When I receive this in angularjs and I put the value of content in the console log (chrome), this is what I get:
{Parameters: Array[1], $promise: Object, $resolved: true, $get: function, $save: function…}
0:"S"
1: "e"
2: ","
3: "C"
4: "↵"
$promise: object
$resolved: true`
Why did the content received in the angularjs contain characters
already instead of a byte of array?
How can I control the content in such a way that I will only use
the csv related data and remove $promise and $resolved? Why are they included in the first place? How to remove them?
What is the proper way of generating a csv if what I am doing is
wrong? :|
Forgot to update this, but i now found a way to solve this:
There will be two API's, one (POST) will remember the data to be used in the processing and another one (GET) which will dispense the file.
POST:
[HttpPost]
public async Task<HttpResponseMessage> BuildFile(FileParameters fileParams)
{
var guid = Guid.NewGuid().ToString();
if (fileParams!= null)
{
await Task.Run(() => FileContents.Add(guid, fileParams));
return this.Request.CreateResponse(HttpStatusCode.OK, new { Value = guid });
}
return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid data");
}
In AngularJs, remember the guid returned and pass this to another api:
location.href = '/api/file/generatefile' + '?guid=' + generatedGuidFromAPI + '&reportName=' + $scope.reportName;
And here is the generatefile API controller in MVC:
GET:
[HttpGet]
public async Task<HttpResponseMessage> GenerateFile(string guid, string reportName)
{
byte[] output = null;
if (FileContents.ContainsKey(guid))
{
await Task.Run(() =>
{
using (var stream = new MemoryStream())
{
this.CreateFile(FileContents[guid], stream);
stream.Flush();
output = stream.ToArray();
}
});
}
FileContents.Remove(guid);
if (output != null)
{
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(output) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = reportName + ".csv"
};
return result;
}
return this.Request.CreateErrorResponse(HttpStatusCode.NoContent, "No record found");
}
using location.href will cause the browser to automatically download the file, asking you whether to save it or not.
Here's how I do it: (tested in chrome)
// WebAPI controller action
public IHttpActionResult Get(string rpt, DateTime date)
{
List<DailyMIReportViewModel> list = new List<DailyMIReportViewModel>();
// Do some stuff to generate list of items
// Download Requested
if (rpt == "dailymidl")
{
// Create byte array of csv
byte[] csvData = WriteCsvWithHeaderToMemory(list);
// create FileContentResult of cdv byte array
FileContentResult result = new FileContentResult(csvData, "application/octet-stream");
// set filename in FileContentResult
result.FileDownloadName = "Report.csv";
return Ok(result);
}
// Data Requested
return Ok(list);
// Client-side angularjs
// Called on button click
$scope.generateMIDownload = function (forDate) {
// Using $resource to return promise with FileContentResult payload
reportsRepository.dailymidl(forDate).$promise.then(
function (data) {
//ok
// NOTE: the base64 part is what got it working
var dataUrl = 'data:application/octet-stream;base64,' + data.FileContents
var link = document.createElement('a');
angular.element(link)
.attr('href', dataUrl)
.attr('download', data.FileDownloadName)
.attr('target','_blank')
link.click();
},
function (response) {
//not ok
});
}
// Reports Repository (for ref)
angular.module('msgnr').factory('reportsRepository', function ($resource) {
return {
dailymidl: function (date) {
return $resource('/api/Report/', { rpt: 'dailymidl', date: date, toDate: date }).get();
}
}
});
Incase it helps anyone else.

Categories