Passing a String[] from react to springboot - java

I want to pass a String array of usernames from react to Spring so that I can then get some user details for each of those usernames and finally pass this back to react as a List<String>
So far in react, I am making an array of usernames, and then passing them as the request body to spring
const roundRobin = () => {
const userList = []
//Get list of entrants usernames to pass to backend
for(let i = 0; i < entrants.length; i++){
userList.push(entrants[i].username);
console.log(userList);
}
const List = JSON.stringify(userList)
//API call
apiCalls
.getRandomUserList(List)
.then((response) => {
console.log(response.data);
})
.catch((apiError) => {
if (apiError.response.data && apiError.response.data.validationErrors) {
setEditErrors(apiError.response.data.validationErrors);
}
console.log(apiError.response.data)
setPendingApiCall(false);
});
}
In spring my controller takes the request body as a String[]
//create a random list of members who have entered an event
#CrossOrigin
#GetMapping("/users/createRandomList")
List<String> randomList(#RequestBody String[] usernames) {
return userService.createRandomUserList(usernames);
}
The UserService then takes the String[] and changes it to a List and calls a method which randomly rearranges the order of the Strings, it then loops through the returned List (which are a username) and gets the User from the database and adds some details about that User to a new List This is then returned to react.
public List<String> createRandomUserList(String[] randomUsernames) {
List<String> users = new ArrayList<>();
List<String> randomUsersList = Arrays.asList(randomUsernames);
List<String> randomUsers = getRandomUsers(randomUsersList);
for (String randUsernames : randomUsers) {
User u = userRepository.findByUsername(randUsernames);
users.add(u.getFirstname() + " " + u.getSurname() + " " + u.getHandicap());
}
return users;
}
//Create list of entrants IDs in random order for tee times.
public List<String> getRandomUsers(List<String> userIds) {
int size = userIds.size();
List<String> passedList = userIds;
List<String> entrants = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < size; i++) {
int randomIndex = rand.nextInt(passedList.size());
entrants.add(passedList.get(randomIndex));
passedList.remove(randomIndex);
}
return entrants;
}
When I try and run this in my web app though, I get an HTTP 400 error,
{timestamp: 1640902047907, status: 400, message: 'Required request body is missing: java.util.List<j…ser.UserController.randomList(java.lang.String[])', url: '/api/1.0/users/createRandomList'}
I am not sure what I am doing wrong, as far as I can tell, I am passing an array to Spring, when I console.log(List), I get ["user1","user2"]

I think you should change the get mapping to post mapping and then use the List instead of String[], try in that way
#CrossOrigin
#GetMapping("/users/createRandomList")
List<String> randomList(#RequestBody List<String> usernames) {
return userService.createRandomUserList(usernames);
}
also change service methods according to the changes

Related

I can't add an element to the list. It returns null. How can I add it? [duplicate]

This question already has answers here:
Java List<string> not adding to list after Arrays.asList() has been used
(3 answers)
Closed 4 months ago.
My controller class:
#PostMapping(value = "/uniqueUrl")
#ResponseBody
public ResponseEntity<MyResponse> urlGenerator(#RequestBody MyRequest myRequest){
log.info("Request for url : ", myRequest);
MyResponse myResponse= this.generateUrlService.urlGenerator(myRequest);
log.info("generateUniqueUrl response: ", myResponse.getLongUniqueUrlList());
return ResponseEntity.accepted().body(myResponse);
}
MyRequest class:
#Data
public class MyRequestimplements Serializable {
#NotNull(message = "Url cannot be null or empty")
private String url;
#NotNull(message = "count cannot be null or empty")
private int cound;
}
My service implemantation :
#Override
public myResponse urlGenerator(MyRequest myRequest) {
log.info("urlGenerator started..");
myUrlRequestValidator.validate(myRequest);
String longUrl = myRequest.getUrl();
int count = myRequest.getCount();
List<String> uniqueUrlList = Arrays.asList(new String[count]);
for (String string : uniqueUrlList) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
MyResponse response = new MyResponse();
response.setLongUniqueUrlList(uniqueUrlList);
return response;
}
MyResponse class:
#Data
public class MyResponse extends BaseResponse {
private List<String> longUniqueUrlList;
private List<String> shortUrlList;
}
In the method where my Controller and Service class is as follows, the result of uniqueUrlList returns null. I want to add each string formed by the add method to the list, but it does not add it. Can you help me where am I going wrong?
edit1 : When I change the random url generation and adding to the list in this way, it does not enter the for loop, or when I do not change the loop and only define it as an arraylist, it gives a Null error in the add method. How can I solve this? It's such an easy thing, but I don't understand why I can't do it?
List<String> uniqueUrlList = new ArrayList<String>();
String string = null;
for ( int j = 0; j < count; j++) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
}
It is null because your List<String> uniqueUrlList is initialized with Arrays.asList which are fixed in size and unmodifiable, as specified in the Javadoc. The Arrays.asList(new String[count]) is also empty as there are no elements inside the new String[count].
Instead you should initialize it with a new ArrayList<String>():
List<String> uniqueUrlList = new ArrayList<String>();
Where you can then modify the list as you please, using a loop to add to your uniqueUrlList as many as myRequest.getCount() times.
You should initialize a list by
List<String> uniqueUrlList = new ArrayList<>();

