summaryrefslogtreecommitdiffstats
path: root/proxy/code/src/org/fedoraproject/candlepin/resource/EntitlementResource.java
blob: e8de41cb04891c7d1bf07e57ac4bb9db16dd636b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
 * Copyright (c) 2009 Red Hat, Inc.
 *
 * This software is licensed to you under the GNU General Public License,
 * version 2 (GPLv2). There is NO WARRANTY for this software, express or
 * implied, including the implied warranties of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
 * along with this software; if not, see
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
 *
 * Red Hat trademarks are not licensed under GPLv2. No permission is
 * granted to use or replicate Red Hat trademarks that are incorporated
 * in this software or its documentation.
 */
package org.fedoraproject.candlepin.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.fedoraproject.candlepin.model.Consumer;
import org.fedoraproject.candlepin.model.Entitlement;
import org.fedoraproject.candlepin.model.EntitlementPool;
import org.fedoraproject.candlepin.model.ObjectFactory;
import org.fedoraproject.candlepin.model.Product;
import org.fedoraproject.candlepin.resource.cert.CertGenerator;
import org.fedoraproject.candlepin.util.EntityManagerUtil;

import com.sun.jersey.api.representation.Form;


/**
 * REST api gateway for the User object.
 */
@Path("/entitlement")
public class EntitlementResource extends BaseResource {

    /** default ctor */
    public EntitlementResource() {
        super(Entitlement.class);
    }

    /** Logger for this class */
    private static Logger log = Logger.getLogger(EntitlementResource.class);

    private Object validateObjectInput(Form form, String fieldName, Class clazz) {
        String uuid = form.getFirst(fieldName);
        Object o = ObjectFactory.get().lookupByUUID(clazz, uuid);
        if (o == null) {
            throw new RuntimeException(clazz.getName() + " with UUID: [" + 
                    uuid + "] not found");
        }
        return o;
    }
    
    private Object validateObjectInput(String uuid, Class clazz) {
        Object o = ObjectFactory.get().lookupByUUID(clazz, uuid);
        if (o == null) {
            throw new RuntimeException(clazz.getName() + " with UUID: [" + 
                    uuid + "] not found");
        }
        return o;
    }

    private Object newValidateObjectInput(EntityManager em, Long id, Class clazz) {
        Query q = em.createQuery("from " + clazz.getName() + " o where o.id = :id");
        q.setParameter("id", id);
//        if (o == null) {
//            throw new RuntimeException(clazz.getName() + " with UUID: [" + 
//                    uuid + "] not found");
//        }
        Object result = q.getSingleResult();
        return result;
    }

    /**
     * Test method
     * @param c consumer test
     * @return test object
     */
    @POST
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Path("/foo")
    public Object foo(Consumer c) {
        return "return value";
    }

    /**
     * Entitles the given Consumer with the given Product.
     * @param c Consumer to be entitled
     * @param p The Product
     * @return Entitled object
     */
    @POST
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Path("/entitle")
    public Object entitle(Consumer c, Product p) {

        // Possibly refactor this down into some 'business layer'
        // Check for a matching EntitlementPool
        List pools = ObjectFactory.get().listObjectsByClass(EntitlementPool.class);
        for (int i = 0; i < pools.size(); i++) {
            EntitlementPool ep = (EntitlementPool) pools.get(i);
            if (ep.getProduct().equals(p)) {
                log.debug("We found a matching EP");
                // Check membership availability
                if (ep.getCurrentMembers() >= ep.getMaxMembers()) {
                    throw new RuntimeException("Not enough entitlements");
                }
                // Check expiration
                Date today = new Date();
                if (ep.getEndDate().before(today)) {
                    throw new RuntimeException("Entitlement expired on: " +
                        ep.getEndDate());
                }
                
                Entitlement e = new Entitlement();
                e.setPool(ep);
                e.setStartDate(new Date());
                ep.bumpCurrentMembers();
                c.addConsumedProduct(p);
                c.addEntitlement(e);
                e.setOwner(ep.getOwner());
                
                
                ObjectFactory.get().store(e);
                ObjectFactory.get().store(ep);
                
                return CertGenerator.getCertString(); 
            }
        }
        return null;
    }

    /**
     * Check to see if a given Consumer is entitled to given Product
     * @param consumerUuid consumerUuid to check if entitled or not
     * @param productId productUuid to check if entitled or not
     * @return boolean if entitled or not
     */
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Path("/has")
    public boolean hasEntitlement(@PathParam("consumer_uuid") String consumerUuid, 
            @PathParam("product_id") String productId) {
        Consumer c = (Consumer) validateObjectInput(consumerUuid, Consumer.class);
        Product p = (Product) validateObjectInput(productId, Product.class);
        for (Entitlement e : c.getEntitlements()) {
            if (e.getProduct().equals(p)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Match/List the available entitlements for a given Consumer.  Right now
     * this returns ALL entitlements because we haven't built any filtering logic.
     * @param uuid consumerUuid
     * @return List<Entitlement> of applicable 
     */
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Path("/listavailable")
    public List<EntitlementPool> listAvailableEntitlements(
        @PathParam("consumerId") Long consumerId) {
        EntityManager em = EntityManagerUtil.createEntityManager();

        Consumer c = (Consumer) newValidateObjectInput(em, consumerId, Consumer.class);
        List<EntitlementPool> entitlementPools = new EntitlementPoolResource().list();
        List<EntitlementPool> retval = new ArrayList<EntitlementPool>();
        EntitlementMatcher matcher = new EntitlementMatcher();
        for (EntitlementPool ep : entitlementPools) {
            boolean add = false;
            System.out.println("max = " + ep.getMaxMembers());
            System.out.println("cur = " + ep.getCurrentMembers());
            if (ep.getMaxMembers() > ep.getCurrentMembers()) {
                add = true;
            }
            if (matcher.isCompatible(c, ep.getProduct())) {
                add = true;
            }
            if (add) {
                retval.add(ep);
            }
        }
        return retval;
    }

    
    // TODO:
    // EntitlementLib.UnentitleProduct(Consumer, Entitlement) 
    
   
    /**
     * Return list of Entitlements
     * @return list of Entitlements
     */
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Entitlement> list() {
        List<Object> u = ObjectFactory.get().listObjectsByClass(getApiClass());
        List<Entitlement> entitlements = new ArrayList<Entitlement>();
        for (Object o : u) {
            entitlements.add((Entitlement) o);
        }
        return entitlements;
    }

}