Sending integer values in response from node js server - java

I have a node js server implementation and I would like to send some values to an Android (Java) client. The method of the node js server is as follows:
app.get('/GetValues*', function (request, response) {
// Request needs to be a GET
if (request.method == 'GET') {
var username = request.query.account;
var time_now = Date.now();
var db = database('./database.db');
var row_account = db.prepare('SELECT SCORE score, STARTED_STUDY_SERVER_MILLIS timestamp, DAYS_TOTAL days_total FROM ACCOUNTS WHERE NAME = ?').get(username);
var score = row_account.score;
var days_total = row_account.days_total;
var days_count = time_now - row_account.timestamp;
var minutes_count = time_now - row_account.timestamp;
var statement = db.prepare("UPDATE ACCOUNTS SET DAYS_COUNT = ?, MINUTES_COUNT = ? WHERE ID = ?");
statement.run(days_count,minutes_count,getAccountID(db, request.query.account));
var row_usage = db.prepare('SELECT DURATION_ENABLED duration_enabled, DURATION_DISABLED duration_disabled FROM USAGE WHERE NAME = ?').get(username);
var duration_enabled = row_usage.duration_enabled;
var duration_disabled = row_usage.duration_disabled;
}
});
I would like to send the values score (integer), days_total (integer), days_count (integer), minutes_count (long), duration_enabled (long), duration_disabled (long) to the client.
How can I send it to the client? I think response.send() only accepts strings. How can I parse the values in Java when received?

