How to group data specific field wise? - java

I am getting data from database for specific category.
Suppose I select or pass data to query that category is Laptop then it give me data of all attribute and it's value.
Like :
My Code to getting and display data on JSP page is :
<%
List<String> attribNameList = (List<String>)request.getAttribute("attribName");
List<String> attribValueList = (List<String>)request.getAttribute("attribValue");
List<String> attribDataList = (List<String>)request.getAttribute("attribData");
String aname,aval,adata;
for(int i = 0 ; i<attribValueList.size() ; i++)
{
aname = attribNameList.get(i);
aval = attribValueList.get(i);
adata = attribDataList.get(i);
%>
<a><%=i%><%= aname %></a>
<a><%= aval %></a>
<%
if(adata == null)
{
}
else
{
%>
<a><%= adata %></a>
<%
}
%>
<br>
<%
}
%>
Here aname display attribute name i.e. RAM, Processor, etc.
aval display value i.e. 4, 2.8, etc.
and adata display last data i.e. GB, GHz, MP, etc.
Now I want to display data as category wise like all memory attribute will display first.
Like :
RAM 4 GB
HDD 1 TB
Cache 3 MB, etc.
How can I display data in such format ?
I have tried using if condition where adata variable checked with
if(adata.equals("GB")||adata.equals("TB")||adata.equals("MB"))
{
//memory category data display
}
else
{
//Other data
}
but it isn't working.
Any Suggestion Please...

