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 javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
25  import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
26  import static javax.servlet.http.HttpServletResponse.SC_OK;
27  import static org.opencastproject.index.service.util.JSONUtils.safeString;
28  import static org.opencastproject.index.service.util.RestUtils.okJson;
29  import static org.opencastproject.workflow.api.ConfiguredWorkflow.workflow;
30  
31  import org.opencastproject.assetmanager.api.AssetManager;
32  import org.opencastproject.assetmanager.util.Workflows;
33  import org.opencastproject.util.NotFoundException;
34  import org.opencastproject.util.RestUtil;
35  import org.opencastproject.util.doc.rest.RestParameter;
36  import org.opencastproject.util.doc.rest.RestQuery;
37  import org.opencastproject.util.doc.rest.RestResponse;
38  import org.opencastproject.util.doc.rest.RestService;
39  import org.opencastproject.workflow.api.ConfiguredWorkflow;
40  import org.opencastproject.workflow.api.WorkflowDatabaseException;
41  import org.opencastproject.workflow.api.WorkflowDefinition;
42  import org.opencastproject.workflow.api.WorkflowInstance;
43  import org.opencastproject.workflow.api.WorkflowService;
44  
45  import com.google.gson.Gson;
46  import com.google.gson.JsonArray;
47  import com.google.gson.JsonObject;
48  
49  import org.apache.commons.lang3.StringUtils;
50  import org.osgi.framework.BundleContext;
51  import org.osgi.service.component.annotations.Activate;
52  import org.osgi.service.component.annotations.Component;
53  import org.osgi.service.component.annotations.Reference;
54  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  import java.util.ArrayList;
59  import java.util.Collections;
60  import java.util.List;
61  import java.util.Map;
62  import java.util.Map.Entry;
63  import java.util.Optional;
64  import java.util.Set;
65  import java.util.function.Function;
66  import java.util.stream.Collectors;
67  
68  import javax.servlet.http.HttpServletResponse;
69  import javax.ws.rs.FormParam;
70  import javax.ws.rs.GET;
71  import javax.ws.rs.POST;
72  import javax.ws.rs.Path;
73  import javax.ws.rs.QueryParam;
74  import javax.ws.rs.core.Response;
75  import javax.ws.rs.core.Response.Status;
76  
77  @Path("/admin-ng/tasks")
78  @RestService(
79      name = "TasksService",
80      title = "UI Tasks",
81      abstractText = "Provides resources and operations related to the tasks",
82      notes = { "All paths above are relative to the REST endpoint base (something like http://your.server/files)",
83                "If the service is down or not working it will return a status 503, this means the the underlying "
84                    + "service is not working and is either restarting or has failed",
85                "A status code 500 means a general failure has occurred which is not recoverable and was not "
86                    + "anticipated. In other words, there is a bug! You should file an error report with your server "
87                    + "logs from the time when the error occurred: "
88                    + "<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(
131       name = "getProcessing",
132       description = "Returns all the data related to the processing tab in the new tasks modal as JSON",
133       returnDescription = "All the data related to the tasks processing tab as JSON",
134       restParameters = {
135           @RestParameter(name = "tags", isRequired = false, description = "A comma separated list of tags to filter "
136               + "the workflow definitions", type = RestParameter.Type.STRING)
137       },
138       responses = {
139           @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the tasks processing tab "
140               + "as JSON")
141       })
142   public Response getProcessing(@QueryParam("tags") String tagsString) {
143     List<String> tags = RestUtil.splitCommaSeparatedParam(Optional.ofNullable(tagsString));
144 
145     JsonArray actions = new JsonArray();
146     try {
147       List<WorkflowDefinition> workflowDefinitions = workflowService.listAvailableWorkflowDefinitions();
148       for (WorkflowDefinition wflDef : workflowDefinitions) {
149         if (wflDef.containsTag(tags)) {
150           JsonObject action = new JsonObject();
151           action.addProperty("id", wflDef.getId());
152           action.addProperty("title", safeString(wflDef.getTitle()));
153           action.addProperty("description", safeString(wflDef.getDescription()));
154           action.addProperty("configuration_panel", safeString(wflDef.getConfigurationPanel()));
155           action.addProperty("configuration_panel_json", safeString(wflDef.getConfigurationPanelJson()));
156           actions.add(action);
157         }
158       }
159     } catch (WorkflowDatabaseException e) {
160       logger.error("Unable to get available workflow definitions", e);
161       return RestUtil.R.serverError();
162     }
163 
164     return okJson(actions);
165   }
166 
167   @POST
168   @Path("/new")
169   @RestQuery(
170       name = "createNewTask",
171       description = "Creates a new task by the given metadata as JSON",
172       returnDescription = "The task identifiers",
173       restParameters = {
174           @RestParameter(name = "metadata", isRequired = true,
175               description = "The metadata as JSON.<p>Example:<p>"
176                   + "<code><pre>{\n"
177                   + "  \"workflow\":\"republish-metadata\",\n"
178                   + "  \"configuration\":{\n"
179                   + "    \"ID-dual-stream-demo\":{\"workflowVar\":\"true\"},\n"
180                   + "    \"ID-about-opencast\":{\"workflowVar\":\"true\"}\n"
181                   + "  }\n"
182                   + "}</pre></code>", type = RestParameter.Type.TEXT)
183       },
184       responses = {
185           @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"),
186           @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"),
187           @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed")
188       })
189   public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
190     if (StringUtils.isBlank(metadata)) {
191       logger.warn("No metadata set");
192       return RestUtil.R.badRequest("No metadata set");
193     }
194     Gson gson = new Gson();
195     Map metadataJson;
196     try {
197       metadataJson = gson.fromJson(metadata, Map.class);
198     } catch (Exception e) {
199       logger.warn("Unable to parse metadata {}", metadata);
200       return RestUtil.R.badRequest("Unable to parse metadata");
201     }
202 
203     String workflowId = (String) metadataJson.get("workflow");
204     if (StringUtils.isBlank(workflowId)) {
205       return RestUtil.R.badRequest("No workflow set");
206     }
207 
208     Map<String, Map<String, String>> configuration = (Map<String, Map<String, String>>) metadataJson
209         .get("configuration");
210     if (configuration == null) {
211       return RestUtil.R.badRequest("No events set");
212     }
213 
214     WorkflowDefinition wfd;
215     try {
216       wfd = workflowService.getWorkflowDefinitionById(workflowId);
217     } catch (WorkflowDatabaseException e) {
218       logger.error("Unable to get workflow definition {}", workflowId, e);
219       return RestUtil.R.serverError();
220     }
221 
222     final Workflows workflows = new Workflows(assetManager, workflowService);
223     final List<WorkflowInstance> instances = new ArrayList<>();
224     for (final Entry<String, Map<String, String>> entry : configuration.entrySet()) {
225       final ConfiguredWorkflow workflow = workflow(wfd, entry.getValue());
226       final Set<String> mpIds = Collections.singleton(entry.getKey());
227       final List<WorkflowInstance> partialResult = workflows.applyWorkflowToLatestVersion(mpIds, workflow);
228 
229       if (partialResult.size() != 1) {
230         logger.warn("Couldn't start workflow for media package {}", entry.getKey());
231         return Response.status(Status.BAD_REQUEST).build();
232       }
233 
234       instances.addAll(partialResult);
235     }
236     return Response.status(Status.CREATED)
237         .entity(gson.toJson(instances.stream().map(getWorkflowIds).collect(Collectors.toList())))
238         .build();
239   }
240 
241   private static final Function<WorkflowInstance, Long> getWorkflowIds = a -> a.getId();
242 
243 }