]> git.somenet.org - pub/jan/aic18.git/blob - camunda-overlay/camunda.py
Merge branch '41-rename-term-to-terms-for-camunda-py' into 'master'
[pub/jan/aic18.git] / camunda-overlay / camunda.py
1 #!/usr/bin/env python3
2
3 import sys
4 import os
5 import json
6 import requests
7 import argparse
8 from pprint import pprint
9
10 CAMUNDA="http://localhost:8080/engine-rest/"
11
12 def get_current_deployments(key = 'sentiment-analysis'):
13     res = requests.get(CAMUNDA + "deployment")
14     #return [proc for proc in res.json() if proc['name'] == key]
15     return res.json()
16
17 def get_current_process_instances(key = 'sentiment-analysis'):
18     res = requests.get(CAMUNDA + 'process-instance')
19     if (key is None):
20         return res.json()
21     else:
22         return [instance for instance in res.json() if instance['definitionId'].startswith(key + ":")]
23
24 def cleanup_old_deployments(key='sentiment-analysis'):
25     print ("Cleaning up old deployments")
26     for deployment in get_current_deployments(key):
27         res = requests.delete(CAMUNDA + "deployment/" + deployment['id'] + "?cascade=true&skipCustomListeners=true")
28         if (res.status_code == 204):
29             print ("Cleaned up deployment {}".format(deployment['id']))
30         else:
31             print ("Error cleaning old deployment {}: Code: {}".format(deployment['id'], res.status_code))
32             try:
33                 pprint(res.json())
34             except:
35                 pprint(res.content)
36
37 def get_users():
38     res = requests.get(CAMUNDA + "user")
39     return res.json()
40
41 def cleanup_users(keep = ["demo"]):
42     for user in get_users():
43         # keep user "demo"
44         if user['id'] in keep:
45             continue
46
47         res = requests.delete(CAMUNDA + "user/" + user['id'])
48         if (res.status_code == 204):
49             print ("Cleaned up user {}".format(user['id']))
50         else:
51             print ("Error cleaning user {}: Code: {}".format(user['id'], res.status_code))
52             try:
53                 pprint(res.json())
54             except:
55                 pprint(res.content)
56
57 def create_deployment(cleanup=False):
58     parameters = [
59             ("deployment-name", "sentiment-analysis"),
60             #("enable-duplicate-filtering", "true"),
61             #("deploy-changed-only", "true"),
62             ("file1", open("sentiment-analysis.bpmn")),
63             ("file2", open("forms/input-terms.html")),
64             ("file3", open("forms/download-pdf.html")),
65             ]
66     if cleanup:
67         cleanup_old_deployments()
68     res = requests.post(CAMUNDA + "deployment/create", files=parameters)
69     if (res.status_code == 200):
70         print ("Successfully deployed Sentiment Analysis")
71     else:
72         pprint ("Status Code: {}".format(res.status_code))
73         try:
74             pprint(res.json())
75         except:
76             pprint(res.content)
77
78 def submit_terms(terms):
79     termlist = [{'term': term} for term in terms]
80     # submit to camunda
81     params = {
82             'variables': {
83                 'terms': {
84                     'value': json.dumps(termlist),
85                     'type': "json",
86                     'valueInfo': {
87                         'serializationDataFormat': "application/json",
88                         }
89                     }
90                 }
91             }
92     res = requests.post(CAMUNDA + "process-definition/key/sentiment-analysis/start", json=params)
93     if (res.status_code == 200):
94         print ("Successfully started Sentiment Analysis")
95     else:
96         pprint ("Status Code: {}".format(res.status_code))
97         try:
98             pprint(res.json())
99         except:
100             try:
101                 import xml.dom.minidom
102                 content = res.content.decode('utf-8').replace('<!doctype html>', '')
103                 print(xml.dom.minidom.parseString(content).toprettyxml())
104             except:
105                 pprint(res.content)
106
107 def download_pdf():
108     instances = get_current_process_instances()
109     if len(instances) == 0:
110         print ("Error: no running instance found.")
111         return
112     instance = instances[0]['id']
113     res = requests.get(CAMUNDA + 'process-instance/' + instance + '/variables')
114     try:
115         pprint(res.json())
116     except:
117         pprint(res.content)
118
119 if __name__ == "__main__":
120     parser = argparse.ArgumentParser()
121     parser.add_argument('--no-deploy', dest='deploy', default=True, action='store_false', help="Do not run the deployment step")
122     parser.add_argument('--no-cleanup', dest='cleanup', default=True, action='store_false', help="Initial deploy does not need cleanup")
123     parser.add_argument('--autoclick', dest='autoclick', type=int, default=0, help="How many steps to autoclick")
124     parser.add_argument('--terms', dest='terms', type=str, nargs='*', default=["aic", "TU Wien"], help="How many steps to autoclick")
125     args = parser.parse_args()
126
127     if args.deploy:
128         # initialize camunda process
129         create_deployment(cleanup=args.cleanup)
130         if args.cleanup:
131             cleanup_users()
132
133     if args.autoclick >= 1:
134         # start clicking
135         submit_terms(args.terms)
136
137     if args.autoclick >= 2:
138         download_pdf()