Strange behaviour with ArrayList

I'm in the process of building a basic database using csv files, and i'm currently testing the select function out when i ran into something strange.
private ArrayList<Record> selectField(String selectTerm)
{
Log.log("Selection " + selectTerm,2,"DB_io");
ArrayList<Record> ret = new ArrayList<Record>();
if (titleRow.values.contains(selectTerm))
{
Log.log("Adding values to " + selectTerm);
int ordinal = titleRow.values.indexOf(selectTerm);
Log.log("Ordinal " + ordinal);
List<String> tempList = new ArrayList<String>();
for (Record r : data)
{
List<String> tempList = new ArrayList<String>();
tempList.add(r.values.get(ordinal));
Record s = new Record(tempList);
ret.add(s);
tempList.clear();
}
Log.log("Number of records in ret " + ret.size());
for (Record t : ret)
{
Log.log(t.toString());
}
}
else
{
Log.log("keyField does not contain that field");
return null;
}
Log.log("Values " + ret.toString());
return ret;
}
When i do this, the part where it logs t.ToString() shows the record to be empty, whereas if i log it before tempList.clear(), it shows the record to be containing data like it should.
If i move the tempList declaration into the Record r : data loop, then it works fine and the Record t : ret loop works outputs the contents of the record like it should
Why is this?
Edit : Record class
public class Record
{
List<String> values = new ArrayList<String>();
public Record(List<String> terms)
{
this.values = terms;
}
public Record(String[] s)
{
this.values = Arrays.asList(s);
}
public String toString()
{
return values.toString();
}
}
Your Record instance holds a reference to the ArrayList instance you passed to its constructor. Therefore, when you call tempList.clear(), you clear the same List that your Record instance is holding a reference to.
You shouldn't call tempList.clear(), since you are creating a new ArrayList in each iteration of your loop anyway.
you are referencing object from more than one place and clear method is cleaning object by setting its reference to null:
instead of ret.add(s); you can use ret.add(s.clone());

Why the data is going as null in my test and how to convert it data provider data as per my function in java

I have read some data from Excel in array form, and converted into a 2-D array in order to provide the data to a data provider.But now in the #Test when I pass the data it takes on the null value.
Can you please suggest why it's going null? Also my function in #Test is using a map as well - how can I convert the data provider data to map ?
My function in #Test is like below:-
public void testCategorySearch(String vendor_code, Map<Integer, List<String>> seller_sku , String upload_id,Protocol protocol)
throws InvocationTargetException
My code is :
#DataProvider(name = "valid_parameters")
public Object[][] sendValidParameters() {
List<ArrayList> result = td.getExcelData("C:\\Users\\ashish.gupta02\\QAAutomation\\test.xls", 1);
Object[][] a = new String[result.size()][3];
{
for (int i = 0; i < result.size(); i++) {
Object currentObject = result.get(i);
a[i][0] = currentObject.toString();
System.out.println("COnverted" + a[i][0]);
}
}
System.out.println("Printing data" + a);
//return mapper.getProtocolMappedObject(a);
//return Object ;
return a;
}
#Test(dataProvider = "valid_parameters", groups = {"positive"})
public void testCategorySearch(String vendor_code, Map<Integer, List<String>> seller_sku, String upload_id, Protocol protocol)
throws InvocationTargetException {
//Protocol protocol
//set parameter values to the api
System.out.println("Executing the request");
CreateSellerProductUpdateInfoRequest createReq = setRequest(vendor_code, seller_sku, upload_id, protocol);
CreateSellerProductUpdateInfoResponse createResponse = service.createSellerProductUpdateInfo(createReq);
System.out.print("Response is :" + createResponse);
}

Dart Parse JSON into Table

