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  
22  package org.opencastproject.inspection.ffmpeg.endpoints;
23  
24  import org.opencastproject.inspection.api.MediaInspectionService;
25  import org.opencastproject.inspection.api.util.Options;
26  import org.opencastproject.job.api.JaxbJob;
27  import org.opencastproject.job.api.Job;
28  import org.opencastproject.job.api.JobProducer;
29  import org.opencastproject.mediapackage.MediaPackageElementParser;
30  import org.opencastproject.rest.AbstractJobProducerEndpoint;
31  import org.opencastproject.serviceregistry.api.ServiceRegistry;
32  import org.opencastproject.util.doc.rest.RestParameter;
33  import org.opencastproject.util.doc.rest.RestQuery;
34  import org.opencastproject.util.doc.rest.RestResponse;
35  import org.opencastproject.util.doc.rest.RestService;
36  
37  import org.osgi.service.component.ComponentContext;
38  import org.osgi.service.component.annotations.Activate;
39  import org.osgi.service.component.annotations.Component;
40  import org.osgi.service.component.annotations.Reference;
41  import org.osgi.service.component.annotations.ReferenceCardinality;
42  import org.osgi.service.component.annotations.ReferencePolicy;
43  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
44  import org.slf4j.Logger;
45  import org.slf4j.LoggerFactory;
46  
47  import java.net.URI;
48  
49  import javax.servlet.http.HttpServletResponse;
50  import javax.ws.rs.FormParam;
51  import javax.ws.rs.GET;
52  import javax.ws.rs.POST;
53  import javax.ws.rs.Path;
54  import javax.ws.rs.Produces;
55  import javax.ws.rs.QueryParam;
56  import javax.ws.rs.core.MediaType;
57  import javax.ws.rs.core.Response;
58  
59  /**
60   * A service endpoint to expose the {@link MediaInspectionService} via REST.
61   */
62  @Path("/inspection")
63  @RestService(name = "mediainspection", title = "Media Inspection Service", abstractText = "This service extracts technical metadata from media files.", notes = {
64          "All paths above are relative to the REST endpoint base (something like http://your.server/files)",
65          "If the service is down or not working it will return a status 503, this means the the underlying service is "
66                  + "not working and is either restarting or has failed",
67          "A status code 500 means a general failure has occurred which is not recoverable and was not anticipated. In "
68                  + "other words, there is a bug! You should file an error report with your server logs from the time when the "
69                  + "error occurred: <a href=\"https://github.com/opencast/opencast/issues\">Opencast Issue Tracker</a>" })
70  @Component(
71    property = {
72      "service.description=Media Inspection REST Endpoint",
73      "opencast.service.type=org.opencastproject.inspection",
74      "opencast.service.path=/inspection",
75      "opencast.service.jobproducer=true"
76    },
77    immediate = true,
78    service = { MediaInspectionRestEndpoint.class }
79  )
80  @JaxrsResource
81  public class MediaInspectionRestEndpoint extends AbstractJobProducerEndpoint {
82  
83    /** The logger */
84    private static final Logger logger = LoggerFactory.getLogger(MediaInspectionRestEndpoint.class);
85  
86    /** The inspection service */
87    protected MediaInspectionService service;
88  
89    /** The service registry */
90    protected ServiceRegistry serviceRegistry = null;
91  
92    /**
93     * Callback from the OSGi declarative services to set the service registry.
94     *
95     * @param serviceRegistry
96     *          the service registry
97     */
98    @Reference
99    protected void setServiceRegistry(ServiceRegistry serviceRegistry) {
100     this.serviceRegistry = serviceRegistry;
101   }
102 
103   /**
104    * Sets the inspection service
105    *
106    * @param service
107    *          the inspection service
108    */
109   @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
110   public void setService(MediaInspectionService service) {
111     this.service = service;
112   }
113 
114   /**
115    * Removes the inspection service
116    *
117    * @param service
118    */
119   public void unsetService(MediaInspectionService service) {
120     if (this.service == service) {
121       this.service = null;
122     }
123   }
124 
125   /**
126    * Callback from OSGi that is called when this service is activated.
127    *
128    * @param cc
129    *          OSGi component context
130    */
131   @Activate
132   public void activate(ComponentContext cc) {
133     // String serviceUrl = (String) cc.getProperties().get(RestConstants.SERVICE_PATH_PROPERTY);
134   }
135 
136   @GET
137   @Produces(MediaType.TEXT_XML)
138   @Path("inspect")
139   @RestQuery(name = "inspect", description = "Analyze a given media file",
140     restParameters = {
141         @RestParameter(description = "Location of the media file.", isRequired = false, name = "uri", type = RestParameter.Type.STRING),
142         @RestParameter(description = "Options passed to media inspection service", isRequired = false, name = "options", type = RestParameter.Type.STRING) },
143     responses = {
144         @RestResponse(description = "XML encoded receipt is returned.", responseCode = HttpServletResponse.SC_OK),
145         @RestResponse(description = "Service unavailabe or not currently present", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE),
146         @RestResponse(description = "Problem retrieving media file or invalid media file or URL.", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
147     returnDescription = "Returns a receipt to check on the status and outcome of the job")
148   public Response inspectTrack(@QueryParam("uri") URI uri, @QueryParam("options") String options) {
149     checkNotNull(service);
150     try {
151       Job job = service.inspect(uri, Options.fromJson(options));
152       return Response.ok(new JaxbJob(job)).build();
153     } catch (Exception e) {
154       logger.info("Unable to inspect track {}: {}", uri, e.getMessage());
155       return Response.serverError().build();
156     }
157   }
158 
159   @POST
160   @Produces(MediaType.TEXT_XML)
161   @Path("enrich")
162   @RestQuery(name = "enrich", description = "Analyze and add missing metadata of a given media file",
163     restParameters = {
164         @RestParameter(description = "MediaPackage Element, that should be enriched with metadata ", isRequired = true, name = "mediaPackageElement", type = RestParameter.Type.TEXT),
165         @RestParameter(description = "Should the existing metadata values remain", isRequired = true, name = "override", type = RestParameter.Type.BOOLEAN),
166         @RestParameter(description = "Options passed to media inspection service", isRequired = false, name = "options", type = RestParameter.Type.STRING) },
167     responses = {
168         @RestResponse(description = "XML encoded receipt is returned.", responseCode = HttpServletResponse.SC_OK),
169         @RestResponse(description = "Service unavailabe or not currently present", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE),
170         @RestResponse(description = "Problem retrieving media file or invalid media file or URL.", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) },
171     returnDescription = "Return a receipt to check on the status and outcome of the job")
172   public Response enrichTrack(@FormParam("mediaPackageElement") String mediaPackageElement,
173           @FormParam("override") boolean override, @FormParam("options") String options) {
174     checkNotNull(service);
175     try {
176       Job job = service.enrich(MediaPackageElementParser.getFromXml(mediaPackageElement), override,
177               Options.fromJson(options));
178       return Response.ok(new JaxbJob(job)).build();
179     } catch (Exception e) {
180       logger.info("Unable to enrich track {}: {}", mediaPackageElement, e.getMessage());
181       return Response.serverError().build();
182     }
183   }
184 
185   /**
186    * {@inheritDoc}
187    *
188    * @see org.opencastproject.rest.AbstractJobProducerEndpoint#getService()
189    */
190   @Override
191   public JobProducer getService() {
192     if (service instanceof JobProducer)
193       return (JobProducer) service;
194     else
195       return null;
196   }
197 
198   /**
199    * {@inheritDoc}
200    *
201    * @see org.opencastproject.rest.AbstractJobProducerEndpoint#getServiceRegistry()
202    */
203   @Override
204   public ServiceRegistry getServiceRegistry() {
205     return serviceRegistry;
206   }
207 
208   /**
209    * Checks if the service or services are available, if not it handles it by returning a 503 with a message
210    *
211    * @param services
212    *          an array of services to check
213    */
214   protected void checkNotNull(Object... services) {
215     if (services != null) {
216       for (Object object : services) {
217         if (object == null) {
218           throw new javax.ws.rs.WebApplicationException(javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE);
219         }
220       }
221     }
222   }
223 
224 }