-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSecurityProjectUtils.java
More file actions
4833 lines (4430 loc) · 202 KB
/
Copy pathSecurityProjectUtils.java
File metadata and controls
4833 lines (4430 loc) · 202 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.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
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.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.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);
/**
* 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);
}
/**
* Add an entire project into the security db
*
* @param appId
* @throws Exception
*/
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 projectName = prop.getProperty(Constants.PROJECT_ALIAS);
if (projectName == null) {
projectName = projectId;
}
String displayName = prop.getProperty(Constants.PROJECT_DISPLAY_NAME);
if (displayName == null || displayName.trim().isEmpty()) {
displayName = projectName;
}
boolean reloadInsights = false;
if (prop.containsKey(Constants.RELOAD_INSIGHTS)) {
String booleanStr = prop.get(Constants.RELOAD_INSIGHTS).toString();
reloadInsights = Boolean.parseBoolean(booleanStr);
}
// 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;
} else if (!projectExists) {
addProject(projectId, projectName, displayName, typeAndCost[0], typeAndCost[1], global, isTemplate, user);
} else if (projectExists) {
// delete values if currently present
deleteInsightsFromProjectForRecreation(projectId);
// update project properties anyway ... in case global was shifted for example
updateProject(projectId, projectName, typeAndCost[0], typeAndCost[1], global);
}
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 = null;
if (Utility.projectLoaded(projectId)) {
rne = Utility.getProject(projectId).getInsightDatabase();
} else {
rne = ProjectHelper.loadInsightsEngine(prop, classLogger);
}
// i need to delete any current insights for the project
// before i start to insert new insights
String deleteQuery = "DELETE FROM INSIGHT WHERE PROJECTID='" + projectId + "'";
try {
securityDb.removeData(deleteQuery);
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
// if we are doing a reload
// we will want to remove unnecessary insights
// from the insight permissions
boolean existingInsightPermissions = true;
Set<String> insightPermissionIds = null;
if (reloadInsights) {
// need to flush out the current insights w/ permissions
// will keep the same permissions
// and perform a delta
classLogger.info("Reloading app. Retrieving existing insights with permissions");
String insightsWPer = "SELECT INSIGHTID FROM USERINSIGHTPERMISSION WHERE PROJECTID='" + projectId + "'";
insightPermissionIds = QueryExecutionUtility.flushToSetString(securityDb, insightsWPer, false);
if (insightPermissionIds.isEmpty()) {
existingInsightPermissions = true;
}
}
AbstractSqlQueryUtil securityQueryUtil = securityDb.getQueryUtil();
// make a prepared statement
PreparedStatement ps = null;
try {
ps = securityDb.bulkInsertPreparedStatement(new String[] {
// table name
"INSIGHT",
// column names
"PROJECTID", "INSIGHTID", "INSIGHTNAME", "GLOBAL", "EXECUTIONCOUNT", "CREATEDON", "LASTMODIFIEDON",
"LAYOUT", "CACHEABLE", "CACHEMINUTES", "CACHECRON", "CACHEDON", "CACHEENCRYPT", "RECIPE",
"SCHEMANAME" });
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
// keep a batch size so we dont get heapspace
final int batchSize = 5000;
int count = 0;
Timestamp timeStamp = Utility.getCurrentSqlTimestampUTC();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_ID_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_NAME_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_LAYOUT_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.HIDDEN_INSIGHT_COL));
qs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHEABLE_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_MINUTES_COL));
qs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_CRON_COL));
qs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHED_ON_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.CACHE_ENCRYPT_COL));
qs.addSelector(new QueryColumnSelector(
InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.QUESTION_PKQL_COL));
qs.addSelector(
new QueryColumnSelector(InsightAdministrator.TABLE_NAME + "__" + InsightAdministrator.SCHEMA_NAME_COL));
try (IRawSelectWrapper wrapper = WrapperManager.getInstance().getRawWrapper(rne, qs)) {
while (wrapper.hasNext()) {
Object[] row = wrapper.next().getValues();
try {
// grab the insight rdbms values
int index = 0;
String insightId = row[index++].toString();
String insightName = row[index++].toString();
String insightLayout = row[index++].toString();
Boolean isPrivate = (Boolean) row[index++];
if (isPrivate == null) {
isPrivate = false;
}
Boolean cacheable = (Boolean) row[index++];
if (cacheable == null) {
cacheable = true;
}
Integer cacheMinutes = (Integer) row[index++];
if (cacheMinutes == null) {
cacheMinutes = -1;
}
String cacheCron = (String) row[index++];
SemossDate cachedOn = (SemossDate) row[index++];
Boolean cacheEncrypt = (Boolean) row[index++];
if (cacheEncrypt == null) {
cacheEncrypt = false;
}
Object pixelObject = row[index++];
String schemaName = (String) row[index++];
// insert prepared statement into security db
int parameterIndex = 1;
ps.setString(parameterIndex++, projectId);
ps.setString(parameterIndex++, insightId);
ps.setString(parameterIndex++, insightName);
ps.setBoolean(parameterIndex++, !isPrivate);
ps.setLong(parameterIndex++, 0);
ps.setTimestamp(parameterIndex++, timeStamp);
ps.setTimestamp(parameterIndex++, timeStamp);
ps.setString(parameterIndex++, insightLayout);
ps.setBoolean(parameterIndex++, cacheable);
ps.setInt(parameterIndex++, cacheMinutes);
securityDb.getQueryUtil().setNullableString(ps, parameterIndex++, cacheCron);
if (cachedOn == null) {
ps.setNull(parameterIndex++, java.sql.Types.TIMESTAMP);
} else {
ps.setTimestamp(parameterIndex++, Utility.getSqlTimestampUTC(cachedOn));
}
ps.setBoolean(parameterIndex++, cacheEncrypt);
securityQueryUtil.handleInsertionOfClob(ps.getConnection(), ps, pixelObject, parameterIndex++,
securityGson);
securityDb.getQueryUtil().setNullableString(ps, parameterIndex++, schemaName);
// add to ps
ps.addBatch();
// batch commit based on size
if (++count % batchSize == 0) {
classLogger.info("Executing batch .... row num = {}", count);
ps.executeBatch();
}
if (reloadInsights && insightPermissionIds != null && existingInsightPermissions) {
insightPermissionIds.remove(insightId);
}
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
}
} catch (Exception e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
// well, we are done looping through now
classLogger.info("Executing final batch .... row num = {}", count);
try {
ps.executeBatch();
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
// commit
try {
if (!ps.getConnection().getAutoCommit()) {
ps.getConnection().commit();
}
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(securityDb, ps);
}
count = 0;
// same for insight meta
// i need to delete any current insights for the app
// before i start to insert new insights
deleteQuery = "DELETE FROM INSIGHTMETA WHERE PROJECTID='" + projectId + "'";
try {
securityDb.removeData(deleteQuery);
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
try {
ps = securityDb.bulkInsertPreparedStatement(
new String[] { "INSIGHTMETA", "PROJECTID", "INSIGHTID", "METAKEY", "METAVALUE", "METAORDER" });
} catch (SQLException e1) {
classLogger.error("Failed to create the project and initialize project security records", e1);
}
qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("INSIGHTMETA__INSIGHTID"));
qs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAKEY"));
qs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAVALUE"));
qs.addSelector(new QueryColumnSelector("INSIGHTMETA__METAORDER"));
try (IRawSelectWrapper wrapper = WrapperManager.getInstance().getRawWrapper(rne, qs)) {
while (wrapper.hasNext()) {
IHeadersDataRow data = wrapper.next();
Object[] row = data.getValues();
Object[] raw = data.getRawValues();
try {
int parameterIndex = 1;
ps.setString(parameterIndex++, projectId);
ps.setString(parameterIndex++, row[0].toString());
ps.setString(parameterIndex++, row[1].toString());
// need to determine if our input is a clob
// and if the database allows a clob data type
// use the utility method generated
Object metaValue = raw[2];
securityQueryUtil.handleInsertionOfClob(ps.getConnection(), ps, metaValue, parameterIndex++,
securityGson);
// add the order
ps.setInt(parameterIndex++, ((Number) row[3]).intValue());
// add to ps
ps.addBatch();
// batch commit based on size
if (++count % batchSize == 0) {
classLogger.info("Executing batch .... row num = {}", count);
ps.executeBatch();
}
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
}
} catch (Exception e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
// well, we are done looping through now
classLogger.info("Executing final batch .... row num = {}", count);
try {
ps.executeBatch();
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
try {
if (!ps.getConnection().getAutoCommit()) {
ps.getConnection().commit();
}
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
} finally {
ConnectionUtils.closeAllConnectionsIfPooling(securityDb, ps);
}
// 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 create the project and initialize project security records", e);
}
// need to remove existing insights w/ permissions that do not exist anymore
if (existingInsightPermissions && !insightPermissionIds.isEmpty()) {
classLogger.info("Removing insights with permissions that no longer exist");
String deleteInsightPermissionQuery = "DELETE FROM USERINSIGHTPERMISSION " + "WHERE PROJECTID='"
+ projectId + "'" + " AND INSIGHTID " + createFilter(insightPermissionIds);
try {
securityDb.removeData(deleteInsightPermissionQuery);
securityDb.commit();
} catch (SQLException e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
}
}
classLogger.info("Finished adding project = {}", Utility.cleanLogString(projectId));
}
/**
*
* @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();
String query = "INSERT INTO PROJECT (PROJECTID, PROJECTNAME, TYPE, COST, GLOBAL, DISCOVERABLE, IS_TEMPLATE, CREATEDBY, CREATEDBYTYPE, DATECREATED, DATELASTEDITED, PROJECTDISPLAYNAME) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
try {
QueryExecutionUtility.executeUpdate(securityDb, query, ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, projectId);
ps.setString(parameterIndex++, projectName);
ps.setString(parameterIndex++, projectType);
ps.setString(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()) {
ps.setString(parameterIndex++, projectName);
} else {
ps.setString(parameterIndex++, projectDisplayName);
}
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to create the project and initialize project security records", e);
}
}
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, VISIBILITY, 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.setBoolean(parameterIndex++, true);
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();
String query = "UPDATE PROJECT SET PROJECTNAME=?, TYPE=?, COST=?, GLOBAL=? WHERE PROJECTID=?";
try {
QueryExecutionUtility.executeUpdate(securityDb, query, ps -> {
int parameterIndex = 1;
ps.setString(parameterIndex++, projectName);
ps.setString(parameterIndex++, projectType);
ps.setString(parameterIndex++, projectCost);
ps.setBoolean(parameterIndex++, global);
ps.setString(parameterIndex++, projectID);
});
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
classLogger.error("Failed to update project properties in the security database", e);
}
}
/**
* 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);
}
}
/**
*
* @param projectId
* @return
* @throws Exception
*/
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);
{
boolean error = false;
PreparedStatement insertPs = null;
String iprefix = "INSIGHT__";
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector(iprefix + "INSIGHTID"));
qs.addSelector(new QueryColumnSelector(iprefix + "INSIGHTNAME"));
qs.addSelector(new QueryColumnSelector(iprefix + "LAYOUT"));
qs.addSelector(new QueryColumnSelector(iprefix + "CREATEDON"));
qs.addSelector(new QueryColumnSelector(iprefix + "LASTMODIFIEDON"));
qs.addSelector(new QueryColumnSelector(iprefix + "GLOBAL"));
qs.addSelector(new QueryColumnSelector(iprefix + "CACHEABLE"));
qs.addSelector(new QueryColumnSelector(iprefix + "CACHEMINUTES"));
qs.addSelector(new QueryColumnSelector(iprefix + "CACHECRON"));
qs.addSelector(new QueryColumnSelector(iprefix + "CACHEDON"));
qs.addSelector(new QueryColumnSelector(iprefix + "CACHEENCRYPT"));
qs.addSelector(new QueryColumnSelector(iprefix + "RECIPE"));
qs.addSelector(new QueryColumnSelector(iprefix + "SCHEMANAME"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter(iprefix + "PROJECTID", "==", projectId));
try (IRawSelectWrapper wrapper = WrapperManager.getInstance().getRawWrapper(securityDb, qs)) {
insertPs = admin.getAddInsightPreparedStatement();
while (wrapper.hasNext()) {
Object[] row = wrapper.next().getValues();
int index = 0;
String insightId = (String) row[index++];
String insightName = (String) row[index++];
String insightLayout = (String) row[index++];
SemossDate createdOn = (SemossDate) row[index++];
SemossDate lastModifiedOn = (SemossDate) row[index++];
Boolean global = (Boolean) row[index++];
Boolean cacheable = (Boolean) row[index++];
int cacheMinutes = ((Number) row[index++]).intValue();
String cacheCron = (String) row[index++];
SemossDate sdCachedOn = (SemossDate) row[index++];
LocalDateTime cachedOn = null;
if (sdCachedOn != null) {
cachedOn = sdCachedOn.getLocalDateTime();
}
boolean cacheEncrypt = (Boolean) row[index++];
String pixelRecipe = (String) row[index++];
String schemaName = (String) row[index++];
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", insightId);
continue;
}
admin.batchInsight(insertPs, insightId, insightName, insightLayout, pixelList, global, cacheable,
cacheMinutes, cacheCron, cachedOn, cacheEncrypt, 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(securityDb, 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;
String iprefix = "INSIGHTMETA__";
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector(iprefix + "INSIGHTID"));
qs.addSelector(new QueryColumnSelector(iprefix + "METAKEY"));
qs.addSelector(new QueryColumnSelector(iprefix + "METAVALUE"));
qs.addSelector(new QueryColumnSelector(iprefix + "METAORDER"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter(iprefix + "PROJECTID", "==", projectId));
try (IRawSelectWrapper wrapper = WrapperManager.getInstance().getRawWrapper(securityDb, qs)) {
insertPs = admin.getAddInsightMetaPreparedStatement();
while (wrapper.hasNext()) {
Object[] row = wrapper.next().getValues();
int index = 0;
String insightId = (String) row[index++];
String metaKey = (String) row[index++];
String metaValue = (String) row[index++];
int metaOrder = ((Number) row[index++]).intValue();
admin.batchInsightMetadata(insertPs, insightId, metaKey, metaValue, 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(securityDb, 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;
}
/**
* 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");
}
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);
}
/**
*
* @param projectId
* @return
*/
public static Map<String, Object> getProjectPortalDetailsMap(String projectId) {
Map<String, Object> portalDetails = new HashMap<>();
IProject project = Utility.getProject(projectId);
portalDetails.put("project_is_published", project.isPublished());
String url = Utility.getApplicationUrl() + "/" + Utility.getPublicHomeFolder() + "/" + projectId + "/"
+ Constants.PORTALS_FOLDER + "/";
portalDetails.put("project_portal_url", url);
return portalDetails;
}
/**
* Get markdown for a given project
*
* @param user
* @param projectId
* @return
*/
public static String getProjectMarkdown(User user, String projectId) {
IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb();
SelectQueryStruct qs = new SelectQueryStruct();
qs.addSelector(new QueryColumnSelector("PROJECTMETA__METAVALUE"));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTMETA__METAKEY", "==", Constants.MARKDOWN));
qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTMETA__PROJECTID", "==", projectId));
{
SelectQueryStruct qs1 = new SelectQueryStruct();
qs1.addSelector(new QueryColumnSelector("PROJECT__PROJECTID"));
{
OrQueryFilter orFilter = new OrQueryFilter();
orFilter.addFilter(SimpleQueryFilter.makeColToValFilter("PROJECT__DISCOVERABLE", "==",
Arrays.asList(true, null), PixelDataType.BOOLEAN));
orFilter.addFilter(SimpleQueryFilter.makeColToValFilter("PROJECTPERMISSION__USERID", "==",
getUserFiltersQs(user)));
qs1.addExplicitFilter(orFilter);
}
qs1.addRelation("PROJECT", "PROJECTPERMISSION", "join");
IRelation subQuery = new SubqueryRelationship(qs1, "PROJECT", "join",
new String[] { "PROJECT__PROJECTID", "PROJECTMETA__PROJECTID", "=" });
qs.addRelation(subQuery);
}
return QueryExecutionUtility.flushToString(securityDb, qs);
}