/** * Place a bid on the specified item identifier * * @param id item identifier * @param bid Bid object to represent the bid * @throws AuctionNotFoundException when bid does not exists * @throws BidInvalidException when the bid is lower than the previous one * @throws RemoteException on RMI error */ public void placeBid(int id, Bid bid) throws AuctionNotFoundException, BidInvalidException, RemoteException { logger.info("Placing a new bid for item %d", id); AuctionItem item = auctions.get(id); if (item == null) { logger.warning("Auction %d does not exists", id); throw new AuctionNotFoundException(); } synchronized (item) { if (!item.isOpen()) { logger.warning("Attempt to place a bid on the closed item %d", id); throw new BidInvalidException("Auction is closed for this item"); } if (item.getHighestBid() != null && bid.getValue() <= item.getHighestBid().getValue()) { logger.info("Bid too low on item %d", id); throw new BidInvalidException("Amount is too low"); } item.addBid(bid); } }
private final AuctionItem getAuctionItem(final int auctionItemId) { for (int i = _items.size(); i-- > 0; ) { final AuctionItem item = _items.get(i); if (item.getAuctionItemId() == auctionItemId) return item; } return null; }
// Test method public LinkedList<Integer> getLiveAuctionsIds() throws RemoteException { LinkedList<Integer> ll = new LinkedList<Integer>(); for (AuctionItem t : liveAuctionItems.values()) { ll.add(t.getAuctionId()); } return ll; }
@Override public LinkedList<String> getExistingAuctions() throws RemoteException { LinkedList<String> ll = new LinkedList<String>(); for (AuctionItem i : liveAuctionItems.values()) { ll.add(i.toString()); } return ll; }
public static void show(Long id) { System.out.printf("=== id: %d\n", id); List<AuctionItem> items = AuctionItem.findAll(); for (AuctionItem item : items) { System.out.printf("--- id: %d\n", item.id); } AuctionItem item = AuctionItem.findById(id); item.viewCount++; item.save(); render(item); }
@Override // Event though the data structure for live auctions is concurrent the method still needs to be // synchronized because the creation // of auction items concurrently produces auction items with the same id. public synchronized boolean registerAuctionItem( String name, double min_item_value, Date closing_date, int client) throws RemoteException { AuctionItem item = new AuctionItem(name, min_item_value, closing_date, client, this); liveAuctionItems.put(item.getAuctionId(), item); Thread t = new Thread(item); t.start(); return true; }
private final ItemAuction createAuction(final long after) { final AuctionItem auctionItem = _items.get(Rnd.get(_items.size())); final long startingTime = _dateGenerator.nextDate(after); final long endingTime = startingTime + TimeUnit.MILLISECONDS.convert(auctionItem.getAuctionLength(), TimeUnit.MINUTES); final ItemAuction auction = new ItemAuction( _auctionIds.getAndIncrement(), _instanceId, startingTime, endingTime, auctionItem); auction.storeMe(); return auction; }
public static void doCreateItem(@Valid AuctionItem item) throws IOException { if (validation.hasErrors()) { System.out.println(validation.errorsMap()); render("@createAuctionItem", item); } // set the user based on the logged in user item.createdBy = Authenticate.getLoggedInUser(); item.save(); show(item.id); }
public ArrayList<AuctionItem> getAllAuctions() { ArrayList<AuctionItem> allAuctions = new ArrayList<AuctionItem>(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + AUCTIONS_TABLE + ";", null); if (cursor != null) { if (cursor.moveToFirst()) { while (cursor.isAfterLast() == false) { AuctionItem auction = new AuctionItem(); auction.id = cursor.getInt(cursor.getColumnIndex("ID")); auction.name = cursor.getString(cursor.getColumnIndex(AUCTIONS_NAME)); auction.starting_price = Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_STARTING_PRICE))); auction.created_by = cursor.getString(cursor.getColumnIndex(AUCTIONS_CREATED_BY)); auction.highest_bid = Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BID))); auction.highest_bidder = cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BIDDER)); auction.hours_active = Integer.parseInt(cursor.getString(cursor.getColumnIndex(AUCTIONS_HOURS_ACTIVE))); allAuctions.add(auction); cursor.moveToNext(); } } cursor.close(); } return allAuctions; }
@Override public boolean moveToExpiredAuctions(int auctionId) { if (!liveAuctionItems.containsKey(auctionId)) { System.out.println("This auction does not exist\n"); return false; } AuctionItem temp; if ((temp = liveAuctionItems.remove(auctionId)) != null) { System.out.println("Auction successfully removed from list with live auctions\n"); // Change the auction id to correspond to the index expiredAuctions.put(temp.getAuctionId(), temp); Thread t = new Thread(temp); t.start(); return true; } return false; }
public AuctionItem getAuctionItem(int id) { db = dbHelper.getReadableDatabase(); AuctionItem auction = new AuctionItem(); Cursor cursor = db.query( AUCTIONS_TABLE, null, " ID" + " =?", new String[] {String.valueOf(id)}, null, null, null); if (cursor.getCount() < 1) // item doesn't exist { cursor.close(); return null; } cursor.moveToFirst(); auction.name = cursor.getString(cursor.getColumnIndex(AUCTIONS_NAME)); auction.starting_price = Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_STARTING_PRICE))); auction.created_by = cursor.getString(cursor.getColumnIndex(AUCTIONS_CREATED_BY)); auction.highest_bid = Double.parseDouble(cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BID))); auction.highest_bidder = cursor.getString(cursor.getColumnIndex(AUCTIONS_HIGHEST_BIDDER)); auction.hours_active = Integer.parseInt(cursor.getString(cursor.getColumnIndex(AUCTIONS_HOURS_ACTIVE))); db.close(); return auction; }
public static void search(String search, Integer page) { validation.required(search).message("You must enter something to search for"); if (validation.hasErrors()) { render(); } page = page == null ? 1 : page; SearchResults results = AuctionItem.search(search, page); render(results, page, search); }
public static void newBids(Long id) { // count new bids long newBids = Bid.count( "from AuctionItem a join a.bids as b " + "where a.id = ? AND b.date > ?", id, request.date); // wait if needed if (newBids == 0) { await("1s"); } // return the JSON output of the new bids AuctionItem item = AuctionItem.findById(id); JsonObject json = new JsonObject(); json.addProperty("next", item.getNextBidPrice()); json.addProperty("top", item.getCurrentTopBid()); renderJSON(json.toString()); }
@Override public void notifyResult(AuctionItem item) { if (registeredUsers.containsKey(item.getCreator_id())) { RMIClientIntf creator = registeredUsers.get(item.getCreator_id()); try { creator.callBack("Your Auction has produced the following results :\n "); creator.callBack(item.getResult()); } catch (RemoteException e) { System.out.println("Creator no longer online\n"); } } else { System.out.println("Creator id does not exist\n"); } // Normally an auction with no creator registered should not exist but since this is a // simplified implementation // We allow bids on auctions with no creator (usually the initialised ones) for testing // purposes. if (item.numberOfBids() != 0) { System.out.println("Notifying bidders"); Iterator<Bid> it = item.getBidders(); while (it.hasNext()) { Bid bidder = it.next(); if (registeredUsers.containsKey(bidder.getUserId())) { RMIClientIntf client = registeredUsers.get(bidder.getUserId()); try { client.callBack(item.getResult()); } catch (RemoteException e) { System.out.println("Bidder with id " + bidder.getUserId() + " no longer online\n"); } } else { System.out.println("User id does not exist\n"); } } } }
public static void recentlyAdded() { List<AuctionItem> items = AuctionItem.recentlyAdded(50); render(items); }
/** * Get auction item name. * * @return the string */ public String getAuctionItemName() { return auctionItem.getItemName(); }
public static void main(String args[]) { AuctionItem item1 = new AuctionItem("Carnations = a Painting", 780.00, 500.00); item1.showItemStatus(); item1.makeABid(300.00, "*****@*****.**"); item1.showItemStatus(); item1.makeABid(510.00, "*****@*****.**"); item1.showItemStatus(); item1.makeABid(600.00, "*****@*****.**"); item1.showItemStatus(); item1.sell(); item1.showSaleInfo(); item1.showItemStatus(); item1.sell(item1.getItemPrice()); item1.showItemStatus(); item1.cancelSale(); item1.makeABid(520.00, "*****@*****.**"); item1.showItemStatus(); item1.sell(item1.getItemPrice(), "*****@*****.**"); item1.showSaleInfo(); item1.showItemStatus(); // Test the Auction class Auction auction1 = new Auction(); auction1.addAuctionItem(item1); auction1.addAuctionItem(new AuctionItem("IPAD1", 100.00, 70.00)); // add at least 3 more AuctionItem instances of your choice auction1.addAuctionItem(new AuctionItem("Binke", 10.00, 7.00)); auction1.addAuctionItem(new AuctionItem("kebing", 200.00, 50.00)); auction1.addAuctionItem(new AuctionItem("luobing", 80.00, 9.00)); auction1.showAllAuctionItems(); auction1.showAuctionItemsByStatus("SOLD"); auction1.showAuctionItemsByStatus("AVAILABLE"); auction1.showAuctionItemStatus("carnations = a painting"); auction1.showAuctionItemWithHighestBid(); }
public static void showPDF(Long id) { AuctionItem item = AuctionItem.findById(id); item.viewCount++; item.save(); renderPDF(item); }
public static void index() { List<AuctionItem> mostPopular = AuctionItem.getMostPopular(5); List<AuctionItem> endingSoon = AuctionItem.getEndingSoon(5); render(mostPopular, endingSoon); }
public static void showImage(Long id) { AuctionItem item = AuctionItem.findById(id); response.setContentTypeIfNotSet(item.photo.type()); renderBinary(item.photo.get()); }
/** * Get auction item price. * * @return the double */ public double getAuctionItemPrice() { return auctionItem.getItemPrice(); }
public static void main(String args[]) { String host = "localhost"; int port = 1099; if (args.length > 0) { host = args[0]; port = Integer.parseInt(args[1]); } // Initialise auctions from permanent storage BufferedReader br = null; BufferedWriter bw = null; try { AuctionServer rmiServer = new AuctionServer(); Registry reg = LocateRegistry.getRegistry(host, port); reg.rebind("auctionServer", rmiServer); System.out.println("AuctionServer is ready"); System.out.println( "Select one of the two options :\n1: To save live auctions\n2: To load test auctions that expire in a minute (note you need to start 5 clients first) "); Scanner sc = new Scanner(System.in); bw = new BufferedWriter(new FileWriter("auctionsSaved.dat")); switch (sc.nextInt()) { case 1: for (AuctionItem item : rmiServer.liveAuctionItems.values()) { bw.write(item.toString() + "\n"); } System.out.println("Saved auctions state."); break; case 2: GenerateAuctions generator = new GenerateAuctions(); generator.generateList(); br = new BufferedReader(new FileReader("auctionsBackup.dat")); String currentLine; while ((currentLine = br.readLine()) != null) { String[] array = currentLine.split(","); String name = array[0]; double min_item_value = Double.parseDouble(array[1]); Date closing_date = new SimpleDateFormat("d/M/y H:mm:s").parse(array[2]); int client = Integer.parseInt(array[3]); rmiServer.registerAuctionItem(name, min_item_value, closing_date, client); } System.out.println("Initialised auctions..."); break; } } catch (RemoteException e) { System.out.println("Exception in AuctionServer.main " + e); } catch (MalformedURLException ue) { System.out.println("MalformedURLException in RMIServerImp.main " + ue); } catch (IOException e) { System.out.println("Could not open file "); e.printStackTrace(); } catch (ParseException e) { System.out.println("Unable to parse date"); e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { System.out.println("Unable to close file."); } } if (bw != null) { try { bw.close(); } catch (IOException e) { System.out.println("Unable to close file."); } } } }
public static void addBid(Long id, Float amount) { AuctionItem item = AuctionItem.findById(id); item.addBid(amount); item.save(); }
/** * static method to create the object Precondition: If this object is an element, the current or * next start element starts this object and any intervening reader events are ignorable If this * object is not an element, it is a complex type and the reader is at the event just after the * outer start element Postcondition: If this object is an element, the reader is positioned at * its end element If this object is a complex type, the reader is positioned at the end element * of its outer element */ public static AuctionItem parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception { AuctionItem object = new AuctionItem(); int event; java.lang.String nillableValue = null; java.lang.String prefix = ""; java.lang.String namespaceuri = ""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) { java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName != null) { java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1) { nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":")); } nsPrefix = nsPrefix == null ? "" : nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1); if (!"auctionItem".equals(type)) { // find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (AuctionItem) edu.columbia.ase.auctionhouse.webservice.ExtensionMapper.getTypeObject( nsUri, type, reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); // handle attribute "itemId" java.lang.String tempAttribItemId = reader.getAttributeValue(null, "itemId"); if (tempAttribItemId != null) { java.lang.String content = tempAttribItemId; object.setItemId( org.apache.axis2.databinding.utils.ConverterUtil.convertToInt(tempAttribItemId)); } else { throw new org.apache.axis2.databinding.ADBException( "Required attribute itemId is missing"); } handledAttributes.add("itemId"); // handle attribute "itemName" java.lang.String tempAttribItemName = reader.getAttributeValue(null, "itemName"); if (tempAttribItemName != null) { java.lang.String content = tempAttribItemName; object.setItemName( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(tempAttribItemName)); } else { } handledAttributes.add("itemName"); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException( "Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; }
public ItemAuctionInstance(final int instanceId, final AtomicInteger auctionIds, final Node node) throws Exception { _instanceId = instanceId; _auctionIds = auctionIds; _auctions = new TIntObjectHashMap<ItemAuction>(); _items = new ArrayList<AuctionItem>(); final NamedNodeMap nanode = node.getAttributes(); final StatsSet generatorConfig = new StatsSet(); for (int i = nanode.getLength(); i-- > 0; ) { final Node n = nanode.item(i); if (n != null) generatorConfig.set(n.getNodeName(), n.getNodeValue()); } _dateGenerator = new AuctionDateGenerator(generatorConfig); for (Node na = node.getFirstChild(); na != null; na = na.getNextSibling()) { try { if ("item".equalsIgnoreCase(na.getNodeName())) { final NamedNodeMap naa = na.getAttributes(); final int auctionItemId = Integer.parseInt(naa.getNamedItem("auctionItemId").getNodeValue()); final int auctionLenght = Integer.parseInt(naa.getNamedItem("auctionLenght").getNodeValue()); final long auctionInitBid = Integer.parseInt(naa.getNamedItem("auctionInitBid").getNodeValue()); final int itemId = Integer.parseInt(naa.getNamedItem("itemId").getNodeValue()); final int itemCount = Integer.parseInt(naa.getNamedItem("itemCount").getNodeValue()); if (auctionLenght < 1) throw new IllegalArgumentException( "auctionLenght < 1 for instanceId: " + _instanceId + ", itemId " + itemId); final StatsSet itemExtra = new StatsSet(); final AuctionItem item = new AuctionItem( auctionItemId, auctionLenght, auctionInitBid, itemId, itemCount, itemExtra); if (!item.checkItemExists()) throw new IllegalArgumentException("Item with id " + itemId + " not found"); for (final AuctionItem tmp : _items) { if (tmp.getAuctionItemId() == auctionItemId) throw new IllegalArgumentException("Dublicated auction item id " + auctionItemId); } _items.add(item); for (Node nb = na.getFirstChild(); nb != null; nb = nb.getNextSibling()) { if ("extra".equalsIgnoreCase(nb.getNodeName())) { final NamedNodeMap nab = nb.getAttributes(); for (int i = nab.getLength(); i-- > 0; ) { final Node n = nab.item(i); if (n != null) itemExtra.set(n.getNodeName(), n.getNodeValue()); } } } } } catch (final IllegalArgumentException e) { _log.log(Level.WARNING, "ItemAuctionInstance: Failed loading auction item", e); } } if (_items.isEmpty()) throw new IllegalArgumentException("No items defined"); Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(); PreparedStatement statement = con.prepareStatement("SELECT auctionId FROM item_auction WHERE instanceId=?"); statement.setInt(1, _instanceId); ResultSet rset = statement.executeQuery(); while (rset.next()) { final int auctionId = rset.getInt(1); try { final ItemAuction auction = loadAuction(auctionId); if (auction != null) { _auctions.put(auctionId, auction); } else { ItemAuctionManager.deleteAuction(auctionId); } } catch (final SQLException e) { _log.log(Level.WARNING, "ItemAuctionInstance: Failed loading auction: " + auctionId, e); } } } catch (final SQLException e) { _log.log(Level.SEVERE, "L2ItemAuctionInstance: Failed loading auctions.", e); return; } finally { L2DatabaseFactory.close(con); } _log.log( Level.INFO, "L2ItemAuctionInstance: Loaded " + _items.size() + " item(s) and registered " + _auctions.size() + " auction(s) for instance " + _instanceId + "."); checkAndSetCurrentAndNextAuction(); }