android random item from arraylist - random

I want to get random item from arraylist. My code how i tried not working.
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_ADD, parser.getValue(e, KEY_ADD)); --edited code
menuItems.add(map);
int index = random.nextInt(menuItems.size());
HashMap<String, String> itm = menuItems.get(index);
System.out.println(itm);
EDIT:
int index = random.nextInt(menuItems.size());
HashMap<String, String> itm = new HashMap<String, String>();
itm = menuItems.get(index);
String randomstring = itm.get(MyClass.KEY_NAME);
System.out.println(randomstring);
receiving NullPointerException

use
HashMap<String, String> itm =new HashMap<String, String>();
itm = menuItems.get(index);
System.out.println(itm);
instead of
HashMap<String, String> itm = menuItems.get(index);
System.out.println(itm);
in current code you are not initializing hashmap itm before using it

Related

Spring data Mongodb write operation from ApplicationRunner

I have a problem with writing to mongodb instance. Problem is that i can't write anything from this class.
#Component
#AllArgsConstructor
public class DemoDataWriter implements ApplicationRunner {
private WarehouseRepository warehouseRepository;
private CustomerRepository customerRepository;
#Override
public void run(ApplicationArguments args) throws Exception {
Customer customer1 = new Customer("Gleb", new Coordinate(4, 3));
Customer customer2 = new Customer("Sasha", new Coordinate(8, 9));
Customer customer3 = new Customer("Misha", new Coordinate(15, 10));
Map<String, Integer> merchandiseQuantity1 = new HashMap<>();
merchandiseQuantity1.put("computer", 16);
merchandiseQuantity1.put("bebra", 6);
merchandiseQuantity1.put("vacine", 10);
Map<String, Integer> merchandiseQuantity2 = new HashMap<>();
merchandiseQuantity1.put("laptop", 100);
merchandiseQuantity1.put("grivna", 20);
merchandiseQuantity1.put("beer", 1);
Map<String, Integer> merchandiseQuantity3 = new HashMap<>();
merchandiseQuantity1.put("cup", 13);
merchandiseQuantity1.put("chair", 90);
merchandiseQuantity1.put("notebook", 18);
Map<String, Integer> merchandiseQuantity4 = new HashMap<>();
merchandiseQuantity1.put("gun", 54);
merchandiseQuantity1.put("answer", 42);
merchandiseQuantity1.put("computer", 4);
Map<String, Integer> merchandiseQuantity5 = new HashMap<>();
merchandiseQuantity1.put("gun", 16);
merchandiseQuantity1.put("grinva", 6);
merchandiseQuantity1.put("charger", 132);
Map<String, Integer> merchandiseQuantity6 = new HashMap<>();
merchandiseQuantity1.put("computer", 16);
merchandiseQuantity1.put("bebra", 6);
merchandiseQuantity1.put("vacine", 10);
Warehouse warehouse1 = new Warehouse("Compluter Inc", merchandiseQuantity1, new Coordinate(43,12));
Warehouse warehouse2 = new Warehouse("Bebra", merchandiseQuantity2, new Coordinate(21, 89));
Warehouse warehouse3 = new Warehouse("LG", merchandiseQuantity3, new Coordinate(15, 90));
Warehouse warehouse4 = new Warehouse("Abchihba", merchandiseQuantity4, new Coordinate(567, 890));
Warehouse warehouse5 = new Warehouse("Node", merchandiseQuantity5, new Coordinate(389, 54));
Warehouse warehouse6 = new Warehouse("Meta", merchandiseQuantity6, new Coordinate(321, 590));
customerRepository.save(customer1);
customerRepository.save(customer2);
customerRepository.save(customer3);
warehouseRepository.save(warehouse1);
warehouseRepository.save(warehouse2);
warehouseRepository.save(warehouse3);
warehouseRepository.save(warehouse4);
warehouseRepository.save(warehouse5);
warehouseRepository.save(warehouse6);
}
}
But i can write to database from Controller.
#PostMapping(path = "/customer/create")
public Customer createNewCustomer(#RequestBody Customer customer) {
System.out.println(customer.toString());
return customerRepository.save(customer);
}
Maybe problem in my way of using spring for this logic and i just need to find different way for compliting such operation.
My suggestion is to check whether u are able to go inside the run method in the debug mode.

RestTemplate GET request with request param

I use RestTemplate for GET Request with requestParam as :
final String Url = "http://localhost:8080/player/{nickname}";
final Map<String, String> nickname = new HashMap<String, String>();
nickname.put("nickname", score.getPlayer());
String Uri = "http://localhost:8081/game/{code}";
final Map<String, String> code = new HashMap<String, String>();
code.put("code", score.getGamecode());
Player player = restTemplate.getForObject(Url, Player.class, nickname);
Game game = restTemplate.getForObject(Uri, Game.class, code);
but I have an error
Connection refused
in the console
and error:
"I/O error on GET request for \"http://localhost:8080/player/sahar1\": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect"
in the Postman
could you help me how can I send GET request with requestParam?
the POST method:
#PostMapping
public ResponseEntity<?> createScore(#RequestBody #JsonView(Views.class) #Valid Score score) {
final String Url = "http://localhost:8080/player?nickname={nickname}";
final Map<String, String> nickname = new HashMap<String, String>();
nickname.put("nickname", score.getPlayer());
String Uri = "http://localhost:8081/game?code={code}";
final Map<String, String> code = new HashMap<String, String>();
code.put("code", score.getGamecode());
Player player = restTemplate.getForObject("http://localhost:8080/player/" + nickname, Player.class);
Game game = restTemplate.getForObject(Uri, Game.class, code);
if ((repo.findByScoreid(score.getScoreid())) == null) {
if((player!= null) && (game!=null)) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("score", score.getScore());
map.put("date", score.getDate());
m = null;
m.add(map);
score.setHistory(m);
repo.save(score);
return ResponseEntity.status(201).body("Created!");
}
else return ResponseEntity.status(400).body("Bad Request!");
}
else
return ResponseEntity.status(409).body("Conflict!");
}
}

