1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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(name = "TasksService", title = "UI Tasks",
79 abstractText = "Provides resources and operations related to the tasks",
80 notes = { "All paths above are relative to the REST endpoint base (something like http://your.server/files)",
81 "If the service is down or not working it will return a status 503, this means the the underlying service is "
82 + "not working and is either restarting or has failed",
83 "A status code 500 means a general failure has occurred which is not recoverable and was not anticipated. In "
84 + "other words, there is a bug! You should file an error report with your server logs from the time when the "
85 + "error occurred: <a href=\"https://github.com/opencast/opencast/issues\">Opencast Issue Tracker</a>",
86 "<strong>Important:</strong> "
87 + "<em>This service is for exclusive use by the module admin-ui. Its API might change "
88 + "anytime without prior notice. Any dependencies other than the admin UI will be strictly ignored. "
89 + "DO NOT use this for integration of third-party applications.<em>"})
90 @Component(
91 immediate = true,
92 service = TasksEndpoint.class,
93 property = {
94 "service.description=Admin UI - Tasks facade Endpoint",
95 "opencast.service.type=org.opencastproject.adminui.endpoint.TasksEndpoint",
96 "opencast.service.path=/admin-ng/tasks"
97 }
98 )
99 @JaxrsResource
100 public class TasksEndpoint {
101
102 private static final Logger logger = LoggerFactory.getLogger(TasksEndpoint.class);
103
104 private WorkflowService workflowService;
105
106 private AssetManager assetManager;
107
108
109 @Reference
110 public void setWorkflowService(WorkflowService workflowService) {
111 this.workflowService = workflowService;
112 }
113
114
115 @Reference
116 public void setAssetManager(AssetManager assetManager) {
117 this.assetManager = assetManager;
118 }
119
120 @Activate
121 protected void activate(BundleContext bundleContext) {
122 logger.info("Activate tasks endpoint");
123 }
124
125 @GET
126 @Path("processing.json")
127 @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") })
128 public Response getProcessing(@QueryParam("tags") String tagsString) {
129 List<String> tags = RestUtil.splitCommaSeparatedParam(Optional.ofNullable(tagsString));
130
131 JsonArray actions = new JsonArray();
132 try {
133 List<WorkflowDefinition> workflowDefinitions = workflowService.listAvailableWorkflowDefinitions();
134 for (WorkflowDefinition wflDef : workflowDefinitions) {
135 if (wflDef.containsTag(tags)) {
136 JsonObject action = new JsonObject();
137 action.addProperty("id", wflDef.getId());
138 action.addProperty("title", safeString(wflDef.getTitle()));
139 action.addProperty("description", safeString(wflDef.getDescription()));
140 action.addProperty("configuration_panel", safeString(wflDef.getConfigurationPanel()));
141 action.addProperty("configuration_panel_json", safeString(wflDef.getConfigurationPanelJson()));
142 actions.add(action);
143 }
144 }
145 } catch (WorkflowDatabaseException e) {
146 logger.error("Unable to get available workflow definitions", e);
147 return RestUtil.R.serverError();
148 }
149
150 return okJson(actions);
151 }
152
153 @POST
154 @Path("/new")
155 @RestQuery(
156 name = "createNewTask",
157 description = "Creates a new task by the given metadata as JSON",
158 returnDescription = "The task identifiers",
159 restParameters = {
160 @RestParameter(name = "metadata", isRequired = true,
161 description = "The metadata as JSON.<p>Example:<p>"
162 + "<code><pre>{\n"
163 + " \"workflow\":\"republish-metadata\",\n"
164 + " \"configuration\":{\n"
165 + " \"ID-dual-stream-demo\":{\"workflowVar\":\"true\"},\n"
166 + " \"ID-about-opencast\":{\"workflowVar\":\"true\"}\n"
167 + " }\n"
168 + "}</pre></code>", type = RestParameter.Type.TEXT) },
169 responses = {
170 @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"),
171 @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"),
172 @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
173 public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
174 if (StringUtils.isBlank(metadata)) {
175 logger.warn("No metadata set");
176 return RestUtil.R.badRequest("No metadata set");
177 }
178 Gson gson = new Gson();
179 Map metadataJson;
180 try {
181 metadataJson = gson.fromJson(metadata, Map.class);
182 } catch (Exception e) {
183 logger.warn("Unable to parse metadata {}", metadata);
184 return RestUtil.R.badRequest("Unable to parse metadata");
185 }
186
187 String workflowId = (String) metadataJson.get("workflow");
188 if (StringUtils.isBlank(workflowId))
189 return RestUtil.R.badRequest("No workflow set");
190
191 Map<String, Map<String, String>> configuration = (Map<String, Map<String, String>>) metadataJson.get("configuration");
192 if (configuration == null) {
193 return RestUtil.R.badRequest("No events set");
194 }
195
196 WorkflowDefinition wfd;
197 try {
198 wfd = workflowService.getWorkflowDefinitionById(workflowId);
199 } catch (WorkflowDatabaseException e) {
200 logger.error("Unable to get workflow definition {}", workflowId, e);
201 return RestUtil.R.serverError();
202 }
203
204 final Workflows workflows = new Workflows(assetManager, workflowService);
205 final List<WorkflowInstance> instances = new ArrayList<>();
206 for (final Entry<String, Map<String, String>> entry : configuration.entrySet()) {
207 final ConfiguredWorkflow workflow = workflow(wfd, entry.getValue());
208 final Set<String> mpIds = Collections.singleton(entry.getKey());
209 final List<WorkflowInstance> partialResult = workflows.applyWorkflowToLatestVersion(mpIds, workflow);
210
211 if (partialResult.size() != 1) {
212 logger.warn("Couldn't start workflow for media package {}", entry.getKey());
213 return Response.status(Status.BAD_REQUEST).build();
214 }
215
216 instances.addAll(partialResult);
217 }
218 return Response.status(Status.CREATED)
219 .entity(gson.toJson(instances.stream().map(getWorkflowIds).collect(Collectors.toList())))
220 .build();
221 }
222
223 private static final Function<WorkflowInstance, Long> getWorkflowIds = a -> a.getId();
224
225 }