forked from Bonitasoft-Community/page_ping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActions.groovy
378 lines (300 loc) · 16.7 KB
/
Actions.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.logging.Logger;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.Runtime;
import org.json.simple.JSONObject;
import org.codehaus.groovy.tools.shell.CommandAlias;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.sql.DataSource;
import java.sql.DatabaseMetaData;
import java.sql.Clob;
import java.util.Date;
import org.apache.commons.lang3.StringEscapeUtils
import org.bonitasoft.engine.identity.User;
import org.bonitasoft.engine.search.SearchOptionsBuilder;
import org.bonitasoft.engine.search.SearchResult;
import org.bonitasoft.engine.service.TenantServiceSingleton
import org.bonitasoft.console.common.server.page.PageContext
import org.bonitasoft.console.common.server.page.PageController
import org.bonitasoft.console.common.server.page.PageResourceProvider
import org.bonitasoft.engine.exception.AlreadyExistsException;
import org.bonitasoft.engine.exception.BonitaHomeNotSetException;
import org.bonitasoft.engine.exception.CreationException;
import org.bonitasoft.engine.exception.DeletionException;
import org.bonitasoft.engine.exception.ServerAPIException;
import org.bonitasoft.engine.exception.UnknownAPITypeException;
import org.bonitasoft.engine.bpm.process.ProcessDefinitionNotFoundException;
import org.bonitasoft.engine.api.TenantAPIAccessor;
import org.bonitasoft.engine.bpm.flownode.HumanTaskInstance;
import org.bonitasoft.engine.bpm.flownode.HumanTaskInstanceSearchDescriptor;
import org.bonitasoft.engine.bpm.process.ArchivedProcessInstance;
import org.bonitasoft.engine.bpm.process.ArchivedProcessInstancesSearchDescriptor;
import org.bonitasoft.engine.bpm.process.ProcessInstance;
import org.bonitasoft.engine.bpm.process.ProcessInstanceSearchDescriptor;
import org.bonitasoft.engine.business.data.BusinessDataRepository
import org.bonitasoft.engine.session.APISession;
import org.bonitasoft.engine.api.ProcessAPI;
import org.bonitasoft.engine.api.IdentityAPI;
import org.bonitasoft.engine.command.CommandDescriptor;
import org.bonitasoft.engine.command.CommandCriterion;
import org.bonitasoft.engine.bpm.flownode.ActivityInstance;
import org.bonitasoft.engine.bpm.process.ProcessDeploymentInfo;
import org.bonitasoft.engine.identity.UserSearchDescriptor;
import org.bonitasoft.engine.search.Order;
import org.bonitasoft.engine.bpm.process.ProcessDeploymentInfo;
import org.bonitasoft.log.event.BEvent;
import org.bonitasoft.log.event.BEvent.Level;
import org.bonitasoft.log.event.BEventFactory;
import org.bonitasoft.properties.BonitaProperties;
import org.bonitasoft.engine.service.TenantServiceAccessor;
import org.bonitasoft.engine.service.TenantServiceSingleton;
import com.bonitasoft.users.UsersOperation;
public class Actions {
private static Logger logger= Logger.getLogger("org.bonitasoft.custompage.longboard.groovy");
private static BEvent eventGetSteEvents = new BEvent("com.edf.cockpitste", 1, Level.ERROR,
"Error during loading STE event", "Check Exception to see the cause",
"The properties will not work (no read, no save)", "Check Exception");
private final static BEvent eventCancelCaseError = new BEvent("com.edf.cockpitste", 2, Level.ERROR, "Erreur d'archive du case", "Une erreur est arrivée durant l'archivage du case", "Le case est toujours actif", "Vérifier l'erreur");
private final static BEvent eventCancelCaseWithSuccess = new BEvent("com.edf.cockpitste", 3, Level.SUCCESS, "Le case est archivé", "Le cas a été archivé avec succés");
private final static BEvent eventProcessNotFound = new BEvent("com.edf.cockpitste", 4, Level.ERROR, "Process non trouvé", "Un processus particulier est recherché, et il n'est pas déployé sur votre plateforme", "Aucun cas ne peut être crée", "Deployez le processus");
private final static BEvent eventTransfertRexSubmited = new BEvent("com.edf.cockpitste", 5, Level.SUCCESS, "Requête REX envoyée", "Les requêtes ont été soumises au SI REX");
private final static BEvent eventErreurRequeteREX = new BEvent("com.edf.cockpitste", 6, Level.ERROR, "Erreur lors de la soumission des requêtes", "Erreur", "Le cas n'est pas crée", "Vérifier l'erreur");
// 2018-03-08T00:19:15.04Z
public final static SimpleDateFormat sdfJson = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public final static SimpleDateFormat sdfHuman = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/* -------------------------------------------------------------------- */
/* */
/* doAction */
/* */
/* -------------------------------------------------------------------- */
public static Index.ActionAnswer doAction(HttpServletRequest request, String paramJsonSt, HttpServletResponse response, PageResourceProvider pageResourceProvider, PageContext pageContext) {
// logger.info("#### PingActions:Actions start");
Index.ActionAnswer actionAnswer = new Index.ActionAnswer();
List<BEvent> listEvents=new ArrayList<BEvent>();
Object jsonParam = (paramJsonSt==null ? null : JSONValue.parse(paramJsonSt));
try {
String action=request.getParameter("action");
logger.info("#### log:Actions action is["+action+"] !");
if (action==null || action.length()==0 )
{
actionAnswer.isManaged=false;
logger.info("#### log:Actions END No Actions");
return actionAnswer;
}
actionAnswer.isManaged=true;
// Hello
APISession apiSession = pageContext.getApiSession();
HttpSession httpSession = request.getSession();
ProcessAPI processAPI = TenantAPIAccessor.getProcessAPI(apiSession);
IdentityAPI identityAPI = TenantAPIAccessor.getIdentityAPI(apiSession);
long tenantId = apiSession.getTenantId();
TenantServiceAccessor tenantServiceAccessor = TenantServiceSingleton.getInstance(tenantId);
if ("ping".equals(action))
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
actionAnswer.responseMap.put("pingcurrentdate", sdf.format( new Date() ) );
actionAnswer.responseMap.put("pingserverinfo", "server is up 2.1");
List<ActivityTimeLine> listActivities = new ArrayList<ActivityTimeLine>();
listActivities.add( ActivityTimeLine.getActivityTimeLine("Choose beverage", 9, 11));
listActivities.add( ActivityTimeLine.getActivityTimeLine("Place Tea bag", 11, 12));
listActivities.add( ActivityTimeLine.getActivityTimeLine("Fill Hot Water", 12, 14));
listActivities.add( ActivityTimeLine.getActivityTimeLine("Insert Capsule", 11, 13));
listActivities.add( ActivityTimeLine.getActivityTimeLine("Inject hot water", 13, 14));
listActivities.add( ActivityTimeLine.getActivityTimeLine("Have fun with Bonita", 14, 17));
actionAnswer.responseMap.put("chartObject", getChartTimeLine("Chart Example", listActivities));
// list of process
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SearchOptionsBuilder searchOptionsBuilder = new SearchOptionsBuilder(0,100);
SearchResult<ProcessDeploymentInfo> searchResult = processAPI.searchProcessDeploymentInfos( searchOptionsBuilder.done());
ArrayList<HashMap<String,Object>> listProcesses = new ArrayList<HashMap<String,Object>>();
for (ProcessDeploymentInfo processDeployment : searchResult.getResult())
{
HashMap<String,Object> processMap = new HashMap<String,Object>();
processMap.put("name", processDeployment.getName() );
processMap.put("version", processDeployment.getVersion() );
processMap.put("state", processDeployment.getConfigurationState().toString() );
processMap.put("deployeddate", simpleDateFormat.format( processDeployment.getDeploymentDate() ) );
listProcesses.add( processMap);
}
actionAnswer.responseMap.put("listprocesses", listProcesses);
final UsersOperation userOperations = new UsersOperation();
final List<Map<String, Object>> listMapUsers = userOperations.getUsersList(identityAPI);
actionAnswer.responseMap.put("listusers", listMapUsers);
listEvents.add( new BEvent("com.bonitasoft.ping", 1, Level.INFO, listMapUsers.size()+" Users found", "Number of users found in the system"));
listEvents.add( new BEvent("com.bonitasoft.ping", 1, Level.APPLICATIONERROR, "Fake error", "This is not a real error", "No consequence", "don't call anybody"));
}
else if ("queryusers".equals(action))
{
List listUsers = new ArrayList();
final SearchOptionsBuilder searchOptionBuilder = new SearchOptionsBuilder(0, 100000);
// http://documentation.bonitasoft.com/?page=using-list-and-search-methods
searchOptionBuilder.filter(UserSearchDescriptor.ENABLED, Boolean.TRUE);
searchOptionBuilder.searchTerm( jsonParam==null ? "" : jsonParam.get("userfilter") );
searchOptionBuilder.sort(UserSearchDescriptor.LAST_NAME, Order.ASC);
searchOptionBuilder.sort(UserSearchDescriptor.FIRST_NAME, Order.ASC);
final SearchResult<User> searchResult = identityAPI.searchUsers(searchOptionBuilder.done());
for (final User user : searchResult.getResult())
{
final Map<String, Object> oneRecord = new HashMap<String, Object>();
// oneRecord.put("display", user.getFirstName()+" " + user.getLastName() + " (" + user.getUserName() + ")");
oneRecord.put("display", user.getLastName() + "," + user.getFirstName() + " (" + user.getUserName() + ")");
oneRecord.put("id", user.getId());
listUsers.add( oneRecord );
}
actionAnswer.responseMap.put("listUsers", listUsers);
}
else if ("saveprops".equals(action)) {
logger.info("Save properties paramJsonSt="+paramJsonSt);
if (jsonParam!=null)
{
try
{
BonitaProperties bonitaProperties = new BonitaProperties( pageResourceProvider );
listEvents.addAll( bonitaProperties.load() );
bonitaProperties.setProperty( apiSession.getUserId()+"_firstname", jsonParam.get("firstname") );
logger.info("Save properties -["+apiSession.getUserId()+"_firstname] <- ["+jsonParam.get("firstname") +"]");
listEvents.addAll( bonitaProperties.store());
}
catch( Exception e )
{
logger.severe("Exception "+e.toString());
listEvents.add( new BEvent("com.bonitasoft.ping", 10, Level.APPLICATIONERROR, "Error using BonitaProperties", "Error :"+e.toString(), "Properties is not saved", "Check exception"));
}
}
else
listEvents.add( new BEvent("com.bonitasoft.ping", 11, Level.APPLICATIONERROR, "JsonHash can't be decode", "the parameters in Json can't be decode", "Properties is not saved", "Check page"));
}
if ("loadprops".equals(action)) {
try
{
logger.info("Load properties");
BonitaProperties bonitaProperties = new BonitaProperties( pageResourceProvider );
listEvents.addAll( bonitaProperties.load() );
logger.info("Load done, events = "+listEvents.size() );
String firstName = bonitaProperties.getProperty( apiSession.getUserId()+"_firstname" );
logger.info("Load done, firstName["+firstName+"]" );
actionAnswer.responseMap.put("firstname", (firstName==null ? "" : firstName) );
}
catch( Exception e )
{
logger.severe("Exception "+e.toString());
listEvents.add( new BEvent("com.bonitasoft.ping", 10, Level.APPLICATIONERROR, "Error using BonitaProperties", "Error :"+e.toString(), "Properties is not saved", "Check exception"));
}
}
// actionAnswer.responseMap.put("listevents",BEventFactory.getHtml( listEvents));
logger.info("#### log:Actions END responseMap ="+actionAnswer.responseMap.size());
return actionAnswer;
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionDetails = sw.toString();
logger.severe("#### log:Groovy Exception ["+e.toString()+"] at "+exceptionDetails);
actionAnswer.isResponseMap=true;
actionAnswer.responseMap.put("Error", "log:Groovy Exception ["+e.toString()+"] at "+exceptionDetails);
return actionAnswer;
}
}
/**
to create a simple chart
*/
public static class ActivityTimeLine
{
public String activityName;
public Date dateBegin;
public Date dateEnd;
public static ActivityTimeLine getActivityTimeLine(String activityName, int timeBegin, int timeEnd)
{
Calendar calBegin = Calendar.getInstance();
calBegin.set(Calendar.HOUR_OF_DAY , timeBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.set(Calendar.HOUR_OF_DAY , timeEnd);
ActivityTimeLine oneSample = new ActivityTimeLine();
oneSample.activityName = activityName;
oneSample.dateBegin = calBegin.getTime();
oneSample.dateEnd = calEnd.getTime();
return oneSample;
}
public long getDateLong()
{ return dateBegin == null ? 0 : dateBegin.getTime(); }
}
/** create a simple chart
*/
public static String getChartTimeLine(String title, List<ActivityTimeLine> listSamples){
Logger logger = Logger.getLogger("org.bonitasoft");
/** structure
* "rows": [
{
c: [
{ "v": "January" },"
{ "v": 19,"f": "42 items" },
{ "v": 12,"f": "Ony 12 items" },
]
},
{
c: [
{ "v": "January" },"
{ "v": 19,"f": "42 items" },
{ "v": 12,"f": "Ony 12 items" },
]
},
*/
String resultValue="";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss,SSS");
for (int i=0;i<listSamples.size();i++)
{
logger.info("sample [i] : "+listSamples.get( i ).activityName+"] dateBegin["+simpleDateFormat.format( listSamples.get( i ).dateBegin)+"] dateEnd["+simpleDateFormat.format( listSamples.get( i ).dateEnd) +"]");
if (listSamples.get( i ).dateBegin!=null && listSamples.get( i ).dateEnd != null)
resultValue+= "{ \"c\": [ { \"v\": \""+listSamples.get( i ).activityName+"\" }," ;
resultValue+= " { \"v\": \""+listSamples.get( i ).activityName +"\" }, " ;
resultValue+= " { \"v\": \"Date("+ simpleDateFormat.format( listSamples.get( i ).dateBegin) +")\" }, " ;
resultValue+= " { \"v\": \"Date("+ simpleDateFormat.format( listSamples.get( i ).dateEnd) +")\" } " ;
resultValue+= "] },";
}
if (resultValue.length()>0)
resultValue = resultValue.substring(0,resultValue.length()-1);
String resultLabel = "{ \"type\": \"string\", \"id\": \"Role\" },{ \"type\": \"string\", \"id\": \"Name\"},{ \"type\": \"datetime\", \"id\": \"Start\"},{ \"type\": \"datetime\", \"id\": \"End\"}";
String valueChart = " {"
valueChart += "\"type\": \"Timeline\", ";
valueChart += "\"displayed\": true, ";
valueChart += "\"data\": {";
valueChart += "\"cols\": ["+resultLabel+"], ";
valueChart += "\"rows\": ["+resultValue+"] ";
/*
+ "\"options\": { "
+ "\"bars\": \"horizontal\","
+ "\"title\": \""+title+"\", \"fill\": 20, \"displayExactValues\": true,"
+ "\"vAxis\": { \"title\": \"ms\", \"gridlines\": { \"count\": 100 } }"
*/
valueChart += "}";
valueChart +="}";
// +"\"isStacked\": \"true\","
// +"\"displayExactValues\": true,"
//
// +"\"hAxis\": { \"title\": \"Date\" }"
// +"},"
logger.info("Value1 >"+valueChart+"<");
return valueChart;
}
}