JavaScript and Google Chrome, Input Streams and Arrays - javascript

So my title might not explain things all to well, so I'll explain better, I am working on this extension for chrome that grabs synonyms from a dat file I found on the web from someone at MIT. I've gotten most of my idea written in Java (my native language), here it is so you can see what I'm trying to do:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
public class Grabber {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
URL mit = new URL(
"http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat");
BufferedReader in = new BufferedReader(new InputStreamReader(
mit.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.startsWith("spoken")) {
ArrayList<String> list = new ArrayList<String>();
String[] synonyms = inputLine.substring("spoken".length())
.split(" ");
for (String toPrint : synonyms) {
if (toPrint.length() > 0) {
list.add(toPrint.trim());
}
}
for (String toPrint : list) {
System.out.println(toPrint);
}
}
}
in.close();
}
}
Now, with my 'Codecademy' knowledge of the language, I don't know about all the library's and such included in Chrome's JavaScript API. We're should I start looking to complete this task? Oh, I also need to figure out how to make array's in JavaScript, act like the collection I wrote above.

Here's an example:
var xhr = new XMLHttpRequest(); // Use XMLHttpRequest to fetch resources from the Web
xhr.open("GET", // HTTP GET method
"http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat",
true // asynchronous
);
xhr.onreadystatechange = (function()
{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) // success
{
// data fetched in xhr.responseText, now parse it
var inputLines = xhr.responseText.split(/\r|\n|\r\n/); //Split them into lines
/* A quick and brief alternative to
while ((inputLine = in.readLine()) != null) {
if (inputLine.startsWith("spoken")) {
...
}
} */
inputLines.filter(function(inputLine)
{
// You can also use
// return inputLine.substr(0, 6) == "spoken";
// if you are not familiar with regular expressions.
return inputLine.match(/^spoken/);
}).forEach(inputLine)
{
var list = [];
var synonyms = inputLine.substring("spoken".length).split(" ");
synonyms.fonEach(function(toPrint)
{
if(toPrint.length > 0)
list.push(toPrint.replace(/^\s+|\s+$/g, ''));
//toPrint.replace(/^\s+|\s+$/g, '') is similar to toPrint.trim() in Java
//list.push(...) is used to add a new element in the array list.
});
list.forEach(function(toPrint)
{
// Where do you want to put your output?
});
});
}
});
xhr.send(); // Send the request and fetch the data.

Related

How to upload multiple images from front-end using JavaScript, jQuery, Ajax in JSP file and send it into Spring Boot Controller?

