Repository navigation
Expand file tree
/
Copy pathSecurityProjectUtils.java
More file actions
4394 lines (4057 loc) · 193 KB
/
Copy pathSecurityProjectUtils.java
File metadata and controls
4394 lines (4057 loc) · 193 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.auth.utils;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.javatuples.Pair;
import prerna.auth.AccessPermissionEnum;
import prerna.auth.AccessToken;
import prerna.auth.AuthProvider;
import prerna.auth.User;
import prerna.auth.access.ModelUsageLimit;
import prerna.auth.access.PermissionChange;
import prerna.auth.access.PermissionErrorRules;
import prerna.auth.access.PermissionGrant;
import prerna.auth.access.PermissionProblem;
import prerna.auth.access.PermissionSubject;
import prerna.auth.access.PermissionTargetResource;
import prerna.date.SemossDate;
import prerna.engine.api.IEngine;
import prerna.engine.api.IHeadersDataRow;
import prerna.engine.api.IRDBMSEngine;
import prerna.engine.api.IRawSelectWrapper;
import prerna.engine.impl.InsightAdministrator;
import prerna.engine.impl.SmssUtilities;
import prerna.notifications.NotificationDbUtils;
import prerna.project.api.IProject;
import prerna.project.impl.ProjectHelper;
import prerna.query.querystruct.SelectQueryStruct;
import prerna.query.querystruct.filters.AndQueryFilter;
import prerna.query.querystruct.filters.IQueryFilter;
import prerna.query.querystruct.filters.OrQueryFilter;
import prerna.query.querystruct.filters.SimpleQueryFilter;
import prerna.query.querystruct.joins.IRelation;
import prerna.query.querystruct.joins.SubqueryRelationship;
import prerna.query.querystruct.selectors.QueryColumnOrderBySelector;
import prerna.query.querystruct.selectors.QueryColumnSelector;
import prerna.query.querystruct.selectors.QueryFunctionHelper;
import prerna.query.querystruct.selectors.QueryFunctionSelector;
import prerna.query.querystruct.selectors.QueryIfSelector;
import prerna.rdf.engine.wrappers.WrapperManager;
import prerna.sablecc2.PixelUtility;
import prerna.sablecc2.lexer.LexerException;
import prerna.sablecc2.om.PixelDataType;
import prerna.sablecc2.om.execptions.SemossPixelException;
import prerna.sablecc2.parser.ParserException;
import prerna.usertracking.AuditEventType;
import prerna.usertracking.AuditTargetType;
import prerna.usertracking.UserAuditTrailUtils;
import prerna.util.ConnectionUtils;
import prerna.util.Constants;
import prerna.util.DIHelper;
import prerna.util.EmailUtility;
import prerna.util.InsightsRDBMSUtils;
import prerna.util.NotificationConstants;
import prerna.util.QueryExecutionUtility;
import prerna.util.SystemEngineRegistry;
import prerna.util.Utility;
import prerna.util.sql.AbstractSqlQueryUtil;
import prerna.util.sql.RdbmsTypeEnum;
public class SecurityProjectUtils extends AbstractSecurityUtils {
private static final Logger classLogger = LogManager.getLogger(SecurityProjectUtils.class);
private static final String INSUFFICIENT_PRIVILEGES = "Insufficient privileges to modify this project's permissions.";
private static final String NOT_HIGH_ENOUGH = "The user doesn't have the high enough permissions to modify this users project permission.";
private static final String INSERT_PROJECT = "INSERT INTO PROJECT (PROJECTID, PROJECTNAME, TYPE, COST, GLOBAL, "
+ "DISCOVERABLE, IS_TEMPLATE, CREATEDBY, CREATEDBYTYPE, DATECREATED, DATELASTEDITED, PROJECTDISPLAYNAME) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
private static final String UPDATE_PROJECT = "UPDATE PROJECT SET PROJECTNAME=?, TYPE=?, COST=?, GLOBAL=? "
+ "WHERE PROJECTID=?";
private static final String SELECT_STORED_INSIGHTS = "SELECT INSIGHTID, INSIGHTNAME, LAYOUT, GLOBAL, CACHEABLE, "
+ "CACHEMINUTES, CACHECRON, CACHEDON, CACHEENCRYPT, RECIPE, SCHEMANAME FROM INSIGHT WHERE PROJECTID=?";
private static final String SELECT_STORED_INSIGHT_META = "SELECT INSIGHTID, METAKEY, METAVALUE, METAORDER "
+ "FROM INSIGHTMETA WHERE PROJECTID=?";
/**
* Add an entire project into the security db - Expectation is not to call this
* method but addProject(projectId, boolean global = true)
*
* @param projectId
*
* PLEASE DEFINE GLOBAL
* {@link #addProject(String, boolean, User)}
* @throws Exception
*/
@Deprecated
public static void addProject(String projectId, User user) throws Exception {
// default project is not global
addProject(projectId, false, user);
}
/**
* Registers a project in the security database from its smss file, with the
* insights of its insights database. A project that is registered already is
* left as it is, unless its smss file sets RELOAD_INSIGHTS.
*
* <p>
* The project's files and its insights database cannot be part of a security
* database transaction, so the work runs in this order:
* </p>
* <ol>
* <li>The insights database is opened: the loaded project's, or else the one
* its smss file names. A failure to open it is thrown, and nothing is
* written.</li>
* <li>A first security database transaction registers the project, or updates
* its name, type, cost and global flag when it is registered already. It
* commits before the insights are copied, so the project is registered even
* when its insights cannot be.</li>
* <li>A second security database transaction replaces the project's INSIGHT and
* INSIGHTMETA rows with the rows of the insights database and, on a reload,
* removes the user permissions and preferences of the insights that no longer
* exist. Either all of it is saved or none of it is.</li>
* <li>The insights database is closed unless it is the loaded project's, and on
* a reload the smss file's RELOAD_INSIGHTS is set to false.</li>
* </ol>
*
* <p>
* A failure of either security database transaction is logged, not thrown, and
* rolled back. When the project's row is not saved, the insights are not
* copied. When the insights are not saved, the project keeps the insight rows
* it had: none, for a new project. Step 4 still runs.
* </p>
*
* @param projectId the project
* @param global whether the project is public, for a project not yet
* registered or reloaded
* @param user the user recorded as the creator of a project not yet
* registered, or null
* @throws Exception when the insights database cannot be opened
*/
public static void addProject(String projectId, boolean global, User user) throws Exception {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
String smssFile = DIHelper.getInstance().getProjectProperty(projectId + "_" + Constants.STORE) + "";
Properties prop = Utility.loadProperties(smssFile);
boolean isTemplate = Boolean.parseBoolean(prop.getProperty(Constants.IS_TEMPLATE, "false"));
String alias = prop.getProperty(Constants.PROJECT_ALIAS);
String projectName = alias == null ? projectId : alias;
String smssDisplayName = prop.getProperty(Constants.PROJECT_DISPLAY_NAME);
String displayName = smssDisplayName == null || smssDisplayName.trim().isEmpty() ? projectName
: smssDisplayName;
boolean reloadInsights = prop.containsKey(Constants.RELOAD_INSIGHTS)
&& Boolean.parseBoolean(prop.get(Constants.RELOAD_INSIGHTS).toString());
// TODO: we do not need cost for project
String[] typeAndCost = new String[] { prop.getOrDefault(Constants.PROJECT_ENUM_TYPE, "") + "", "" };
boolean projectExists = containsProjectId(projectId);
if (projectExists && !reloadInsights) {
classLogger.info("Security database already contains project with unique id = {}",
Utility.cleanLogString(SmssUtilities.getUniqueName(prop)));
return;
}
classLogger.info("Security database going to add project with alias = {}", Utility.cleanLogString(projectName));
// load just the insights database
// first see if engine is already loaded
boolean projectLoaded = false;
IRDBMSEngine rne;
if (Utility.projectLoaded(projectId)) {
rne = Utility.getProject(projectId).getInsightDatabase();
projectLoaded = true;
} else {
rne = ProjectHelper.loadInsightsEngine(prop, classLogger);
}
AbstractSqlQueryUtil securityQueryUtil = securityDb.getQueryUtil();
String insertInsight = securityQueryUtil.createInsertPreparedStatementString("INSIGHT",
new String[] { "PROJECTID", "INSIGHTID", "INSIGHTNAME", "GLOBAL", "EXECUTIONCOUNT", "CREATEDON",
"LASTMODIFIEDON", "LAYOUT", "CACHEABLE", "CACHEMINUTES", "CACHECRON", "CACHEDON",
"CACHEENCRYPT", "RECIPE", "SCHEMANAME" });
String insertInsightMeta = securityQueryUtil.createInsertPreparedStatementString("INSIGHTMETA",
new String[] { "PROJECTID", "INSIGHTID", "METAKEY", "METAVALUE", "METAORDER" });
Timestamp timeStamp = Utility.getCurrentSqlTimestampUTC();
SelectQueryStruct insightsQs = new SelectQueryStruct();
insightsQs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_ID_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_NAME_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_LAYOUT_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.HIDDEN_INSIGHT_COL));
insightsQs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHEABLE_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_MINUTES_COL));
insightsQs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_CRON_COL));
insightsQs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHED_ON_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_ENCRYPT_COL));
insightsQs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_PKQL_COL));
insightsQs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.SCHEMA_NAME_COL));
SelectQueryStruct metaQs = new SelectQueryStruct();
metaQs.addSelector(new QueryColumnSelector("INSIGHTMETA__INSIGHTID"));
metaQs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAKEY"));
metaQs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAVALUE"));
metaQs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAORDER"));
final int INSIGHT_BATCH_SIZE = 5000;
// the project's row is committed on its own first, so the project is
// registered even when its insights cannot be copied
boolean projectSaved = false;
try {
QueryExecutionUtility.write(securityDb, connection -> {
if (QueryExecutionUtility.queryOne(connection, "SELECT PROJECTID FROM PROJECT WHERE PROJECTID=?",
statement -> statement.setString(1, projectId), rs -> rs.getString(1)) == null) {
insertProject(connection, securityQueryUtil, projectId, projectName, displayName, typeAndCost[0],
typeAndCost[1], global, isTemplate, user);
} else {
// update project properties anyway ... in case global was shifted for example
updateProject(connection, securityQueryUtil, projectId, projectName, typeAndCost[0], typeAndCost[1],
global);
}
return null;
});
projectSaved = true;
} catch (Exception e) {
classLogger.error("Failed to save the project row of project {}", Utility.cleanLogString(projectId), e);
}
// the project's insights and their metadata, and on a reload the permissions
// of insights that no longer exist, in a second transaction, so a failure
// leaves the insight rows that were there
if (projectSaved) {
try {
QueryExecutionUtility.write(securityDb, connection -> {
// on a reload, the insights with permissions now; an insight that still
// exists keeps its permissions, and the others' are removed below
Set<String> insightPermissionIds = new HashSet<>();
if (reloadInsights) {
classLogger.info("Reloading app. Retrieving existing insights with permissions");
insightPermissionIds.addAll(QueryExecutionUtility.queryList(connection,
"SELECT INSIGHTID FROM USERINSIGHTPERMISSION WHERE PROJECTID=?",
statement -> statement.setString(1, projectId), rs -> rs.getString(1)));
}
QueryExecutionUtility.executeUpdate(connection, "DELETE FROM INSIGHT WHERE PROJECTID=?",
statement -> statement.setString(1, projectId));
int insights = QueryExecutionUtility.executeBatchFromQuery(connection, insertInsight, rne,
insightsQs, INSIGHT_BATCH_SIZE, (statement, row) -> {
String insightId = bindInsight(statement, row, projectId, timeStamp, securityQueryUtil);
// an insight that still exists keeps its permissions
insightPermissionIds.remove(insightId);
});
QueryExecutionUtility.executeUpdate(connection, "DELETE FROM INSIGHTMETA WHERE PROJECTID=?",
statement -> statement.setString(1, projectId));
int metaRows = QueryExecutionUtility.executeBatchFromQuery(connection, insertInsightMeta, rne,
metaQs, INSIGHT_BATCH_SIZE,
(statement, row) -> bindInsightMeta(statement, row, projectId, securityQueryUtil));
classLogger.info("Saved {} insights and {} insight metadata rows", insights, metaRows);
// need to remove existing insights w/ permissions that do not exist anymore
if (!insightPermissionIds.isEmpty()) {
classLogger.info("Removing insights with permissions that no longer exist");
QueryExecutionUtility.executeBatch(connection,
"DELETE FROM USERINSIGHTPERMISSION WHERE PROJECTID=? AND INSIGHTID=?",
insightPermissionIds, (statement, deleteId) -> {
statement.setString(1, projectId);
statement.setString(2, deleteId);
});
QueryExecutionUtility.executeBatch(connection,
"DELETE FROM USERINSIGHTPREFERENCE WHERE PROJECTID=? AND INSIGHTID=?",
insightPermissionIds, (statement, deleteId) -> {
statement.setString(1, projectId);
statement.setString(2, deleteId);
});
}
return null;
});
} catch (Exception e) {
classLogger.error("Failed to save the insights of project {}", Utility.cleanLogString(projectId), e);
}
}
// close the connection to the insights
// if the engine is not already loaded
// since the open method will load it
if (!projectLoaded && rne != null) {
rne.close();
}
if (reloadInsights) {
classLogger.info("Modifying force reload to false");
try {
Utility.changePropertiesFileValue(smssFile, Constants.RELOAD_INSIGHTS, "false");
} catch (IOException e) {
classLogger.error("Failed to set RELOAD_INSIGHTS to false in the smss file of project {}",
Utility.cleanLogString(projectId), e);
}
}
classLogger.info("Finished adding project = {}", Utility.cleanLogString(projectId));
}
/**
* Binds an INSIGHT row from a row of the project's insights database.
*
* @return the insight's id
*/
private static String bindInsight(PreparedStatement statement, IHeadersDataRow row, String projectId,
Timestamp timeStamp, AbstractSqlQueryUtil queryUtil) throws SQLException, UnsupportedEncodingException {
Object[] values = row.getValues();
// grab the insight rdbms values
int index = 0;
String insightId = values[index++].toString();
String insightName = values[index++].toString();
String insightLayout = values[index++].toString();
Boolean isPrivate = (Boolean) values[index++];
if (isPrivate == null) {
isPrivate = false;
}
Boolean cacheable = (Boolean) values[index++];
if (cacheable == null) {
cacheable = true;
}
Integer cacheMinutes = (Integer) values[index++];
if (cacheMinutes == null) {
cacheMinutes = -1;
}
String cacheCron = (String) values[index++];
SemossDate cachedOn = (SemossDate) values[index++];
Boolean cacheEncrypt = (Boolean) values[index++];
if (cacheEncrypt == null) {
cacheEncrypt = false;
}
Object pixelObject = values[index++];
String schemaName = (String) values[index++];
int parameterIndex = 1;
statement.setString(parameterIndex++, projectId);
statement.setString(parameterIndex++, insightId);
statement.setString(parameterIndex++, insightName);
statement.setBoolean(parameterIndex++, !isPrivate);
statement.setLong(parameterIndex++, 0);
statement.setTimestamp(parameterIndex++, timeStamp);
statement.setTimestamp(parameterIndex++, timeStamp);
statement.setString(parameterIndex++, insightLayout);
statement.setBoolean(parameterIndex++, cacheable);
statement.setInt(parameterIndex++, cacheMinutes);
queryUtil.setNullableString(statement, parameterIndex++, cacheCron);
if (cachedOn == null) {
statement.setNull(parameterIndex++, java.sql.Types.TIMESTAMP);
} else {
statement.setTimestamp(parameterIndex++, Utility.getSqlTimestampUTC(cachedOn));
}
statement.setBoolean(parameterIndex++, cacheEncrypt);
queryUtil.handleInsertionOfClob(statement.getConnection(), statement, pixelObject, parameterIndex++,
securityGson);
queryUtil.setNullableString(statement, parameterIndex++, schemaName);
return insightId;
}
/**
* Binds an INSIGHTMETA row from a row of the project's insights database.
*/
private static void bindInsightMeta(PreparedStatement statement, IHeadersDataRow row, String projectId,
AbstractSqlQueryUtil queryUtil) throws SQLException, UnsupportedEncodingException {
Object[] values = row.getValues();
int parameterIndex = 1;
statement.setString(parameterIndex++, projectId);
statement.setString(parameterIndex++, values[0].toString());
statement.setString(parameterIndex++, values[1].toString());
// the value can be a clob, which goes in as it was read
queryUtil.handleInsertionOfClob(statement.getConnection(), statement, row.getRawValues()[2], parameterIndex++,
securityGson);
statement.setInt(parameterIndex++, ((Number) values[3]).intValue());
}
/**
* Adds a project to the security database with its name as its display name.
* The project is not discoverable and not a template, and the user, when given,
* is recorded as its creator.
*
* @param projectId
* @param projectName
* @param projectType
* @param projectCost
* @param portalName
* @param global
* @param user
*/
public static void addProject(String projectId, String projectName, String projectType, String projectCost,
boolean global, User user) {
addProject(projectId, projectName, projectName, projectType, projectCost, global, user);
}
public static void addProject(String projectId, String projectName, String projectDisplayName, String projectType,
String projectCost, boolean global, User user) {
addProject(projectId, projectName, projectDisplayName, projectType, projectCost, global, false, user);
}
public static void addProject(String projectId, String projectName, String projectDisplayName, String projectType,
String projectCost, boolean global, boolean isTemplate, User user) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
try {
QueryExecutionUtility.write(securityDb, connection -> {
insertProject(connection, securityDb.getQueryUtil(), projectId, projectName, projectDisplayName,
projectType, projectCost, global, isTemplate, user);
return null;
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
}
/**
* Inserts a project's PROJECT row on the caller's connection, in its
* transaction. The project is not discoverable, it was created and last edited
* now, and the user, when given, is recorded as its creator. A blank display
* name gives the project's name as its display name.
*
* @param connection the security database connection, in the caller's
* transaction
* @param queryUtil the security database's query util, for its binders
*/
private static void insertProject(Connection connection, AbstractSqlQueryUtil queryUtil, String projectId,
String projectName, String projectDisplayName, String projectType, String projectCost, boolean global,
boolean isTemplate, User user) throws Exception {
QueryExecutionUtility.executeUpdate(connection, INSERT_PROJECT, ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, projectId);
queryUtil.setNullableString(ps, parameterIndex++, projectName);
queryUtil.setNullableString(ps, parameterIndex++, projectType);
queryUtil.setNullableString(ps, parameterIndex++, projectCost);
ps.setBoolean(parameterIndex++, global);
ps.setBoolean(parameterIndex++, false);
ps.setBoolean(parameterIndex++, isTemplate);
if (user != null) {
AuthProvider ap = user.getPrimaryLogin();
AccessToken token = user.getAccessToken(ap);
ps.setString(parameterIndex++, token.getId());
ps.setString(parameterIndex++, ap.toString());
} else {
ps.setNull(parameterIndex++, java.sql.Types.VARCHAR);
ps.setNull(parameterIndex++, java.sql.Types.VARCHAR);
}
ps.setTimestamp(parameterIndex++, Utility.getCurrentSqlTimestampUTC());
ps.setTimestamp(parameterIndex++, Utility.getCurrentSqlTimestampUTC());
if (projectDisplayName == null || projectDisplayName.trim().isEmpty()) {
queryUtil.setNullableString(ps, parameterIndex++, projectName);
} else {
ps.setString(parameterIndex++, projectDisplayName);
}
});
}
public static void addProjectOwner(User user, String projectId, String userId) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
Pair<String, String> userDetails = User.getPrimaryUserIdAndTypePair(user);
String query = "INSERT INTO PROJECTPERMISSION (USERID, PERMISSION, PROJECTID, PERMISSIONGRANTEDBY, PERMISSIONGRANTEDBYTYPE, DATEADDED) VALUES (?,?,?,?,?,?)";
try {
QueryExecutionUtility.executeUpdate(securityDb, query, ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, userId);
ps.setInt(parameterIndex++, AccessPermissionEnum.OWNER.getId());
ps.setString(parameterIndex++, projectId);
ps.setString(parameterIndex++, userDetails.getValue0());
ps.setString(parameterIndex++, userDetails.getValue1());
ps.setTimestamp(parameterIndex++, Utility.getCurrentSqlTimestampUTC());
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to add project owner", e);
}
}
public static void updateProject(String projectID, String projectName, String projectType, String projectCost,
boolean global) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
try {
QueryExecutionUtility.write(securityDb, connection -> {
updateProject(connection, securityDb.getQueryUtil(), projectID, projectName, projectType, projectCost,
global);
return null;
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to update project properties in the security database", e);
}
}
/**
* Updates a project's name, type, cost and global flag on the caller's
* connection, in its transaction.
*
* @param connection the security database connection, in the caller's
* transaction
* @param queryUtil the security database's query util, for its binders
*/
private static void updateProject(Connection connection, AbstractSqlQueryUtil queryUtil, String projectId,
String projectName, String projectType, String projectCost, boolean global) throws Exception {
QueryExecutionUtility.executeUpdate(connection, UPDATE_PROJECT, ps -> {
int parameterIndex = 1;
queryUtil.setNullableString(ps, parameterIndex++, projectName);
queryUtil.setNullableString(ps, parameterIndex++, projectType);
queryUtil.setNullableString(ps, parameterIndex++, projectCost);
ps.setBoolean(parameterIndex++, global);
ps.setString(parameterIndex++, projectId);
});
}
/**
* For updating Last Edited Date for Apps
*
* @param projectID
*/
public static void updateProjectLastEditedDate(String projectID) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
String query = "UPDATE PROJECT SET DATELASTEDITED=? WHERE PROJECTID=?";
try {
QueryExecutionUtility.executeUpdate(securityDb, query, ps -> {
int parameterIndex = 1;
ps.setTimestamp(parameterIndex++, Utility.getCurrentSqlTimestampUTC());
ps.setString(parameterIndex++, projectID);
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to update project last edited date", e);
}
}
/**
* Delete just the insights for a project
*
* @param appId
*/
public static void deleteInsightsFromProjectForRecreation(String projectId) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
String deleteQuery = "DELETE FROM INSIGHT WHERE PROJECTID=?";
try {
QueryExecutionUtility.executeUpdate(securityDb, deleteQuery, ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, projectId);
});
} catch (Exception e) {
classLogger.error("Failed to delete project insights before recreation", e);
throw new IllegalArgumentException("An error occurred deleting the insights for project " + projectId);
}
}
/**
* Builds a new insights database for the project in the given folder from the
* insights and insight metadata stored in the security database, and returns
* its file once the database is closed.
*
* <p>
* The new insights database is a separate engine, so it cannot share a
* transaction with the security database. It is created first; then the
* project's insights and their metadata are read from the security database
* together, in one read transaction, before anything is written to it. When
* that read fails, or an insight cannot be written, the new database is closed,
* its file is deleted, and an {@link IllegalArgumentException} is thrown. An
* insight with no recipe is skipped. When the metadata cannot be written, the
* failure is logged and the file is returned without it.
* </p>
*
* @param projectId the project
* @param folderPath the folder the new insights database is made in
* @return the new insights database's file
* @throws Exception when the new insights database cannot be made
*/
public static File createInsightsDatabase(String projectId, String folderPath) throws Exception {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
// TODO: potentially take into consideration playsheet legacy insights
IProject project = Utility.getProject(projectId);
RdbmsTypeEnum insightType = project.getInsightDatabase().getQueryUtil().getDbType();
IRDBMSEngine newInsightDatabase = InsightsRDBMSUtils.generateInsightsDatabase(projectId, insightType,
folderPath);
InsightsRDBMSUtils.runInsightCreateTableQueries(newInsightDatabase);
InsightAdministrator admin = new InsightAdministrator(newInsightDatabase);
StoredProjectInsights stored = null;
{
boolean error = false;
PreparedStatement insertPs = null;
try {
// the insights and their metadata are read together, before anything is
// written to the new database
stored = QueryExecutionUtility.read(securityDb,
connection -> readStoredInsights(connection, securityDb.getDatabaseZoneId(), projectId));
insertPs = admin.getAddInsightPreparedStatement();
for (StoredInsight insight : stored.insights()) {
String pixelRecipe = insight.recipe();
List<String> pixelList = null;
if (pixelRecipe != null && !pixelRecipe.isEmpty() && !pixelRecipe.equals("null")) {
List<String> pixel = securityGson.fromJson(pixelRecipe, List.class);
int pixelSize = pixel.size();
pixelList = new ArrayList<>(pixelSize);
for (int i = 0; i < pixelSize; i++) {
String pixelString = pixel.get(i).toString();
List<String> breakdown;
try {
breakdown = PixelUtility.parsePixel(pixelString);
pixelList.addAll(breakdown);
} catch (ParserException | LexerException | IOException e) {
classLogger.error("Failed to create or initialize the project insights database", e);
throw new IllegalArgumentException("Error occurred parsing the pixel expression");
}
}
} else {
classLogger.warn("Cannot write insight id '{}' with no pixel recipe", insight.insightId());
continue;
}
admin.batchInsight(insertPs, insight.insightId(), insight.insightName(), insight.layout(),
pixelList, insight.global(), insight.cacheable(), insight.cacheMinutes(),
insight.cacheCron(), insight.cachedOn(), insight.cacheEncrypt(), insight.schemaName());
}
insertPs.executeBatch();
if (!insertPs.getConnection().getAutoCommit()) {
insertPs.getConnection().commit();
}
} catch (Exception e) {
error = true;
classLogger.error("Failed to create or initialize the project insights database", e);
throw new IllegalArgumentException("Error occured creating the insights database");
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(newInsightDatabase, insertPs);
if (error) {
try {
newInsightDatabase.close();
} catch (Exception e) {
classLogger.error("Failed to create or initialize the project insights database", e);
}
String databaseFileLocation = newInsightDatabase.getSmssProp()
.getProperty(AbstractSqlQueryUtil.HOSTNAME);
File databaseFile = new File(databaseFileLocation);
if (databaseFile.exists() && databaseFile.isFile()) {
databaseFile.delete();
}
}
}
}
{
PreparedStatement insertPs = null;
try {
insertPs = admin.getAddInsightMetaPreparedStatement();
for (StoredInsightMeta meta : stored.metadata()) {
admin.batchInsightMetadata(insertPs, meta.insightId(), meta.metaKey(), meta.metaValue(),
meta.metaOrder());
}
insertPs.executeBatch();
if (!insertPs.getConnection().getAutoCommit()) {
insertPs.getConnection().commit();
}
} catch (Exception e) {
// insight metadata is not as important, log the error
classLogger.error("Failed to create or initialize the project insights database", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(newInsightDatabase, insertPs);
}
}
// close the db so we can move it
newInsightDatabase.close();
String databaseFileLocation = newInsightDatabase.getSmssProp().getProperty(AbstractSqlQueryUtil.HOSTNAME);
File databaseFile = new File(databaseFileLocation);
return databaseFile;
}
/**
* Reads a project's insights and their metadata on the caller's connection, in
* its transaction, with each value converted as a query of the security
* database converts it.
*
* @param connection the security database connection
* @param databaseZoneId the security database's time zone, for when an insight
* was cached
* @return the project's insights and their metadata
*/
private static StoredProjectInsights readStoredInsights(Connection connection, ZoneId databaseZoneId,
String projectId) throws Exception {
List<StoredInsight> insights = QueryExecutionUtility.queryList(connection, SELECT_STORED_INSIGHTS,
ps -> ps.setString(1, projectId), rs -> {
Timestamp cachedOn = rs.getTimestamp(8);
return new StoredInsight(rs.getString(1), rs.getString(2), rs.getString(3), rs.getBoolean(4),
rs.getBoolean(5), rs.getInt(6), rs.getString(7),
cachedOn == null ? null
: new SemossDate(cachedOn, databaseZoneId, "yyyy-MM-dd HH:mm:ss")
.getLocalDateTime(),
rs.getBoolean(9), rs.getString(10), rs.getString(11));
});
List<StoredInsightMeta> metadata = QueryExecutionUtility.queryList(connection, SELECT_STORED_INSIGHT_META,
ps -> ps.setString(1, projectId),
rs -> new StoredInsightMeta(rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4)));
return new StoredProjectInsights(insights, metadata);
}
/**
* A project's insights and their metadata as the security database keeps them,
* read together for its insights database.
*/
private record StoredProjectInsights(List<StoredInsight> insights, List<StoredInsightMeta> metadata) {
}
/**
* One of a project's insights as the security database keeps it.
*/
private record StoredInsight(String insightId, String insightName, String layout, boolean global, boolean cacheable,
int cacheMinutes, String cacheCron, LocalDateTime cachedOn, boolean cacheEncrypt, String recipe,
String schemaName) {
}
/**
* One metadata value of one of a project's insights as the security database
* keeps it.
*/
private record StoredInsightMeta(String insightId, String metaKey, String metaValue, int metaOrder) {
}
/**
* Try to reconcile and get the engine id
*
* @return
*/
public static String testUserProjectIdForAlias(User user, String potentialId) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
List<String> ids = new ArrayList<String>();
// String userFilters = getUserFilters(user);
// String query = "SELECT DISTINCT PROJECTPERMISSION.PROJECTID "
// + "FROM PROJECTPERMISSION INNER JOIN PROJECT ON
// PROJECT.PROJECTID=PROJECTPERMISSION.PROJECTID "
// + "WHERE PROJECT.PROJECTNAME='" + potentialId + "' AND
// PROJECTPERMISSION.USERID IN " + userFilters;
//
// IRawSelectWrapper wrapper =
// WrapperManager.getInstance().getRawWrapper(securityDb, query);
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECTPERMISSION__PROJECTID"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__PROJECTNAME", "==", potentialId));
qs.addExplicitFilter(
SimpleQueryFilter.makeColToValFilter("PROJECTPERMISSION__USERID", "==", getUserFiltersQs(user)));
qs.addRelation("PROJECT", "PROJECTPERMISSION", "inner.join");
ids = QueryExecutionUtility.flushToListString(securityDb, qs);
if (ids.isEmpty()) {
// query = "SELECT DISTINCT PROJECT.PROJECTID FROM PROJECT WHERE
// PROJECT.PROJECTNAME='" + potentialId + "' AND PROJECT.GLOBAL=TRUE";
qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTID"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__PROJECTNAME", "==", potentialId));
qs.addExplicitFilter(
SimpleQueryFilter.makeColToValFilter("PROJECT__GLOBAL", "==", true, PixelDataType.BOOLEAN));
ids = QueryExecutionUtility.flushToListString(securityDb, qs);
}
if (ids.size() == 1) {
potentialId = ids.get(0);
} else if (ids.size() > 1) {
throw new IllegalArgumentException("There are 2 projects with the name " + potentialId
+ ". Please pass in the correct id to know which source you want to load from");
}
return potentialId;
}
/**
* Get the engine alias for a id
*
* @return
*/
public static String getProjectAliasForId(String id) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
// String query = "SELECT PROJECTNAME FROM PROJECT WHERE PROJECTID='" + id +
// "'";
// IRawSelectWrapper wrapper =
// WrapperManager.getInstance().getRawWrapper(securityDb, query);
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTNAME"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__PROJECTID", "==", id));
List<String> results = QueryExecutionUtility.flushToListString(securityDb, qs);
if (results.isEmpty()) {
return null;
}
return results.get(0);
}
/**
* Get the display name for a project id. Falls back to canonical name
* (PROJECTNAME) if display name is null or blank.
*
* @param id
* @return
*/
public static String getProjectDisplayNameForId(String id) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTDISPLAYNAME"));
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTNAME"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__PROJECTID", "==", id));
List<Object[]> results = QueryExecutionUtility.flushRsToListOfObjArray(securityDb, qs);
if (results.isEmpty()) {
return null;
}
Object[] row = results.get(0);
String displayName = row[0] != null ? row[0].toString() : null;
String canonicalName = row[1] != null ? row[1].toString() : null;
if (displayName == null || displayName.trim().isEmpty()) {
return canonicalName;
}
return displayName;
}
/**
* Get the catalog type (PROJECT.TYPE, e.g. SKILL / WORKSPACE / CODE) for a
* project id. Returns null when the project row does not exist. This is a
* single securitydb query - unlike {@code Utility.getProject(id)} it never
* force-loads the project, so it is safe for validation loops.
*
* @param id project id
* @return the PROJECT.TYPE value, or null when the project is not cataloged
*/
public static String getProjectTypeForId(String id) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__TYPE"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__PROJECTID", "==", id));
List<String> results = QueryExecutionUtility.flushToListString(securityDb, qs);
if (results.isEmpty()) {
return null;
}
return results.get(0);
}
/**
* Set the display name for a project. Only the project owner can perform this
* action.
*
* @param user
* @param projectId
* @param newDisplayName
* @return
* @throws IllegalAccessException
*/
public static boolean setProjectDisplayName(User user, String projectId, String newDisplayName)
throws IllegalAccessException {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
if (!SecurityUserProjectUtils.userIsOwner(user, projectId)) {
throw new IllegalAccessException(
"The user doesn't have the permission to change the project display name. Only the owner can perform this action.");
}
if (newDisplayName == null || newDisplayName.trim().isEmpty()) {
throw new IllegalArgumentException("Display name cannot be null or blank.");
}
try {
QueryExecutionUtility.executeUpdate(securityDb, "UPDATE PROJECT SET PROJECTDISPLAYNAME=? WHERE PROJECTID=?",
ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, newDisplayName);
ps.setString(parameterIndex++, projectId);
});
} catch (Exception e) {
classLogger.error("Failed to update project display name", e);
throw new IllegalArgumentException("An error occurred updating the project display name");
}
UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_DISPLAY_NAME_UPDATE, projectId,
newDisplayName, Map.of("field", "displayName", "displayName", newDisplayName));
return true;
}
/**
* Get user databases + global databases
*
* @param userId
* @return
*/
public static List<String> getFullUserProjectIds(User user) {
List<String> databaseList = SecurityUserProjectUtils.getFullUserProjectIds(user);
databaseList.addAll(getGlobalProjectIds());
return databaseList.stream().distinct().sorted().collect(Collectors.toList());
}
/**
* Get global databases
*
* @return
*/
public static Set<String> getGlobalProjectIds() {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTID"));
qs.addExplicitFilter(
SimpleQueryFilter.makeColToValFilter("PROJECT__GLOBAL", "==", true, PixelDataType.BOOLEAN));
return QueryExecutionUtility.flushToSetString(securityDb, qs, false);
}
/**
* Get what permission the user has for a given app
*
* @param userId
* @param projectId
* @param insightId
* @return
*/
public static String getActualUserProjectPermission(User user, String projectId) {
String userPermission = SecurityUserProjectUtils.getActualUserProjectPermission(user, projectId);
List<String> groupUserPermissions = SecurityUserProjectUtils.getActualGroupUserProjectPermission(user,
projectId);
return SecurityUserProjectUtils.getHighestProjectPermission(userPermission, groupUserPermissions);
}
/**
* Get a list of the project ids
*
* @return
*/
public static List<String> getAllProjectIds() {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECT__PROJECTID"));
return QueryExecutionUtility.flushToListString(securityDb, qs);
}
/**
* Reads the project's portal details: whether the project is published, and the
* URL of its portal folder.
*
* @param projectId
* @return
*/