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.DefaultResourceListQuery;
26  import org.opencastproject.list.api.ListProviderException;
27  import org.opencastproject.list.api.ListProviderNotFoundException;
28  import org.opencastproject.list.api.ListProvidersService;
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    @RestQuery(
98        name = "availableProviders",
99        description = "Provides the list of the available list providers",
100       responses = {
101           @RestResponse(description = "Returns the availables list providers.",
102               responseCode = HttpServletResponse.SC_OK)
103       },
104       returnDescription = "")
105   public Response getAvailableProviders(@HeaderParam("Accept") String acceptHeader) {
106     JSONArray list = new JSONArray();
107 
108     list.add(listProvidersService.getAvailableProviders());
109 
110     return ApiResponseBuilder.Json.ok(acceptHeader, list.toJSONString());
111   }
112 
113   @GET
114   @Path("{source}.json")
115   @RestQuery(
116       name = "list",
117       description = "Provides key-value list from the given source",
118       pathParameters = {
119           @RestParameter(name = "source", description = "The source for the key-value list", isRequired = true,
120               type = RestParameter.Type.STRING)
121       },
122       restParameters = {
123           @RestParameter(description = "The maximum number of items to return per page", isRequired = false,
124               name = "limit", type = RestParameter.Type.INTEGER),
125           @RestParameter(description = "The offset", isRequired = false, name = "offset",
126               type = RestParameter.Type.INTEGER),
127           @RestParameter(description = "Filters", isRequired = false, name = "filter",
128               type = RestParameter.Type.STRING)
129       },
130       responses = {
131           @RestResponse(description = "Returns the key-value list for the given source.",
132               responseCode = HttpServletResponse.SC_OK)
133       },
134       returnDescription = "")
135   public Response getList(@PathParam("source") final String source, @QueryParam("limit") final int limit,
136           @QueryParam("filter") final String filter, @QueryParam("offset") final int offset,
137           @HeaderParam("Accept") String acceptHeader) {
138 
139     DefaultResourceListQuery query = new DefaultResourceListQuery();
140     query.setLimit(limit);
141     query.setOffset(offset);
142     addRequestFiltersToQuery(filter, query);
143     Map<String, String> autocompleteList;
144     try {
145       autocompleteList = listProvidersService.getList(source, query, false);
146     } catch (ListProviderNotFoundException e) {
147       logger.debug("No list found for {}", source, e);
148       return ApiResponseBuilder.notFound("");
149     } catch (ListProviderException e) {
150       logger.error("Server error when getting list from provider {}", source, e);
151       return ApiResponseBuilder.serverError("");
152     }
153 
154     Gson gson = new Gson();
155     String jsonList = gson.toJson(autocompleteList);
156     return ApiResponseBuilder.Json.ok(acceptHeader, jsonList);
157   }
158 
159   /**
160    * Add the string based filters to the given list query.
161    *
162    * @param filterString
163    *          The string based filters
164    * @param query
165    *          The query to update with the filters
166    */
167   private void addRequestFiltersToQuery(final String filterString, DefaultResourceListQuery query) {
168     if (filterString != null) {
169       String[] filters = filterString.split(",");
170       for (String filter : filters) {
171         String[] splitFilter = filter.split(":", 2);
172         if (splitFilter != null && splitFilter.length == 2) {
173           String key = splitFilter[0].trim();
174           String value = splitFilter[1].trim();
175           query.addFilter(new StringListFilter(key, value));
176         }
177       }
178     }
179   }
180 
181 }
182