|
| 1 | +package com.cacoo.apisample.cacoo.servlet; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +import javax.servlet.ServletException; |
| 8 | +import javax.servlet.http.HttpServlet; |
| 9 | +import javax.servlet.http.HttpServletRequest; |
| 10 | +import javax.servlet.http.HttpServletResponse; |
| 11 | + |
| 12 | +import org.apache.http.HttpResponse; |
| 13 | + |
| 14 | +import com.cacoo.apisample.cacoo.CacooUtils; |
| 15 | +import com.google.gson.JsonElement; |
| 16 | +import com.google.gson.JsonObject; |
| 17 | + |
| 18 | +/* |
| 19 | + * Edit diagram (Automatically add image from URL) |
| 20 | + * https://cacoo.com/api_editor_token |
| 21 | + * https://cacoo.com/api_editor_automation |
| 22 | + */ |
| 23 | +public class CacooEditorServlet extends HttpServlet { |
| 24 | + private static final long serialVersionUID = 1L; |
| 25 | + |
| 26 | + @Override |
| 27 | + protected void doGet(HttpServletRequest req, HttpServletResponse resp) |
| 28 | + throws ServletException, IOException { |
| 29 | + String diagramId = req.getParameter("diagramId"); |
| 30 | + try{ |
| 31 | + HttpResponse res; |
| 32 | + JsonElement json; |
| 33 | + JsonObject root; |
| 34 | + |
| 35 | + // step-1 : get authentication token to open editing page |
| 36 | + res = CacooUtils.cacooApi(req, resp, "api/v1/diagrams/"+diagramId+"/editor/token.json", null); |
| 37 | + if(res==null){ |
| 38 | + // OAuth authentication is required. |
| 39 | + return; |
| 40 | + } |
| 41 | + json = CacooUtils.httpResponse2json(res); |
| 42 | + root = json.getAsJsonObject(); |
| 43 | + String editorToken = root.get("token").getAsString(); |
| 44 | + |
| 45 | + // step-2 : register automation command and get token |
| 46 | + Map<String,String> params = new HashMap<String, String>(); |
| 47 | + |
| 48 | + // FIXME Replace URL that you want to insert image. |
| 49 | + String imageUrl = "http://www.nulab.co.jp/"; |
| 50 | + |
| 51 | + params.put("command", "{\"operations\":[{\"type\":\"AddImageUrl\",\"parameter\":{\"url\":\""+imageUrl+"\",\"x\":10,\"y\":10}}]}"); |
| 52 | + res = CacooUtils.cacooApi(req, resp, "api/v1/diagrams/"+diagramId+"/editor/automation.json", params); |
| 53 | + if(res==null){ |
| 54 | + // OAuth authentication is required. |
| 55 | + return; |
| 56 | + } |
| 57 | + json = CacooUtils.httpResponse2json(res); |
| 58 | + root = json.getAsJsonObject(); |
| 59 | + String automationToken = root.get("token").getAsString(); |
| 60 | + |
| 61 | + // step-3 : redirect to editing page. |
| 62 | + resp.sendRedirect(CacooUtils.editorLink(diagramId, editorToken, automationToken, req)); |
| 63 | + }catch (Exception e) { |
| 64 | + e.printStackTrace(); |
| 65 | + req.setAttribute("message", e.getMessage()); |
| 66 | + req |
| 67 | + .getRequestDispatcher("/WEB-INF/jsp/cacoo/error.jsp") |
| 68 | + .forward(req, resp); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments