2 * Copyright (C) 2015 Roland Haeder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.jshopcore.model.basket;
19 import java.util.Deque;
20 import java.util.LinkedHashMap;
21 import java.util.LinkedList;
23 import java.util.Objects;
24 import org.mxchange.jshopcore.exceptions.BasketItemAlreadyAddedException;
27 * A general basket class. This class does not store any properties, it only
28 * contains logic for handling the items (T).
30 * @author Roland Haeder<roland@mxchange.org>
31 * @param <T> Any instance that implements AddableBasketItem
33 public abstract class BaseBasket<T extends AddableBasketItem> implements Basket<T> {
37 private static final long serialVersionUID = 782_396_762_230_845_717L;
42 private final Deque<T> deque;
45 * Protected constructor with session instance
47 protected BaseBasket () {
49 this.deque = new LinkedList<>();
53 public void addItem (final T item) throws BasketItemAlreadyAddedException {
54 // item must not be null
57 throw new NullPointerException("item is null"); //NOI18N
58 } else if (this.isAdded(item)) {
60 throw new BasketItemAlreadyAddedException(item); //NOI18N
68 public boolean isEmpty () {
69 // Deligate call to frontend
70 return this.deque.isEmpty();
74 public Map<Long, T> getAll () {
76 Map<Long, T> map = new LinkedHashMap<>(this.deque.size());
78 // Iterate over full item list
79 for (T item : this.deque) {
80 // item should not be null
83 throw new NullPointerException("item is null"); //NOI18N
86 // Add to map, use the item's id as key
87 map.put(item.getItemId(), item);
97 return this.deque.getLast();
101 public int getLastNumRows () {
102 // Is the list empty?
103 assert this.isEmpty() : "deque is empty"; //NOI18N
106 return (this.deque.size() - 1);
110 public boolean isAdded (final T item) {
111 // item must not be null
114 throw new NullPointerException("item is null"); //NOI18N
118 Map<Long, T> map = this.getAll();
120 // Default is not found
121 boolean isAdded = false;
123 for (Map.Entry<Long, T> entrySet : map.entrySet()) {
125 Long itemId = entrySet.getKey();
128 if (Objects.equals(itemId, item.getItemId())) {