View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  package org.opencastproject.external.endpoint;
22  
23  import org.opencastproject.external.common.ApiMediaType;
24  import org.opencastproject.external.common.ApiResponseBuilder;
25  import org.opencastproject.list.api.ListProviderException;
26  import org.opencastproject.list.api.ListProvidersService;
27  import org.opencastproject.list.impl.ListProviderNotFoundException;
28  import org.opencastproject.list.impl.ResourceListQueryImpl;
29  import org.opencastproject.list.query.StringListFilter;
30  import org.opencastproject.util.doc.rest.RestParameter;
31  import org.opencastproject.util.doc.rest.RestQuery;
32  import org.opencastproject.util.doc.rest.RestResponse;
33  import org.opencastproject.util.doc.rest.RestService;
34  
35  import com.google.gson.Gson;
36  
37  import org.json.simple.JSONArray;
38  import org.osgi.service.component.ComponentContext;
39  import org.osgi.service.component.annotations.Activate;
40  import org.osgi.service.component.annotations.Component;
41  import org.osgi.service.component.annotations.Reference;
42  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  import java.util.Map;
47  
48  import javax.servlet.http.HttpServletResponse;
49  import javax.ws.rs.GET;
50  import javax.ws.rs.HeaderParam;
51  import javax.ws.rs.Path;
52  import javax.ws.rs.PathParam;
53  import javax.ws.rs.Produces;
54  import javax.ws.rs.QueryParam;
55  import javax.ws.rs.core.Response;
56  
57  @Path("/api/listproviders")
58  @Produces({ ApiMediaType.JSON, ApiMediaType.VERSION_1_10_0, ApiMediaType.VERSION_1_11_0 })
59  @RestService(
60          name = "externalapilistproviders",
61          title = "External API List Providers Service",
62          notes = {},
63          abstractText = "Provides resources and operations related to configurable lists"
64  )
65  @Component(
66          immediate = true,
67          service = ListProviderEndpoint.class,
68          property = {
69                  "service.description=External API - List Providers Endpoint",
70                  "opencast.service.type=org.opencastproject.external.listproviders",
71                  "opencast.service.path=/api/listproviders"
72          }
73  )
74  @JaxrsResource
75  public class ListProviderEndpoint {
76  
77    /** The logging facility */
78    private static final Logger logger = LoggerFactory.getLogger(ListProviderEndpoint.class);
79  
80    /** The capture agent service */
81    private ListProvidersService listProvidersService;
82  
83    /** OSGi DI */
84    @Reference
85    public void setListProvidersService(ListProvidersService listProvidersService) {
86      this.listProvidersService = listProvidersService;
87    }
88  
89    /** OSGi activation method */
90    @Activate
91    void activate(ComponentContext cc) {
92      logger.info("Activating External API - List Providers Endpoint");
93    }
94  
95    @GET
96    @Path("providers.json")
97    @Produces({ ApiMediaType.JSON, ApiMediaType.VERSION_1_10_0 })
98    @RestQuery(
99        name = "availableProviders",
100       description = "Provides the list of the available list providers",
101       responses = {
102           @RestResponse(description = "Returns the availables list providers.",
103               responseCode = HttpServletResponse.SC_OK)
104       },
105       returnDescription = "")
106   public Response getAvailableProviders(@HeaderParam("Accept") String acceptHeader) {
107     JSONArray list = new JSONArray();
108 
109     list.add(listProvidersService.getAvailableProviders());
110 
111     return ApiResponseBuilder.Json.ok(acceptHeader, list.toJSONString());
112   }
113 
114   @GET
115   @Path("{source}.json")
116   @Produces({ ApiMediaType.JSON, ApiMediaType.VERSION_1_10_0 })
117   @RestQuery(
118       name = "list",
119       description = "Provides key-value list from the given source",
120       pathParameters = {
121           @RestParameter(name = "source", description = "The source for the key-value list", isRequired = true,
122               type = RestParameter.Type.STRING)
123       },
124       restParameters = {
125           @RestParameter(description = "The maximum number of items to return per page", isRequired = false,
126               name = "limit", type = RestParameter.Type.INTEGER),
127           @RestParameter(description = "The offset", isRequired = false, name = "offset",
128               type = RestParameter.Type.INTEGER),
129           @RestParameter(description = "Filters", isRequired = false, name = "filter",
130               type = RestParameter.Type.STRING)
131       },
132       responses = {
133           @RestResponse(description = "Returns the key-value list for the given source.",
134               responseCode = HttpServletResponse.SC_OK)
135       },
136       returnDescription = "")
137   public Response getList(@PathParam("source") final String source, @QueryParam("limit") final int limit,
138           @QueryParam("filter") final String filter, @QueryParam("offset") final int offset,
139           @HeaderParam("Accept") String acceptHeader) {
140 
141     ResourceListQueryImpl query = new ResourceListQueryImpl();
142     query.setLimit(limit);
143     query.setOffset(offset);
144     addRequestFiltersToQuery(filter, query);
145     Map<String, String> autocompleteList;
146     try {
147       autocompleteList = listProvidersService.getList(source, query, false);
148     } catch (ListProviderNotFoundException e) {
149       logger.debug("No list found for {}", source, e);
150       return ApiResponseBuilder.notFound("");
151     } catch (ListProviderException e) {
152       logger.error("Server error when getting list from provider {}", source, e);
153       return ApiResponseBuilder.serverError("");
154     }
155 
156     Gson gson = new Gson();
157     String jsonList = gson.toJson(autocompleteList);
158     return ApiResponseBuilder.Json.ok(acceptHeader, jsonList);
159   }
160 
161   /**
162    * Add the string based filters to the given list query.
163    *
164    * @param filterString
165    *          The string based filters
166    * @param query
167    *          The query to update with the filters
168    */
169   private void addRequestFiltersToQuery(final String filterString, ResourceListQueryImpl query) {
170     if (filterString != null) {
171       String[] filters = filterString.split(",");
172       for (String filter : filters) {
173         String[] splitFilter = filter.split(":", 2);
174         if (splitFilter != null && splitFilter.length == 2) {
175           String key = splitFilter[0].trim();
176           String value = splitFilter[1].trim();
177           query.addFilter(new StringListFilter(key, value));
178         }
179       }
180     }
181   }
182 
183 }
184