How to access AWS Lambda callback results in Java - java

I am calling an AWS Lambda function written in NodeJS which exports:
exports.handler = (event, context, callback) => {
The callback is passed the output of a SQL query:
new mssql.Request(conn).query(passedStatement,(err, result) => {
if (err) {
callback(err);
} else {
console.log("done");
callback(null, result);
}
});
I am calling this function from Java code:
InvokeRequest request = new InvokeRequest()
.withFunctionName(lambdaFunctionName)
.withPayload(jsonPayload)
.withInvocationType(InvocationType.RequestResponse)
.withLogType(LogType.Tail);
InvokeResult result = client.invoke(request);
The log result contains the message 'done' so I believe the code executed without errors. However, I can't see how to get the output from the SQL query. Assuming I pass SELECT * FROM user WHERE Username = 'My User', how do I get user details in the Java code?

In order to get the result callback as JSON all that is required is:
new String(result.getPayload().array())

Related

Passing ID from one function to another with return

I would like to validate and set a ID for a collection in firebase. Right now i am just trying to get an id number back from a collections query and send it to the function that needs it. Here is the function that needs the id#.
const data = lastCustIdGrab(); console.log(`Last number ${data}`);
This is the return sender. I can get the document Id in the console log but can't figure how to send it back.
exports.lastCustIdGrab = () => {
db.collection('Customers')
.orderBy('createdAt', 'desc')
.limit(1);
.get()
.then((data) => {
let DOC = data.docs[0];
let ID = DOC.id;
console.log("LOOOP ",ID);
return ID;
})}
This gets me the id in the LOOOP output but won't return it! I know i can return data as i have tested with the arbitrary code below and it works. The return sends it back to be console logged in the "last number" output properly.
exports.lastCustIdGrab = () => {
let ID = 12345;
return ID;
}
So I'm sure that i am just missing something simple. Thanks for the Help!
In the lastCustIdGrab function you need to return the promises chain, as follows:
exports.lastCustIdGrab = () => {
return db.collection('Customers') // <== See return
.orderBy('createdAt', 'desc')
.limit(1);
.get()
.then((data) => {
let DOC = data.docs[0];
let ID = DOC.id;
console.log("LOOOP ",ID);
return ID;
});
}
AND you should note that the lastCustIdGrab function is asynchronous and returns a Promise, which means that you need to do:
lastCustIdGrab()
.then(data => {
console.log(`Last number ${data}`);
});
.get() is asynchronous, and in your method you're not returning the promise. So even though the then() is executing, the value returned from the promise's resolve isn't being returned to lastCustIdGrab() invocation because the promise is never returned. So (switching it up to use async/await) try this:
exports.lastCustIdGrab = async () => {
let data = await db.collection('Customers')
.orderBy('createdAt', 'desc')
.limit(1)
.get();
let DOC = data.docs[0];
let ID = DOC.id;
return ID;
}
}
And in your invocation wait for the promise to resolve to ensure error handling and method completion:
const data = await lastCustIdGrab();

Stuck in error JSON Parse error: Unable to parse JSON string

I am stuck in very common error JSON parse error cannot figure out web service is faulty or fetch code I get a response from this web service when I test it in my postman it return two objects but when I want to login from this web service it always gives parse error
React Native Function to loginUser where may be error is present
UserLoginFunction = () =>{
const { UserContact } = this.state ;
const { UserPassword } = this.state ;
if(this.state.UserContact == ""){
ToastAndroid.show('Pleas Enter Contact Number Correctly ',ToastAndroid.SHORT)
}
else if (this.state.UserPassword == ""){
ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
}
else{
fetch(urls.localhosturl + urls.login, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_contact: UserContact,
user_password: UserPassword,
//user_name: UserName,
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
//Save User Details to Local Storage
AsyncStorage.setItem("userContact", JSON.stringify(UserContact));
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('Home',{user_contact:UserContact,});
}
else{
ToastAndroid.show(responseJson,ToastAndroid.SHORT);
//Alert.alert(string,responseJson);
}
}).catch((error) => {
console.error(error);
});
}
}
PHP webservice
<!-- begin snippet: js hide: false console: true babel: false -->
<?php
// Importing DBConfig.php file.
include 'config.php';
// Creating connection.
$con = mysqli_connect($host_name, $host_user, $host_password, $database_name);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json, true);
$user_contact = $obj['user_contact'];
$user_password = $obj['user_password'];
// $user_contact = $_REQUEST['user_contact'];
// $user_password = $_REQUEST['user_password'];
//$user_name = $obj['user_name'];
$Sql_Query = "select * from user_information where user_contact = '$user_contact' and user_password = '$user_password' ";
$check = mysqli_fetch_array(mysqli_query($con, $Sql_Query));
if (isset($check)) {
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson;
} else {
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again';
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon;
}
$result = $con->query($Sql_Query);
$array = $result->fetch_assoc();
$json = json_encode($array, true);
echo $json;
mysqli_close($con);
It looks like the standard output of your PHP service is used as the source of the JSON.
In that case, the fact that you are spitting out the following line is causing you trouble:
echo $SuccessLoginJson;
You may want to either suppress this message, write it to a log file, or perhaps write it to standard error instead. In any case, you've turned your web service into something that gives your client two results instead of one, and the client doesn't understand how to handle it.

