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.adminui.endpoint;
23  
24  import static com.entwinemedia.fn.Stream.$;
25  import static com.entwinemedia.fn.data.Opt.nul;
26  import static com.entwinemedia.fn.data.json.Jsons.arr;
27  import static com.entwinemedia.fn.data.json.Jsons.f;
28  import static com.entwinemedia.fn.data.json.Jsons.obj;
29  import static com.entwinemedia.fn.data.json.Jsons.v;
30  import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
31  import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
32  import static javax.servlet.http.HttpServletResponse.SC_OK;
33  import static org.opencastproject.index.service.util.RestUtils.okJson;
34  import static org.opencastproject.workflow.api.ConfiguredWorkflow.workflow;
35  
36  import org.opencastproject.assetmanager.api.AssetManager;
37  import org.opencastproject.assetmanager.util.Workflows;
38  import org.opencastproject.util.NotFoundException;
39  import org.opencastproject.util.RestUtil;
40  import org.opencastproject.util.data.Option;
41  import org.opencastproject.util.doc.rest.RestParameter;
42  import org.opencastproject.util.doc.rest.RestQuery;
43  import org.opencastproject.util.doc.rest.RestResponse;
44  import org.opencastproject.util.doc.rest.RestService;
45  import org.opencastproject.workflow.api.ConfiguredWorkflow;
46  import org.opencastproject.workflow.api.WorkflowDatabaseException;
47  import org.opencastproject.workflow.api.WorkflowDefinition;
48  import org.opencastproject.workflow.api.WorkflowInstance;
49  import org.opencastproject.workflow.api.WorkflowService;
50  
51  import com.entwinemedia.fn.Fn;
52  import com.entwinemedia.fn.data.json.JValue;
53  import com.google.gson.Gson;
54  
55  import org.apache.commons.lang3.StringUtils;
56  import org.osgi.framework.BundleContext;
57  import org.osgi.service.component.annotations.Activate;
58  import org.osgi.service.component.annotations.Component;
59  import org.osgi.service.component.annotations.Reference;
60  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
61  import org.slf4j.Logger;
62  import org.slf4j.LoggerFactory;
63  
64  import java.util.ArrayList;
65  import java.util.Collections;
66  import java.util.List;
67  import java.util.Map;
68  import java.util.Map.Entry;
69  import java.util.Set;
70  
71  import javax.servlet.http.HttpServletResponse;
72  import javax.ws.rs.FormParam;
73  import javax.ws.rs.GET;
74  import javax.ws.rs.POST;
75  import javax.ws.rs.Path;
76  import javax.ws.rs.QueryParam;
77  import javax.ws.rs.core.Response;
78  import javax.ws.rs.core.Response.Status;
79  
80  @Path("/admin-ng/tasks")
81  @RestService(name = "TasksService", title = "UI Tasks",
82    abstractText = "Provides resources and operations related to the tasks",
83    notes = { "All paths above are relative to the REST endpoint base (something like http://your.server/files)",
84              "If the service is down or not working it will return a status 503, this means the the underlying service is "
85                + "not working and is either restarting or has failed",
86              "A status code 500 means a general failure has occurred which is not recoverable and was not anticipated. In "
87                + "other words, there is a bug! You should file an error report with your server logs from the time when the "
88                + "error occurred: <a href=\"https://github.com/opencast/opencast/issues\">Opencast Issue Tracker</a>",
89              "<strong>Important:</strong> "
90                + "<em>This service is for exclusive use by the module admin-ui. Its API might change "
91                + "anytime without prior notice. Any dependencies other than the admin UI will be strictly ignored. "
92                + "DO NOT use this for integration of third-party applications.<em>"})
93  @Component(
94    immediate = true,
95    service = TasksEndpoint.class,
96    property = {
97      "service.description=Admin UI - Tasks facade Endpoint",
98      "opencast.service.type=org.opencastproject.adminui.endpoint.TasksEndpoint",
99      "opencast.service.path=/admin-ng/tasks"
100   }
101 )
102 @JaxrsResource
103 public class TasksEndpoint {
104 
105   private static final Logger logger = LoggerFactory.getLogger(TasksEndpoint.class);
106 
107   private WorkflowService workflowService;
108 
109   private AssetManager assetManager;
110 
111   /** OSGi callback for the workflow service. */
112   @Reference
113   public void setWorkflowService(WorkflowService workflowService) {
114     this.workflowService = workflowService;
115   }
116 
117   /** OSGi callback to set the asset manager. */
118   @Reference
119   public void setAssetManager(AssetManager assetManager) {
120     this.assetManager = assetManager;
121   }
122 
123   @Activate
124   protected void activate(BundleContext bundleContext) {
125     logger.info("Activate tasks endpoint");
126   }
127 
128   @GET
129   @Path("processing.json")
130   @RestQuery(name = "getProcessing", description = "Returns all the data related to the processing tab in the new tasks modal as JSON", returnDescription = "All the data related to the tasks processing tab as JSON", restParameters = { @RestParameter(name = "tags", isRequired = false, description = "A comma separated list of tags to filter the workflow definitions", type = RestParameter.Type.STRING) }, responses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the tasks processing tab as JSON") })
131   public Response getProcessing(@QueryParam("tags") String tagsString) {
132     List<String> tags = RestUtil.splitCommaSeparatedParam(Option.option(tagsString)).value();
133 
134     // This is the JSON Object which will be returned by this request
135     List<JValue> actions = new ArrayList<>();
136     try {
137       List<WorkflowDefinition> workflowsDefinitions = workflowService.listAvailableWorkflowDefinitions();
138       for (WorkflowDefinition wflDef : workflowsDefinitions) {
139         if (wflDef.containsTag(tags)) {
140           actions.add(obj(f("id", v(wflDef.getId())), f("title", v(nul(wflDef.getTitle()).getOr(""))),
141                   f("description", v(nul(wflDef.getDescription()).getOr(""))),
142                   f("configuration_panel", v(nul(wflDef.getConfigurationPanel()).getOr(""))),
143                   f("configuration_panel_json", v(nul(wflDef.getConfigurationPanelJson()).getOr("")))));
144         }
145       }
146     } catch (WorkflowDatabaseException e) {
147       logger.error("Unable to get available workflow definitions", e);
148       return RestUtil.R.serverError();
149     }
150 
151     return okJson(arr(actions));
152   }
153 
154   @POST
155   @Path("/new")
156   @RestQuery(
157       name = "createNewTask",
158       description = "Creates a new task by the given metadata as JSON",
159       returnDescription = "The task identifiers",
160       restParameters = {
161           @RestParameter(name = "metadata", isRequired = true,
162               description = "The metadata as JSON.<p>Example:<p>"
163                   + "<code><pre>{\n"
164                   + "  \"workflow\":\"republish-metadata\",\n"
165                   + "  \"configuration\":{\n"
166                   + "    \"ID-dual-stream-demo\":{\"workflowVar\":\"true\"},\n"
167                   + "    \"ID-about-opencast\":{\"workflowVar\":\"true\"}\n"
168                   + "  }\n"
169                   + "}</pre></code>", type = RestParameter.Type.TEXT) },
170       responses = {
171           @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"),
172           @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"),
173           @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
174   public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
175     if (StringUtils.isBlank(metadata)) {
176       logger.warn("No metadata set");
177       return RestUtil.R.badRequest("No metadata set");
178     }
179     Gson gson = new Gson();
180     Map metadataJson;
181     try {
182       metadataJson = gson.fromJson(metadata, Map.class);
183     } catch (Exception e) {
184       logger.warn("Unable to parse metadata {}", metadata);
185       return RestUtil.R.badRequest("Unable to parse metadata");
186     }
187 
188     String workflowId = (String) metadataJson.get("workflow");
189     if (StringUtils.isBlank(workflowId))
190       return RestUtil.R.badRequest("No workflow set");
191 
192     Map<String, Map<String, String>> configuration = (Map<String, Map<String, String>>) metadataJson.get("configuration");
193     if (configuration == null) {
194       return RestUtil.R.badRequest("No events set");
195     }
196 
197     WorkflowDefinition wfd;
198     try {
199       wfd = workflowService.getWorkflowDefinitionById(workflowId);
200     } catch (WorkflowDatabaseException e) {
201       logger.error("Unable to get workflow definition {}", workflowId, e);
202       return RestUtil.R.serverError();
203     }
204 
205     final Workflows workflows = new Workflows(assetManager, workflowService);
206     final List<WorkflowInstance> instances = new ArrayList<>();
207     for (final Entry<String, Map<String, String>> entry : configuration.entrySet()) {
208       final ConfiguredWorkflow workflow = workflow(wfd, entry.getValue());
209       final Set<String> mpIds = Collections.singleton(entry.getKey());
210       final List<WorkflowInstance> partialResult = workflows.applyWorkflowToLatestVersion(mpIds, workflow);
211 
212       if (partialResult.size() != 1) {
213         logger.warn("Couldn't start workflow for media package {}", entry.getKey());
214         return Response.status(Status.BAD_REQUEST).build();
215       }
216 
217       instances.addAll(partialResult);
218     }
219     return Response.status(Status.CREATED).entity(gson.toJson($(instances).map(getWorkflowIds).toList())).build();
220   }
221 
222   private static final Fn<WorkflowInstance, Long> getWorkflowIds = new Fn<WorkflowInstance, Long>() {
223     @Override
224     public Long apply(WorkflowInstance a) {
225       return a.getId();
226     }
227   };
228 
229 }