I am working on a spring boot web application, where I want to upload multiple images of a product at a time along with other fields (for example product name, SKU code, category, tags, subcategory, etc). I have written code for RESTful API to upload multiple images and it is working perfectly for me. I tested API using postman and it is working fine. But, I don't know how to do it from the front end. I am showing you my front-end code below, where I am sending a single image to my controller using Ajax.
$("#file").change(function(){
var formData = new FormData();
var fileSelect = document.getElementById("file");
if(fileSelect.files && fileSelect.files.length == 1) {
var file = fileSelect.files[0];
formData.set("file",file,file.name);
}else{
$("#file").focus();
return false;
}
var request = new XMLHttpRequest();
try {
request.onreadystatechange=function() {
if(request.readyState==4) {
var v = JSON.parse(request.responseText);
if(v.status==="OK") {
alert("Product Image Uploaded Successfully")
document.getElementById('imagepath').value = v.response;
}
}
}
request.open('POST',"<%=AkApiUrl.testuploadfile%>");
request.send(formData);
} catch(e) {
swal("Unable to connect to server","","error");
}
});
As I told you, the above code is to send a single file at a time. I am showing you my API controller code also:
#RequestMapping(value = AkApiUrl.testuploadfile, method = { RequestMethod.POST, RequestMethod.GET }, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> testuploadfile(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) {
CustomResponse = ResponseFactory.getResponse(request);
String imgurl = "NA";
try {
String path = Constants.webmedia;
String relativepath = "public/media/";
System.out.println("Here is the image: ");
List<MultipartFile> multifile = Arrays.asList(files);
if( null != multifile && multifile.size()>0) {
for (int i=0; i < multifile.size(); i++) {
String filename = files[i].getOriginalFilename();
String extension = filename.substring(filename.lastIndexOf("."), filename.length());
int r = (int )(Math.random() * 500 + 1);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = new Date();
String formatdate = format.format(date);
formatdate = "ECOM" + formatdate + r;
byte[] bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(path + File.separator + formatdate + extension)));
stream.write(bytes);
stream.flush();
stream.close();
String newimgurl = relativepath + formatdate + extension;
imgurl = imgurl+"##"+newimgurl;
if(imgurl != null) {
CustomResponse.setResponse(imgurl);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
This API is working fine, I am getting desired response. But I do not know how should I implement this thing on the JSP page. Please, any suggestions would be appreciated.

Why does my custom Excel function never return a value ONLY on Windows?

I am building an Office Excel Add-in using the web add-in framework provided by Microsoft.
This add-in also includes a custom function. Currently, the custom function is working on Excel for Mac, Excel online (device agnostic), but not on Windows?
The add-in loads fine, and there are no obvious errors. But when the function is run (on Windows) it just says:
#BUSY and then resolves to #VALUE! and stays like that.
The code also works when using the Shared Runtime configuration, but that requires that we make all our Javascript compatible with IE, which is definitely a possibility - but I would like to know why the regular configuration is not working.
WISE is the Excel function.
function WISE(symbol, parameter, year, quarter) {
var param = parameter.replace(/\s/g, '').toLowerCase();
param = param.replace('&', 'and');
symbol = symbol.toUpperCase();
if (quarter == null) {
return getAnnualData(symbol, param, year);
}
}
function getVal(data, param) {
var apiResponseDataFormatted = {};
for (var key in data) {
apiResponseDataFormatted[key.replace(/ /g, '').toLowerCase()] = data[key];
}
var newValue = apiResponseDataFormatted[param];
if (newValue !== 0 && !newValue) {
newValue = 'Unavailable';
}
return newValue;
}
function getAnnualData(symbol, parameter, year) {
var apiPath = requestMap[parameter];
var response = "";
var url = URL_API + "/" + apiPath + "/" + symbol + "?apikey=" + api_key;
var request = new XMLHttpRequest();
request.open('GET', url, false); // `false` makes the request synchronous
request.send(null);
if (request.status === 200) {// That's HTTP for 'ok'
response = JSON.parse(request.responseText);
}else{
return "Request Error: " + request.status + " " + url;
}
var apiResponseData;
var currentYear = new Date().getFullYear();
if (year != null && year !== currentYear) {
apiResponseData = response[currentYear - year - 1];
} else {
apiResponseData = response[0];
}
result = getVal(apiResponseData, parameter)
return result;
}
sorry for the frustration. One of the main reason for this could be that currently on windows custom functions run in their own runtime, which is a seperate. While that runtime conserves memory, one of the limitations is it doesn't support Full CORS.
We have been recommending the use of the Shared Runtime as a way to get around this. This effectively will run the custom function in the same runtime as the taskpane, so I suspect will work for you. This also makes it easy to share state between taskpanes and functions.
Can you try that?
https://learn.microsoft.com/en-us/office/dev/add-ins/tutorials/share-data-and-events-between-custom-functions-and-the-task-pane-tutorial
(I realize the docs aren't super clear about this, so will follow up offline on this to get it corrected).

can not convert JSON to object

First of all I have searched the internet for a solution to my problem.
I have found several sites that can parse my JSON and tell me that it's valid. I knew that beforehand since it originates from my SQL Server.
But when calling JSON.parse(...) with the following json, I get a string back not a object!
My code so far:
function GetConfig(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);
if (xhr.status === 200)
return JSON.parse(xhr.responseText);
else
return null;
};
/*
xhr.responseText returns this JSON:
{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
*/
function GenerateHighChart(ressponse) {
var data = GetConfig('/api/Settings/Powerlog/Temperatures');
}
But when trying to access data as a object I get an error since data is still a string
var a = data.graphSettings.min;
UPDATE
I believe the problem is in my API
So here is my controller:
[Produces("application/json")]
[Route("api/Settings")]
public class APIGetSettings : Controller
{
private string InternalGetJson(string commandText, params object[] parameters)
{
var json = GetJson(commandText, parameters);
return json.Replace("[", "").Replace("]", "");
}
private string GetSettingFromName(string name) => InternalGetJson("select * from fn_GetVisualSettings(#0) for json path", name);
[Route("Powerlog/Temperatures")]
public IActionResult Powerlog_Temperatures() => new JsonResult(GetSettingFromName("Powerlog/Temperatures"));
}
/*
JSON returned from GetSettingFromName
{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
*/
in my Javascript if I change GetConfig to
if (xhr.status === 200)
return JSON.parse(xhr.responseJSON);
else
return null;
responseJSON is undefined
** UPDATE **
I found the bug. the problem is the text returned from my API
I get this :
"{\"graphSettings\":{\"Caption\":\"TEST\",\"Min\":2.850000000000000e+001,\"Max\":2.950000000000000e+001}}"
but expected this:
"{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}"
I'll create a new QUESTION
This is working:
var x = {"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
console.log(x.graphSettings.Min);
Please log/debug the xhr.responseText and see whats there.
If you have any error, remember to post it here as well.

Reading local server .json file with mobileFirst javascript adapter

Is there any way that I can read a .json file (located in server) from a javascript http adapter?
I tried a lot of methods described in the internet but they don't seem to work because they are made for browser javascript (I get errors like XMLHttpRequest is not defined or activeObject is not defined).
for example, I used this but it doesn't work:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
return allText;
}
}
}
rawFile.send(null);
}
Is there any way that I could do this without using java?
You can read a file with Javascript as shown below.
function readFile(filename) {
var content = "";
var fileReader = new java.io.FileReader(filename);
var bufferedReader = new java.io.BufferedReader(fileReader);
var line;
while((line = bufferedReader.readLine()) != null) {
content += line;
}
bufferedReader.close();
return content;
}
function test() {
var file = 'yourfilename.json';
var fileContents;
try {
fileContents = JSON.parse(readFile(file));
} catch(ex) {
// handle error
}
return {
fileContents: fileContents
};
}
For those interested in using Java.
One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.
First create a Javascript adapter.
Then create a Java class under the server/lib folder. I created the class ReadJSON.java under the package com.sample.customcode.
Inside the ReadJSON.java
public class ReadJSON {
public static String readJSON() throws IOException {
//Open File
File file = new File("file.txt");
BufferedReader reader = null;
try {
//Create the file reader
reader = new BufferedReader(new FileReader(file));
String text = null;
//read file
while ((text = reader.readLine()) != null) {}
} finally {
try {
//Close the stream
reader.close();
}
}
return "the text from file";
}
}
Inside your javascript adapter you can use Java methods like below:
function readJOSN() {
var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
return {
result: JSONfromServer
};
}
Hope this helps.