Can't edit other Parse User objects , save In Background doesn't write in Parse Dashboard

I have been bonking my head everywhere on this problem , I would really need some help please !! I am pretty new to Android.
My problem is the following , I have completed the User Class with some columns , for example "Former Friends" which are a list of Strings .
I do a first query , then I find the Parseuser objects matching the query (which are not the logged in user) and then I try to fill those columns.
I also update the info for the logged in user
It properly works for the logged in user ,however I can't see the filled info for the other Parse object user
I tried modifying the write access for the first user (objects.get(0)) ,but it doesn't work
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("username", getCurrentUser().getUsername());
query.whereNotContainedIn("username",getCurrentUser().getList("Former_friends"));
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
// Here I just add the first object to a list and I update the current user data ,that works fine
List<String> aList = ParseUser.getCurrentUser().getList("Former_friends");
aList.add(objects.get(0).getString("username"));
ParseUser.getCurrentUser().put("Former_friends", aList);
ParseUser.getCurrentUser().saveInBackground();
ParseUser userfound =objects.get(0);
// The two following Lines doesn't work. I don't see "Any String" in the ParseDashboard "Name" columns..
userfound.put("Name","Any String");
userfound.saveInBackground();
There are no bugs , but no update for the non-logged-in user
Big thx,
Serge
For security reasons, in Parse Server, one user cannot change another user object directly from client side. If it were possible, a bad user could erase all other users data, for example.
So this operation requires you to write a cloud code function. You should have a cloud function similar to this one here:
Parse.cloud.define('formerFriends', async request => {
const query = new Parse.Query(Parse.User);
query.notEqualTo('username', request.user.getUsername());
query.notContainedIn('username', request.user.get('Former_friends'));
const objects = await query.find({ useMasterKey: true });
if (object.length > 0) {
const aList = request.user.get('Former_friends');
aList.add(objects[0].getUsername());
request.user.set('Former_friends', aList);
await request.user.save();
const userfound = objects[0];
userfound.set('Name', 'Any String');
await userfound.save(null, { useMasterKey: true });
}
});
And then call the cloud function from Android like this:
HashMap<String, Object> params = new HashMap<String, Object>();
ParseCloud.callFunctionInBackground("formerFriends", params, new FunctionCallback<Float>() {
void done(Object result, ParseException e) {
if (e == null) {
// success
}
}
});

How to set parameters in a get request from reactJS

Maybe its a very newbie question for here but i spend a lot of time to see a good approach for doing this and i didn't find convenient answer. I am trying to make a simple call to a rest api and i want to pass a value with the GET request appended to the string. like url/foo where foo is the parameter. I have a query variable that i want to append to the end of the url string for the get request. Thank you in advance.
class About extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
filteredItems: [],
user: {},
query: '' <-- query variable to be appended to the end of the get request
};
}
componentDidMount() {
fetch(`'myurl/${this.state.query}'`) <-- i want to append the variable at the end of the string ??
.then(res => res.json())
.then((result) => {
console.log(result);
this.setState({
products: result,
filteredItems: result
});
}
)
}
queryChange = (evt) => {
this.setState({query: evt.target.value}) <-- update the variable state from an event
}
Get rid of the extra quotations (') in 'myurl/${this.state.query}'
let query = {id:1};
let url = 'https:example.com//xyz.com/search?' + query;
fetch(url)
You can pass param without using `` or $ also,In componentDidMount()
componentDidMount() {
let query = this.state.query;
fetch('myurl/'+query)
.then(res => res.json())
.then((result) => {
console.log(result);
this.setState({
products: result,
filteredItems: result
});
}
)
}

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.

Categories