Java8 generate Map containing another Map

How do I achieve this using java=8
I have a CSV in below format and from this i want to populate Map<String, Map<String, String>
where the outer map will have key scriptId and transationType as these are the distinct Type and inner map for scriptId key should contain first 5 values stating from position 2 as key and 3 as value.
<scriptId<
<TATA,TATA Moters>
<REL,Reliance Industries Ltd>
<LNT, L&T>
<SBI, State Bank of India>>
<transactionType,<
<P,B>
<S,S>>
Content of CSV File
Type,ArcesiumValue,GICValue
scriptId,TATA,TATA Moters
scriptId,REL,Reliance Industries Ltd
scriptId,LNT,L&T
scriptId,SBI,State Bank of India
transactionType,P,B
transactionType,S,S
How do i generate this using Java8
public void loadReferenceData() throws IOException {
List<Map<String, Map<String, String>>> cache = Files.lines(Paths.get("data/referenceDataMapping.csv")).skip(1)
.map(mapRefereneData).collect(Collectors.toList());
System.out.println(cache);
}
public static Function<String, Map<String, Map<String, String>>> mapRefereneData = (line) -> {
String[] sp = line.split(",");
Map<String, Map<String, String>> cache = new HashMap<String, Map<String, String>>();
try {
if (cache.containsKey(sp[0])) {
cache.get(sp[0]).put(sp[1], sp[2]);
} else {
Map<String, String> map = new HashMap<String, String>();
map.put(sp[1], sp[2]);
cache.put(sp[0], map);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return cache;
};
Well it is much simpler to use two Collectors:
Map<String, Map<String, String>> groupCSV = Files.lines(Paths.get("..."))
.skip(1L).map(l -> l.split(","))
.collect(Collectors.groupingBy(a -> a[0], Collectors.toMap(a -> a[1], a -> a[2])));

Spring batch JdbcPagingItemReader endless loop

I am facing problems with JdbcPagingItemReader. I am stucked in endless loop. I read about that itemReader contract have to return null, but I don't manage to implement it correctly. Somebody can show me an example?
public List<TransactionDTO> getTransactions(Integer chunk, LocalDateTime startDate, LocalDateTime endDate)
throws Exception {
final TransactionMapper transactionMapper = new TransactionMapper();
final SqlPagingQueryProviderFactoryBean sqlPagingQueryProviderFactoryBean = new SqlPagingQueryProviderFactoryBean();
sqlPagingQueryProviderFactoryBean.setDataSource(dataSource);
sqlPagingQueryProviderFactoryBean.setSelectClause(env.getProperty("sql.fromdates.select"));
sqlPagingQueryProviderFactoryBean.setFromClause(env.getProperty("sql.fromdates.from"));
sqlPagingQueryProviderFactoryBean.setWhereClause(env.getProperty("sql.fromdates.where"));
sqlPagingQueryProviderFactoryBean.setSortKey(env.getProperty("sql.fromdates.sort"));
final Map<String, Object> parametros = new HashMap<>();
parametros.put("startDate", startDate);
parametros.put("endDate", endDate);
final JdbcPagingItemReader<TransactionDTO> itemReader = new JdbcPagingItemReader<>();
itemReader.setDataSource(dataSource);
itemReader.setQueryProvider(sqlPagingQueryProviderFactoryBean.getObject());
// TODO esto debe ser el chunk
itemReader.setPageSize(1);
itemReader.setFetchSize(1);
itemReader.setRowMapper(transactionMapper);
itemReader.afterPropertiesSet();
itemReader.setParameterValues(parametros);
ExecutionContext executionContext = new ExecutionContext();
itemReader.open(executionContext);
List<TransactionDTO> list = new ArrayList<>();
TransactionDTO primerDto = itemReader.read();
while (primerDto != null) {
list.add(itemReader.read());
}
itemReader.close();
return list;
}

Fetch properties from Sonarqube via Sonarqube wsClient

I'd like to fetch sonar.timemachine.period1 via wsclient.
Seeing that it doesn't have one, I decided to bake one for myself
private Map<String, String> retrievePeriodProperties(final WsClient wsClient, int requestedPeriod) {
if (requestedPeriod > 0) {
final WsRequest propertiesWsRequestPeriod =
new GetRequest("api/properties/sonar.timemachine.period" + requestedPeriod);
final WsResponse propertiesWsResponsePeriod =
wsClient.wsConnector().call(propertiesWsRequestPeriod);
if (propertiesWsResponsePeriod.isSuccessful()) {
String resp = propertiesWsResponsePeriod.content();
Map<String, String> map = new HashMap<>();
map.put(Integer.toString(requestedPeriod), resp);
return map;
}
}
return new HashMap<>();
}
but it always return an empty Map<>
Any lead where I can go from this direction?
You can use org.sonar.api.config.Settings to fetch properties defined in SonarQube.

Resources