I'm trying to figure out how to parse a JSON feed into a table in Dart. I'm not sure if I should use a Map but if I do, I'm not sure how to approach extracting data. I want to have one cell to hold the assetID, then another for domain name, and another for IP address. Please let me know if you need more information.
Dart:
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
List<String> list = new List<String>();
list.add(jsonString);
for (var x = 0; x < list.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
TableCellElement cell = row.insertCell(x);
cell.text = list.toString();
// print(list);
}
// Iterator itr= list.iterator();
//
// print("Displaying List Elements,");
//
// while(itr.hasNext())
// {
// print(itr.next());
// }
}
JSON
[{"serviceResponseValue":[{"assetId":"8a41250446b89b5f0146b04d49910023","oplock":0,"longitude":115.86,"domainName":"free-aus-trip.au","latitude":-31.95,"ipAddress":"6.0.0.6"},{"assetId":"8a49859246918966014691b1aac9000c","oplock":0,"longitude":-65.30,"domainName":null,"latitude":-24.18,"ipAddress":"4.0.0.4"},{"assetId":"8a49859246876566014691b1437512e4","oplock":0,"longitude":77.60,"domainName":"allmovies.cn","latitude":12.97,"ipAddress":"14.0.0.14"},{"assetId":"8a49850446b04b5f0146b04d49910000","oplock":0,"longitude":112.47,"domainName":"getrichez.cn","latitude":32.98,"ipAddress":"5.0.0.5"},{"assetId":"8a498592469189660146919b7a210006","oplock":0,"longitude":-37.61,"domainName":"googles.com","latitude":55.75,"ipAddress":null},{"assetId":"8a42250876b89b5f0876b04d49910763","oplock":0,"longitude":-68.90,"domainName":"lolcatzfun.net","latitude":-22.48,"ipAddress":"8.0.0.8"},{"assetId":"8a498592469189660146919f8d700008","oplock":0,"longitude":113.50,"domainName":"ccn.com","latitude":52.03,"ipAddress":null},{"assetId":"8a45250446b89b5f0876b04d49910187","oplock":0,"longitude":115.84,"domainName":"free-aus-trip.au","latitude":-31.86,"ipAddress":"7.0.0.7"},{"assetId":"8a49859246918966014691aeda76000a","oplock":0,"longitude":3.38,"domainName":"cashnow.net","latitude":6.52,"ipAddress":"2.0.0.2"},{"assetId":"8a49859246918966014691ae19df0009","oplock":0,"longitude":7.48,"domainName":"free-money.tv","latitude":9.07,"ipAddress":"222.222.222.222"},{"assetId":"8a498592469189660146919e09900007","oplock":0,"longitude":30.34,"domainName":"facebok.com","latitude":59.93,"ipAddress":"111.111.111.222"},{"assetId":"8a49859246918966014691b14375000b","oplock":0,"longitude":116.41,"domainName":null,"latitude":39.90,"ipAddress":"0.0.0.111"}],"messages":{"messages":[]}}]
To work with JSON, you have in dart a great thing : dart:convert => JSON
here some example of use:
var encoded = JSON.encode([1, 2, { "a": null }]);
var decoded = JSON.decode('["foo", { "bar": 499 }]');
I have done some thing but i'm not sure that is fit perfectly with your need
import 'dart:html';
import 'dart:convert';
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
var jsonObject = JSON.decode(jsonString);
for (var x = 0; x < jsonObject.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
for (var d in jsonObject[x]["serviceResponseValue"]) {
TableCellElement cell = row.insertCell(x);
cell.text = d["assetId"];
cell = row.insertCell(x);
cell.text = d["domainName"];
cell = row.insertCell(x);
cell.text = d["ipAddress"];
print(d["assetId"]);
print(d["domainName"]);
print(d["ipAddress"]);
}
// print(list);
}
}
You parse JSON into a Dart data structure using
import 'dart:convert' show JSON;
var decoded = JSON.decode(jsonString);
see also How to handle JSON in Dart (Alexandres answer)
decoded is then a Dart data structure (lists, maps, values) that you can iterate over or investigate in the debugger. If you need further assistance please add a comment.

How to update users list using DWR

I am developing chat client which can connect to Gtalk and Facebook.I am using DWR for the purpose.
Once I log into I have to populate the user s lists. On client side I have
function showUsersOnline() {
var cellFuncs = [ function(user) {
return '<i>'+user+'</i>';
} ];
LoginG.usersOnline( {
callback : function(users) {
dwr.util.removeAllRows('usersOnline');
dwr.util.addRows("usersOnline", users, cellFuncs, {
escapeHtml : false
});
On server side I am using Smack Api to get the roster list(online)
public void usersOnline() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
System.out.println(roster.getEntryCount());
int count1 = 0;
int count2 = 0;
for (RosterEntry r : entries) {
String user = r.getUser();
Presence presence = roster.getPresence(user);
if (presence.getType() == Presence.Type.available) {
System.out.println(user + " is online");
count1++;
} else {
System.out.println(user + " is offline");
count2++;
}
Now should I return the data as JSON or is there a way DWR can handle the collection???
If you modify your server method usersOnline() to return the Collection<RosterEntry> object then DWR will populate that in the argument of the callback function which in your case is function(users). So after the call is returned back to the callback function function(users) you can go through the users object to get the updates made to it by the server side method. The users object will need to be traversed like an array since you are returning a Collection or a List whatever applies.
Is this what you are looking for? More on this can be read here.

Categories

Resources