How about creating a custom object to store your entries:
class MyDataRow implements Comparable<MyDataRow> {
private String aname;
private String aval;
private String adata;
// getters, setters, constructors etc
#Override
public int compareTo(MyDataRow other) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if(other == null) return AFTER;
if(other.getAdata().equals(this.adata)) return EQUALS;
if(this.adata.equals("GB")||this.adata.equals("TB")||this.adata.equals("MB"))
{
if(other.getAdata().equals("GB") || xxxxxxx) return EQUAL;
return BEFORE;
}
if(next category in the list... etc etc)
}
}
Then the result of your database query populates a List. In MyDataRow, you override the 'compareTo' method with the ordering logic that you want. Before you enter the loop that prints out your list to the page, call Collections.sort(myDataRowList) :
List<MyDataRow> myDataRowList = new ArrayList<MyDataRow>();
for(int i = 0 ; i<attribValueList.size() ; i++)
{
aname = attribNameList.get(i);
aval = attribValueList.get(i);
adata = attribDataList.get(i);
myDataRowList.add(new MyDataRow(aname, aval, adata);
}
Collections.sort(myDataRowList); // now your myDataRowList is sorted in the order you want
for(MyDataRow myDataRow : myDataRowList) {
// print rows to screen
}

Related

Spring-hibernate debug

I have a very strange problem. I'm trying to show in a basket the price of products. When I run the code and add a product to the basket, I can see the name of the product but I can't see its price. When I click back to a previous page and add another product, I am able to see its price. There is no error message.
Also, when I try to debug this program, everything works. The problem appears only when I'm not debugging. The problem is closely connected with these two variables as indicated below. I think that these variables are 0 which is later printed on the screen. But I don't know why they are sometimes 0 and sometimes not. I also tried to set breakpoints on:
dataService.getQuantityOfDays();
dataService.getQuantityOfBreakfasts();
When I assign values to these two variables in Data class everything is ok (not 0).
Controller code:
#RequestMapping("/basket/{roomName}")
public String createBasket(Model model, #PathVariable("roomName") String roomName){
Floor currentFloor = floorService.getCurrentFloor();
User currentUser = userService.getCurrentUser();
this.roomName = roomName;
if(currentFloor != null){
Room currentRoom = roomService.getRoomByName(roomName, currentFloor);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
if(currentUser == null){
userService.setCurrentUser(userService.getUserByName(name)); // wykona sie jesli nie zakladamy konta w danej sesji
}
Basket basketToSave = new Basket(userService.getCurrentUser());
BasketItem basketItem = new BasketItem(currentRoom);
int quantityOfDays = dataService.getQuantityOfDays(); //<--problem
int quantityOfBreakfast = dataService.getQuantityOfBreakfasts(); //<--problem
int priceForOneBreakfast = 17;
int priceForOneDay = currentRoom.getPriceForOneDay();
int wholePrice = quantityOfDays * priceForOneDay + quantityOfBreakfast * priceForOneBreakfast;
basketItem.setPrice(wholePrice);
basketItem.setQuantityOfDays(quantityOfDays);
basketItem.setQuantityOfBreakfast(quantityOfBreakfast);
Set<BasketItem> basketItemList = new HashSet<BasketItem>();
basketItemList.add(basketItem);
basketService.countBasketPrice(basketItemList, basketToSave);
basketToSave.setBasketItems(basketItemList);
basketItem.setBasket(basketToSave);
currentRoom.setBasketItemList(basketItemList);
boolean ifWasAnUpdate = basketService.save(basketToSave); // metoda save oprócz zapisu lub nadpisania zwraca co się wydarzyło (true - jesli nadpisywaliśmy koszyk)
if(ifWasAnUpdate){
basketItem.setBasket(basketService.get(basketToSave.getUser())); // jeżeli dodaje coś do koszyka (a nie tworzę go od nowa), muszę ustawić basketItemowi
} // koszyk, który już istnieje, a nie ten, który stworzyłem wcześniej w klasie BasketController.
// W tym celu pobieram go z bazy.
basketItemService.save(basketItem);
}
model.addAttribute("basket", basketService.get(currentUser));
model.addAttribute("days", dataService.getQuantityOfDays());
return "basket";
}
EDIT:
It's a repository code.
#Repository
public class DataRepositoryImpl implements DataRepository {
private int quantityOfDays;
private int quantityOfBreakfasts;
public void setQuantityOfDaysAndBreakfasts(String text) {
List<Integer> listOfIndexes = new ArrayList<Integer>();
for(int i=0;i<text.length();i++){
if(text.charAt(i) != '1'){
listOfIndexes.add(i);
}
}
char znak = text.charAt(listOfIndexes.get(0));
this.quantityOfDays = Character.getNumericValue(text.charAt(listOfIndexes.get(0))); // <- I put breakpoint here
this.quantityOfBreakfasts = Character.getNumericValue(text.charAt(listOfIndexes.get(1))); // <- I put breakpoint here
}
public int getQuantityOfDays() {
return this.quantityOfDays;
}
public int getQuantityOfBreakfasts() {
return this.quantityOfBreakfasts;
}
}
A problem can be also in basket save. Firslty when I can see only zeros I persist basket, then I'm only updating it.
Save & update methods:
public boolean save(Basket basketToSave) {
List<Basket> listOfAllBaskets = getAll();
boolean save = true;
boolean ifWasAnUpdate = false;
for(Basket basket: listOfAllBaskets){
if(basketToSave.getUser().equals(basket.getUser())){
save = false;
}
}
if(save){
emManager.persist(basketToSave);
}else{
updateBasket(basketToSave);
ifWasAnUpdate = true;
}
return ifWasAnUpdate;
}
public void updateBasket(Basket basket) {
Basket basketFromDatabase = get(basket.getUser());
basketFromDatabase.setBasketItems(basket.getBasketItems());
basketFromDatabase.setPrice(basket.getPrice());
emManager.merge(basketFromDatabase);
}
EDIT
I'm calling setQuantityOfDaysAndBreakfasts(text) earlier in this apllication. In this controller I'm only setting these values to basketItem class. I'll change this controller. Here another controller where I call setQuantityOfDaysAndBreakfasts(text).
#RequestMapping(value = "/room/rest", method = RequestMethod.POST, consumes = {"application/json"})
public void data(#RequestBody Data request){
String text = request.getText();
dataService.setQuantityOfDaysAndBreakfasts(text);
}
You are calling setQuantityOfDaysAndBreakfasts() after you get the value from your dataService. The value for quantityOfDays and quantityOfBreakfasts are only set when that method is called.
There are several things you should also examine.
As #NathanHughes points out, it's best to put your complex logic in your service layer and leave the controller to simply route requests. This is also true of your repository class. You should keep this very simple as the next developer reading your code is not going to expect to find any logic that doesn't simply read or write to your data source. (See Single Responsibility Principle.) It will also reduce code duplication in the future and as a result, reduce your time maintaining and fixing bugs.
For example, this code:
List<Integer> listOfIndexes = new ArrayList<Integer>();
for(int i=0;i<text.length();i++){
if(text.charAt(i) != '1'){
listOfIndexes.add(i);
}
}
char znak = text.charAt(listOfIndexes.get(0));
Should be refactored to a separate method entirely that can be made static and would not belong in that class.

Receiving "null" in Place of Correct Values

I'm currently using Jersey REST to create a webpage that has a list of birds and taxonomy number, with a link to a page specifically about the bird in question. While my links work between the two pages, and my Bird Name and Taxonomy Number appear, I can't get the order or family name to appear. Following is the code in question.
#Path("/birdslist")
public class BirdsList extends Birds {
#GET
#Path("/all")
#Produces("text/html")
public String all() {
Iterator iterator = birdnames.keySet().iterator();
String page = "<html><title>All Birds</title><body>";
page += "<p>This is the list of all birds. <br> Click the taxonomy number of the bird you wish to view in detail.</p>";
while(iterator.hasNext()){
Object key = iterator.next();
String value = birdnames.get(key);
HashSet fam = family.get(key);
HashSet ord = order.get(key);
}
for (String key : birdnames.keySet()) {
page += String.format("<p>Name:%s <br> Taxonomy Number:<a href=%s>%s</a></p>",birdnames.get(key),key,
key);
getBird(key);
}
page += "</body></html>";
return page;
}
#GET
#Path("{key}")
#Produces("text/html")
public String getBird(#PathParam("key") String key) {
String page = "<html><title>Bird #: {key}</title><body>";
page += String.format("<p>This page contains info on the %s</p>",birdnames.get(key));
page += String.format("<p>Name:%s <br> Taxonomy Number:%s <br> Family:%s <br> Order:%s</p>",birdnames.get(key),key,family.get(key),order.get(key));
page += "<p>Please click <a href=all>here</a> to return to the list of all birds.</p>";
page += "</body></html>";
return page;
}
}
The family and order are saved in a HashSet that is inside of a hashmap, while bird name is in a hashmap. It was written over from a csv file and converted into hashmaps. Following is that code.
public class Birds {
HashMap<String,String> birdnames;
HashMap<String,HashSet<String>> family;
HashMap<String,HashSet<String>> order;
/**
Constructor reads the CSV of all birds
*/
public Birds() {
// long path to eBirds assuming Maven "mvn exec:java" is many levels up
String fileName = "src/main/java/com/example/rest/eBirds.csv";
boolean firstLine = true;
this.birdnames = new HashMap<String,String>();
this.family = new HashMap<String,HashSet<String>>();
this.order = new HashMap<String,HashSet<String>>();
try {
BufferedReader R = new BufferedReader(new FileReader(fileName));
String line;
while (true) {
line = R.readLine();
if (line == null) break;
if (firstLine) { // ignore the first line, it's not a bird
firstLine = false;
continue;
}
String[] fields = line.split(",");
if (!fields[1].equalsIgnoreCase("species")) continue; // ignore all but species records
birdnames.put(fields[0],fields[4]); // add this bird to name table
// extract the order name from fields[6]
String ordername = fields[6];
if (!order.containsKey(ordername)) { // if needed, create first-time order set
order.put(ordername,new HashSet<String>());
}
order.get(ordername).add(fields[0]); // new order member by number for lookup
// extract the family name from fields[7] -- removing quotes first if needed
String famname = fields[7].replace("\"","");
if (!family.containsKey(famname)) { // if needed, create first-time family set
family.put(famname,new HashSet<String>());
}
family.get(famname).add(fields[0]); // new family member by number for lookup
}
}
catch (IOException e) { System.out.println("Stack trace: " + e); }
}
...
}
I've never used HashSets before, that was part of the given info to us. Our assignment was to create a list page and pages specific to each bird and link between the two. I just can't get these last two values to appear correctly. Can anyone help?
Here you use the same key for all values, birdnames, family and order:
while(iterator.hasNext()){
Object key = iterator.next();
String value = birdnames.get(key);
HashSet fam = family.get(key);
HashSet ord = order.get(key);
}
But you initialize them with different keys:
// extract the order name from fields[6]
String ordername = fields[6];
if (!order.containsKey(ordername))
{ // if needed, create first-time order set
order.put(ordername, new HashSet<>());
}
order.get(ordername).add(fields[0]); // new order member by number for lookup
Here the key would be fields[6] and not the birdnames key.
If you want to keep using the same key, you could do the following for the orders:
if (!order.containsKey(fields[0]))
{
order.put(fields[0], new HashSet<>());
}
order.get(fields[0]).add(fields[6]);
Then you can use:
HashSet ord = order.get(key);
And you will receive all the orders for that bird name.
If you don't want to change that and still use the same key you could do something like the following, but that is highly discouraged as it destroys the purpose of using a map in the first place:
Set<String> ord = new HashSet<>();
for (String tmp : order.keySet())
{
if (order.get(tmp).contains(key))
ord.add(tmp);
}
Here ord would contain all the orders for the "key".
As you can see, you need to do much more redundant work, if you don't switch value and "key".

Adjusting page or limit from last.fm api in java eclipse

I`m Student
I am using current last.fm Developer api at java eclipse.
But the problem occurred during use.
I wanted metadata values of a large amount.
But result is only 50 pieces.
I know that the default value is 50.
So, I have adjusted Page or limit but the result still shows 50 pieces.
What is reason?
public static void main(String[] args) {
String key="#########";
String tag = "ballad";
int limit = 100;
int page = 2;
int i = 1;
Chart<Artist> I3 = Tag.getWeeklyArtistChart(tag, page, key);
Iterable<Artist> tag3 = I3.getTopArtists(page, key);
for (Artist artist : tag3) {
System.out.println("["+i+"]"+""+artist.getName());
i++;
}
}
result
[1]Drake
[2]Ellie Goulding
.
.
.
.
[50]One Direction
Yes, the default is "50" and always "50", because you don't even set or use the items per page limit. see chart.getTopArtist(page, limit, api_key)
You need to add item per pages limit in:
Iterable<Artist> tag3 = I3.getTopArtists(page, limit, key)
Full Code:
public static void main(String[] args) {
String key="#########";
String tag = "ballad";
int limit = 100;
int page = 2;
int i = 1;
Chart<Artist> I3 = Tag.getWeeklyArtistChart(tag, page, key); // You can also set the limit here. (optional)
Iterable<Artist> tag3 = I3.getTopArtists(page, limit, key); // Try to add the limit here. (optional)(Default 50)
for (Artist artist : tag3) {
System.out.println("["+i+"]"+""+artist.getName());
i++;
}
}

manipulate and sort text file

I am working on a project where I have been given a text file and I have to add up the points for each team and printout the top 5 teams.
The text file looks like this:
FRAMae Berenice MEITE 455.455<br>
CHNKexin ZHANG 454.584<br>
UKRNatalia POPOVA 453.443<br>
GERNathalie WEINZIERL 452.162<br>
RUSEvgeny PLYUSHCHENKO 191.399<br>
CANPatrick CHAN 189.718<br>
CHNHan YAN 185.527<br>
CHNCheng & Hao 271.018<br>
ITAStefania & Ondrej 270.317<br>
USAMarissa & Simon 264.256<br>
GERMaylin & Daniel 260.825<br>
FRAFlorent AMODIO 179.936<br>
GERPeter LIEBERS 179.615<br>
JPNYuzuru HANYU 197.9810<br>
USAJeremy ABBOTT 165.654<br>
UKRYakov GODOROZHA 160.513<br>
GBRMatthew PARR 157.402<br>
ITAPaul Bonifacio PARKINSON 153.941<br>
RUSTatiana & Maxim 283.7910<br>
CANMeagan & Eric 273.109<br>
FRAVanessa & Morgan 257.454<br>
JPNNarumi & Ryuichi 246.563<br>
JPNCathy & Chris 352.003<br>
UKRSiobhan & Dmitri 349.192<br>
CHNXintong &Xun 347.881<br>
RUSYulia LIPNITSKAYA 472.9010<br>
ITACarolina KOSTNER 470.849<br>
JPNMao ASADA 464.078<br>
UKRJulia & Yuri 246.342<br>
GBRStacey & David 244.701<br>
USAMeryl &Charlie 375.9810<br>
CANTessa & Scott 372.989<br>
RUSEkaterina & Dmitri 370.278<br>
FRANathalie & Fabian 369.157<br>
ITAAnna & Luca 364.926<br>
GERNelli & Alexander 358.045<br>
GBRPenny & Nicholas 352.934<br>
USAAshley WAGNER 463.107<br>
CANKaetlyn OSMOND 462.546<br>
GBRJenna MCCORKELL 450.091<br>
The first three letters represent the team.
the rest of the text is the the competitors name.
The last digit is the score the competitor recived.
Code so far:
import java.util.Arrays;
public class project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = new String[41];
String[] info = new String[41];
String[] stats = new String[41];
String[] team = new String[41];
//.txt file location
FileInput fileIn = new FileInput();
fileIn.openFile("C:\\Users\\O\\Desktop\\turn in\\team.txt");
// txt file to array
int i = 0;
String line = fileIn.readLine();
array[i] = line;
i++;
while (line != null) {
line = fileIn.readLine();
array[i] = line;
i++;
}
//Splitting up Info/team/score into seprate arrays
for (int j = 0; j < 40; j++) {
team[j] = array[j].substring(0, 3).trim();
info[j] = array[j].substring(3, 30).trim();
stats[j] = array[j].substring(36).trim();
}
// Random stuff i have been trying
System.out.println(team[1]);
System.out.println(info[1]);
System.out.println(stats[1]);
MyObject ob = new MyObject();
ob.setText(info[0]);
ob.setNumber(7, 23);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(7));
}
}
I'm pretty much stuck at this point because I am not sure how to add each teams score together.
This looks like homework... First of all you need to examine how you are parsing the strings in the file.
You're saying: the first 3 characters are the country, which looks correct, but then you set the info to the 4th through the 30th characters, which isn't correct. You need to dynamically figure out where that ends and the score begins. There is a space between the "info" and the "stats," knowing that you could use String's indexOf function. (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int))
Have a look at Maps.
A map is a collection that allows you to get data associated with a key in a very short time.
You can create a Map where the key is a country name, with value being the total points.
example:
Map<String,Integer> totalScore = new HashMap<>();
if (totalScore.containsKey("COUNTRYNAME"))
totalScore.put("COUNTRYNAME", totalScore.get("COUNTRYNAME") + playerScore)
else
totalScore.put("COUNTRYNAME",0)
This will add to the country score if the score exists, otherwise it will create a new totalScore for a country initialized to 0.
Not tested, but should give you some ideas:
public static void main(String... args)
throws Exception {
class Structure implements Comparable<Structure> {
private String team;
private String name;
private Double score;
public Structure(String team, String name, Double score) {
this.team = team;
this.name = name;
this.score = score;
}
public String getTeam() {
return team;
}
public String getName() {
return name;
}
public Double getScore() {
return score;
}
#Override
public int compareTo(Structure o) {
return this.score.compareTo(o.score);
}
}
File file = new File("path to your file");
List<String> lines = Files.readAllLines(Paths.get(file.toURI()), StandardCharsets.UTF_8);
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
List<Structure> structures = new ArrayList<Structure>();
for (String line : lines) {
Matcher m = p.matcher(line);
while (m.find()) {
String number = m.group(1);
String text = line.substring(0, line.indexOf(number) - 1);
double d = Double.parseDouble(number);
String team = text.substring(0, 3);
String name = text.substring(3, text.length());
structures.add(new Structure(team, name, d));
}
}
Collections.sort(structures);
List<Structure> topFive = structures.subList(0, 5);
for (Structure structure : topFive) {
System.out.println("Team: " + structure.getTeam());
System.out.println("Name: " + structure.getName());
System.out.println("Score: " + structure.getScore());
}
}
Just remove <br> from your file.
Loading file into memory
Your string splitting logic looks fine.
Create a class like PlayerData. Create one instance of that class for each row and set all the three fields into that using setters.
Keep adding the PlayerData objects into an array list.
Accumulating
Loop through the arraylist and accumulate the team scores into a hashmap. Create a Map to accumulate the team scores by mapping teamCode to totalScore.
Always store row data in a custom object for each row. String[] for each column is not a good way of holding data in general.
Take a look in File Utils. After that you can extract the content from last space character using String Utils e removing the <br> using it as a key for a TreeMap. Than you can have your itens ordered.
List<String> lines = FileUtils.readLines(yourFile);
Map<String, String> ordered = new TreeMap<>();
for (String s : lines) {
String[] split = s.split(" ");
String name = split[0].trim();
String rate = splt[1].trim().substring(0, key.length - 4);
ordered.put(rate, name);
}
Collection<String> rates = ordered.values(); //names ordered by rate
Of course that you need to adjust the snippet.

Compare field from previous row in JDBC ResultSet

I've researched can't find any relevant info. I have a result set that give me back distinct tagId's their can be multiple tagIds for same accountId's.
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
// plenty of other fields being store locally
}
I need to store first accoundId(which is being done) & every subsequent iteration compare it with the previous Id to check for equality or not(if so same account).
I tried this and it failed horribly, after first iteration they'll continually be equal & I must be DUMB bc i though as long as I compare them before assignment global guy(previousId) should be holding the prior value.
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
previousId = accountId;
}
Anyway I wanted my workflow to go something as follows:
while(result_set.next()){
if (previousId = null) {
// this would be the first iteration
}
else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
}
If I've understood you well, this should work..
String previousId = null;
while(result_set.next()){
String tagId = result_set.getString("tagId");
String accountId = result_set.getString("accoundId");
if (previousId == null) {
// this would be the first iteration
} else if (previousId.equals(accountId) {
// go here
} else {
// go here
}
previousId = accountId;
}

Categories

Resources