How to create a custom loader for hls.js?

I'm using hls.js with video Js and I was wondering how I could implement a custom loader that loads the content using fetch API instead of XMLHttpRequest.
The following is what I managed to achive:
hlsConfig: {
loader: function() {
this.load = function(url, responseType, onSuccess, onError, timeout, maxRetry, retryDelay) {
var onProgress = arguments.length <= 8 || arguments[8] === undefined ? null : arguments[8];
var frag = arguments.length <= 9 || arguments[9] === undefined ? null : arguments[9];
this.url = url;
if (frag && !isNaN(frag.byteRangeStartOffset) && !isNaN(frag.byteRangeEndOffset)) {
this.byteRange = frag.byteRangeStartOffset + '-' + (frag.byteRangeEndOffset - 1);
}
this.responseType = responseType;
this.onSuccess = onSuccess;
this.onProgress = onProgress;
this.onError = onError;
this.stats = {
trequest: performance.now(),
retry: 0
};
this.timeout = timeout;
this.maxRetry = maxRetry;
this.retryDelay = retryDelay;
if (self.fetch) {
// use fetch API
} else {
// fallback to XMLHttpRequest loader
}
return true;
}
}
hls.js only takes xmlHTTPrequest events. You have to modify hls.js to make it handle the input the way you like, search for 'loadsuccess' in unminified hls.js and change it to how you would handle the data yourself. Make sure the payload is the requested responseType; make sure payload is an ArrayBuffer if it asks for it, and just a plain string for empty responseType.
Personally I have coded the following shim in order to pass the data came from WebRTC or whatever else:
function CustomLoaderResponse(response)
{
this.currentTarget = {};
this.currentTarget.getResponseHeader = function() { return '' };
this.currentTarget.response = response;
this.currentTarget.responseText = typeof(response) == "string" ? response : '';
}
<...>
var response = new CustomLoaderResponse(/* pass string or arraybuffer here */);
I guess that the should propose handling the regular JavaScript dictionaries in the future releases of hls.js, as this can't be considered as a good practice either.

Categories