Since you need to send all those values at once, it's common to respond with a JSON in such a case. In express, you can send a JSON response using response.send() or response.json() like this:
app.get('/GetValues*', function (request, response) {
// ... your db operations here, then
response.json({
score: score,
days_total: days_total,
days_count: days_count,
minutes_count: minutes_count,
duration_enabled: duration_enabled,
duration_disabled: duration_disabled
});
});
This will send a response with Content-Type: application/json and a JSON string in the body looking like this:
{"score":12,"days_total":12,"days_count":12,"minutes_count":12,"duration_enabled":12,"duration_disabled":12}
Then you just parse it in your Java code.
By the way, this line
if (request.method == 'GET') {
is unnecessary. Registering a handler via app.get(), express will only handle GET requests anyway.

Related

How to obtain `ApproximateReceiveCount` from an SQS message

I'm using Amazon SQS. My goal is to read ApproximateReceiveCount attribute from ReceiveMessage API action using the Java SDK (v2.10.4, Java 11).
I tried the following code, but message.attributes() doesn't contain the required key:
String getApproximateReceiveCount() {
var receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl("https://sqs.eu-west-1.amazonaws.com/012345678910/my-example-queue")
.build();
var sqsClient = SqsClient.builder().endpointOverride(URI.create("http://localhost:4576")).build();
var response = sqsClient.receiveMessage(receiveMessageRequest);
var message = response.messages().get(0);
return message.attributes().get(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT);
}
How to go about receiving an entry for MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT key, in this map?
As per the documentation page to ReceiveMessage which you linked, there is a parameter called AttributeName.N described as
A list of attributes that need to be returned along with each message. These attributes include:
[...]
ApproximateReceiveCount – Returns the number of times a message has been received from the queue but not deleted.
Therefore you need to ask for the attribute in the request, for it to be available in the response. To do that use ReceiveMessageRequestBuilder.attributeNamesWithStrings() method like so:
String getApproximateReceiveCount() {
var receiveMessageRequest = ReceiveMessageRequest.builder()
.queueUrl("https://sqs.eu-west-1.amazonaws.com/012345678910/my-example-queue")
.attributeNamesWithStrings(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT.toString())
.build();
var sqsClient = SqsClient.builder().endpointOverride(URI.create("http://localhost:4576")).build();
var response = sqsClient.receiveMessage(receiveMessageRequest);
var message = response.messages().get(0);
return message.attributes().get(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT);
}
Note that there are two similarly named methods, which you can't use:
.attributeNames() - the parameter enum doesn't list the required key,
.messageAttributeNames() - corresponds to attributes sent along with the message body.

Export indexeddb object store to .csv

I have an object store I need to export or download as a .csv file. I have done some searching and I can't seem to find information on this function. Responses that do not utilize IDB are welcome.
Some background: This is part of a project for work, and I dove into this project without prior knowledge of coding whatsoever. I am using a company issued chromebook, so (as far as I know) NPM installs are not available.
App Background: The project is a customer survey operated through a single terminal. That terminal being my chromebook with hopes to move to an ipad if I can successfully download user inputs to .csv file.
What I have so far:
(function leadIDB() {
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB|| window.msIndexedDB;
if (!window.indexedDB) {
alert('indexDB not supported in this browser');
}
let request = window.indexedDB.open("leadDB", 1),
db,
tx,
store,
index;
request.onupgradeneeded = function(e) {
let db = request.result,
store = db.createObjectStore("LeadStore", {keyPath: "leadID", autoIncrement: true});
index = store.createIndex("firstName", "firstName", {unique: false});
};
request.onerror = function(e) {
console.log("There was an error: " + e.target.errorCode);
};
request.onsuccess = function(e) {
db = request.result;
tx = db.transaction("LeadStore", "readwrite");
store = tx.objectStore("LeadStore");
index = store.index("firstName");
db.onerror = function(e) {
console.log("ERROR" + e.target.errorCode);
};
store.put(newLead);
let lead = store.getAll();
lead.onsuccess = function() {
console.log(lead.result);
console.log(lead.result.firstName);
};
tx.oncomplete = function() {
console.log('Item added to LeadDB');
db.close();
};
};
})();
You are on the right track. There are a few more things to do. First, you need to be able to continue processing once you have loaded the data from indexedDB into js memory. Next, you need to generate the CSV file in memory (as a gigantic string). Next, you need to convert the csv string into a File (which implements Blob). Finally, you want to trigger the download of the file.
There are a few ways to do the first step. I am going to use a promise, but you could do this with a callback or whatever you fancy.
function loadData() {
return new Promise((resolve, reject) => {
var openrequest = indexedDB.open(...);
openrequest.onupgradeneeded = ...;
openrequest.onerror = event => reject(event.target.error);
openrequest.onsuccess = event => {
var db = event.target.result;
var txn = db.transaction(...);
var store = txn.objectStore(...);
var loadrequest = store.getAll();
loadrequest.onerror = event => reject(event.target.error);
loadrequest.onsuccess = event => {
var data = event.target.result;
resolve(data);
};
};
});
}
// You could call the function like this for example:
async function foo() {
var data = await loadData();
console.log('loaded the data, loaded %d objects', data.length);
}
Next, you want to convert the data into a csv-formatted string.
// This is not perfect, just an example of getting you closer
function toCSV(data) {
var output = [];
for(var object of data) {
var row = [];
for(var prop in object) {
row.push(to_csv_value(object[prop]));
row.push(',');
}
row.push('\n');
output.push(row.join(''));
}
return output.join('');
}
function to_csv_value(value) {
var output = '"';
output += value.replace('"', '\\"');
return output + '"';
}
// and then to compose it for example:
async function foo() {
var data = await loadData();
var csvstring = toCSV(data);
}
Next, you want to create a file. You can use the Blob constructor to do this. Something like the following:
// Because File implements blob interface, we are effectively creating a file
// by creating a blob
function createCSVFileFromString(string) {
var csv_mime_type = 'text/csv';
return new Blob([string], {type: csv_mime_type});
}
// And again, to compose it:
async function foo() {
var data = await loadData();
var string = toCSV(data);
var blob = createCSVFileFromString(string);
}
The next step is to make the blob downloadable. This can typically be done using the object url strategy. Kind of like the following:
function downloadBlob(blob, filename) {
var anchor = document.createElement('a');
anchor.setAttribute('download', filename);
var url = URL.createObjectURL(blob);
anchor.setAttribute('href', url);
anchor.click();
URL.revokeObjectURL(url);
}
// And finally, to compose it all together
async function loadAndStartDownloadingData() {
var data = await loadData();
var csvstring = toCSV(data);
var blob = createCSVFileFromString(csvstring);
downloadBlob(blob, 'mydata.csv');
}
Then, somewhere in your application, let's say on click of button, you would do something like this. Im using non-async syntax here just for example of using promise in non-await, you want to always be careful to not hide errors.
var button = ...;
button.onclick = function(event) {
// Load the data and trigger the download, and send any problems to console
loadAndStartDownloadingData().catch(console.warn);
};
Note, this doesn't cover inserting the data, but I'm sure you can figure that out.

Ajax call to retrieve hashmap

I have a hashmap which I have converted into a JSONObject. This JSONObject I am retrieving via a REST api using an AJAX call. What I wish to know is that how will the ajax look like in order to get the JSONObject which I can use afterwards.
My ajax call looks like this :
Ext.Ajax.request({
url : '...',
method:'GET',
scope : this,
success : function(result, request) {
console.log("2");
var data = Ext.decode(result.responseText)[0];
for (var i = 0; i < data.size(); i++) {
console.log("4. ");
}
}
})
The error which appears is
Ext.Error: You're trying to decode an invalid JSON String:
result.responseText returns the Invalid JSON String.Use this code
var responseArray = Ext.decode(response.responseText);
var data = responseArray.data;
console.log(data);
data variable will contain the JSON Object.

Connect to json-rpc interface

I'm trying to connect to the transmission rpc interface via C#/Java to get some informations back.
https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt
Unfortunatly I have problems to get the correct HTTP-Post to access the interface.
For example if I try this in C#:
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["torrent-get"] = "id";
var response = client.UploadValues("http://ip:9091/transmission/rpc", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine("" + responseString);
}
Or if i use:
using (var webClient = new WebClient())
{
String json = "{\"arguments\": {\"fields\": [ \"id\", \"name\", \"totalSize\" ],\"ids\": [ 7, 10 ]},\"method\": \"torrent-get\",\"tag\": 39693}";
var response = webClient.UploadString("http://192.168.240.171:9091/transmission/rpc", "POST", json);
Console.WriteLine(""+response);
}
I get the following error:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The Remoteserver returned an exception: (409) conflict.
You must save the X-Transmission-Session-Id provided in the 409 response and resubmit the request with a X-Transmission-Session-Id property added to your request header.
Example in java :
int index = responseString.indexOf("X-Transmission-Session-Id:");
String sessionId = responseString.substring(index + 27, index + 75);
connection.setRequestProperty("X-Transmission-Session-Id", sessionId);

How to get SoapUI request and response XML in java

I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();

Categories