com.mobiaware.auction.event.AuctionResource.java Source code

Java tutorial

Introduction

Here is the source code for com.mobiaware.auction.event.AuctionResource.java

Source

/*
 * Copyright (c) 2010 mobiaware.com.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.mobiaware.auction.event;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.joda.time.DateTime;

import com.google.inject.Injector;
import com.mobiaware.auction.data.DataService;
import com.mobiaware.auction.model.Auction;
import com.mobiaware.auction.model.Fund;
import com.mobiaware.auction.model.Item;
import com.mobiaware.auction.model.User;
import com.mobiaware.auction.provider.ExportService;

@Path("/auctions")
@Produces({ MediaType.APPLICATION_JSON })
public class AuctionResource {
    private final DataService _dataService;

    @Inject
    public AuctionResource(final DataService dataService) {
        _dataService = dataService;
    }

    @GET
    public List<Auction> getAuctions(@DefaultValue("0") @QueryParam("start") final int start,
            @DefaultValue("9999") @QueryParam("size") final int size, @QueryParam("sort") final String sort,
            @QueryParam("dir") final String dir) {
        List<Auction> auctions = _dataService.getAuctions(start, size, sort, dir);

        if (auctions == null) {
            throw new NotFoundException();
        }

        return auctions;
    }

    @GET
    @Path("/count")
    public Integer getAuctionCount() {
        return _dataService.getAuctionCount();
    }

    @GET
    @Path("/{auction}")
    public Auction getAuction(@PathParam("auction") final int auctionUid) {
        Auction auction = _dataService.getAuction(auctionUid);

        if (auction == null) {
            throw new NotFoundException();
        }

        return auction;
    }

    @POST
    @Consumes({ MediaType.APPLICATION_JSON })
    public Auction addAuction(final Auction auction) {
        int uid = _dataService.editAuction(auction);

        if (uid < 0) {
            throw new InternalServerErrorException();
        }

        return auction.toBuilder().setUid(uid).build();
    }

    @PUT
    @Consumes({ MediaType.APPLICATION_JSON })
    public Auction editAuction(final Auction auction) {
        int uid = _dataService.editAuction(auction);

        if (uid < 0) {
            throw new InternalServerErrorException();
        }

        return auction.toBuilder().setUid(uid).build();
    }

    @DELETE
    @Path("/{auction}")
    public void deleteAuction(@PathParam("auction") final int auctionUid) {
        int uid = _dataService.deleteAuction(auctionUid);

        if (uid < 0) {
            throw new InternalServerErrorException();
        }
    }

    @GET
    @Path("/{auction}/start")
    public Auction startAuction(@PathParam("auction") final int auctionUid) {
        Auction auction = _dataService.getAuction(auctionUid);

        if (auction == null) {
            throw new NotFoundException();
        }

        DateTime today = new DateTime();
        DateTime tomorrow = today.plusDays(30); // +30 days

        auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(tomorrow.getMillis()).build();

        int uid = _dataService.editAuction(auction);

        if (uid < 0) {
            throw new InternalServerErrorException();
        }

        return auction;
    }

    @GET
    @Path("/{auction}/stop")
    public Auction stopAuction(@PathParam("auction") final int auctionUid) {
        Auction auction = _dataService.getAuction(auctionUid);

        if (auction == null) {
            throw new NotFoundException();
        }

        DateTime today = new DateTime();
        DateTime yesterday = today.minusDays(1); // -1 days

        auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(yesterday.getMillis()).build();

        int uid = _dataService.editAuction(auction);

        if (uid < 0) {
            throw new InternalServerErrorException();
        }

        return auction;
    }

    @GET
    @Path("/{auction}/bids/export")
    @Produces("text/csv")
    public Response exportBids(@PathParam("auction") final int auctionUid,
            @Context final HttpServletRequest request) {
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(final OutputStream os) throws IOException, WebApplicationException {
                try (Writer writer = new BufferedWriter(new OutputStreamWriter(os))) {
                    ServletContext context = request.getServletContext();
                    Injector injector = (Injector) context.getAttribute(Injector.class.getName());

                    ExportService exportService = injector.getInstance(ExportService.class);
                    exportService.exportBids(auctionUid, writer);
                }
            }
        };

        return Response.ok(stream).build();
    }

    @GET
    @Path("/{auction}/bids/total")
    @Produces(MediaType.TEXT_PLAIN)
    public Double sumBids(@PathParam("auction") final int auctionUid) {
        List<Item> items = _dataService.getItemsUpdatesOnly(auctionUid);

        if (items == null) {
            throw new NotFoundException();
        }

        double sum = 0.0;

        for (Item item : items) {
            sum += (item.getCurPrice());
        }

        return sum;
    }

    @GET
    @Path("/{auction}/funds/export")
    @Produces("text/csv")
    public Response exportFunds(@PathParam("auction") final int auctionUid,
            @Context final HttpServletRequest request) {
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(final OutputStream os) throws IOException, WebApplicationException {
                try (Writer writer = new BufferedWriter(new OutputStreamWriter(os))) {
                    ServletContext context = request.getServletContext();
                    Injector injector = (Injector) context.getAttribute(Injector.class.getName());

                    ExportService exportService = injector.getInstance(ExportService.class);
                    exportService.exportFunds(auctionUid, writer);
                }
            }
        };

        return Response.ok(stream).build();
    }

    @GET
    @Path("/{auction}/funds/total")
    @Produces(MediaType.TEXT_PLAIN)
    public Double sumFunds(@PathParam("auction") final int auctionUid) {
        List<User> users = _dataService.getUsers(auctionUid, 0, 9999, null, null);

        if (users == null) {
            throw new NotFoundException();
        }

        double sum = 0.0;
        for (User user : users) {
            List<Fund> funds = _dataService.getFundsByUser(user.getUid());
            for (Fund fund : funds) {
                sum += fund.getBidPrice();
            }
        }

        return sum;
    }
}