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<>();
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());
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);
}
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.
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.