-
Notifications
You must be signed in to change notification settings - Fork 591
/
InterfaceWrapperHelper.java
1787 lines (1614 loc) · 56.6 KB
/
InterfaceWrapperHelper.java
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
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2020 metas GmbH
* %%
* 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.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package org.adempiere.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import de.metas.cache.model.IModelCacheService;
import de.metas.error.AdIssueId;
import de.metas.error.IErrorManager;
import de.metas.i18n.IModelTranslationMap;
import de.metas.i18n.impl.NullModelTranslationMap;
import de.metas.logging.LogManager;
import de.metas.organization.OrgId;
import de.metas.util.Check;
import de.metas.util.GuavaCollectors;
import de.metas.util.NumberUtils;
import de.metas.util.Services;
import de.metas.util.StringUtils;
import de.metas.util.lang.RepoIdAware;
import de.metas.util.lang.RepoIdAwares;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import org.adempiere.ad.column.AdColumnId;
import org.adempiere.ad.model.util.IModelCopyHelper;
import org.adempiere.ad.model.util.ModelCopyHelper;
import org.adempiere.ad.persistence.IModelClassInfo;
import org.adempiere.ad.persistence.IModelInternalAccessor;
import org.adempiere.ad.persistence.ModelClassIntrospector;
import org.adempiere.ad.persistence.ModelDynAttributeAccessor;
import org.adempiere.ad.table.api.AdTableId;
import org.adempiere.ad.table.api.impl.TableIdsCache;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.ad.trx.api.ITrxManager;
import org.adempiere.ad.trx.api.OnTrxMissingPolicy;
import org.adempiere.ad.wrapper.CompositeInterfaceWrapperHelper;
import org.adempiere.ad.wrapper.GridTabInterfaceWrapperHelper;
import org.adempiere.ad.wrapper.IInterfaceWrapperHelper;
import org.adempiere.ad.wrapper.POInterfaceWrapperHelper;
import org.adempiere.ad.wrapper.POJOInterfaceWrapperHelper;
import org.adempiere.ad.wrapper.POJOLookupMap;
import org.adempiere.ad.wrapper.POJOWrapper;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.service.ClientId;
import org.adempiere.util.lang.IContextAware;
import org.adempiere.util.lang.ITableRecordReference;
import org.apache.poi.ss.formula.functions.T;
import org.compiere.Adempiere;
import org.compiere.model.GridField;
import org.compiere.model.GridTab;
import org.compiere.model.PO;
import org.compiere.model.POInfo;
import org.compiere.util.Env;
import org.compiere.util.Evaluatee;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* This class is heavily used throughout metasfresh. To understand what it's all about see the javadoc of {@link #create(Object, Class)}.
* It internally relates on a {@link CompositeInterfaceWrapperHelper} which in turn supports all the types that are supported by this class.
*
* @author metas-dev <dev@metasfresh.com>
*/
@UtilityClass
public class InterfaceWrapperHelper
{
private static final Logger logger = LogManager.getLogger(InterfaceWrapperHelper.class);
private static final CompositeInterfaceWrapperHelper helpers = new CompositeInterfaceWrapperHelper()
.addFactory(new POInterfaceWrapperHelper())
.addFactory(new GridTabInterfaceWrapperHelper())
.addFactory(new POJOInterfaceWrapperHelper());
public static final String COLUMNNAME_IsActive = "IsActive";
public static final String COLUMNNAME_Value = "Value";
public static final String COLUMNNAME_Name = "Name";
public static final String COLUMNNAME_DocumentNo = "DocumentNo";
public static final String COLUMNNAME_Description = "Description";
public static final String COLUMNNAME_Created = "Created";
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
public static final String COLUMNNAME_Updated = "Updated";
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
private static POJOLookupMap getInMemoryDatabaseForModel(final Class<?> modelClass)
{
return POJOLookupMap.getInMemoryDatabaseForModel(modelClass);
}
private static POJOLookupMap getInMemoryDatabaseForTableName(final String tableName)
{
return POJOLookupMap.getInMemoryDatabaseForTableName(tableName);
}
private static boolean isInMemoryDatabaseOnly()
{
return org.compiere.Adempiere.isUnitTestMode();
}
public static void registerHelper(final IInterfaceWrapperHelper helper)
{
helpers.addFactory(helper);
}
/**
* Creates a new instance of given object using same context and trxName as <code>contextProvider</code>.
* <p>
* <b>IMPORTANT:</b> if the given contextProvider has the trxName <code>null</code>, then the new instance's trxName will be {@link ITrx#TRXNAME_ThreadInherited}!
* <p>
* The method invokes {@link #newInstance(Class, Object, boolean)} with <code>useCLientOrgFromProvider = true</code>.
* <p>
*
* @param contextProvider any object that carries a context (e.g. a PO, a wrapped PO, GridTab, a wrapped GridTab etc)
* @return new instance
*/
public static <T> T newInstance(final Class<T> cl, final Object contextProvider)
{
return newInstance(cl, contextProvider, true); // useClientOrgFromProvider = true
}
/**
* Creates a new instance of the given object using same context and trxName as <code>contextProvider</code>
*
* @param contextProvider any object that carries a context (e.g. a PO, a wrapped PO, GridTab, a wrapped GridTab etc)<br>
* <p>
* IMPORTANT:</b> If contextProvider's transaction name is NULL and we have a thread inherited transaction, then use that one,
* <i>if</i> the given <code>contextProvider</code> permits it. See {@link IContextAware#isAllowThreadInherited()}.
* @param useClientOrgFromProvider if {@code true}, then the context used to create the new instance will have the {@code contextProvider}'s {@code AD_Client_ID} and {@code AD_Org_ID} as
* {@code #AD_Client_ID} resp. {@code #clone().AD_Org_ID}.
* @return new instance
*/
public static <T> T newInstance(final Class<T> cl,
@NonNull final Object contextProvider,
final boolean useClientOrgFromProvider)
{
final Properties ctx = getCtx(contextProvider, useClientOrgFromProvider);
//
// Get transaction name from contextProvider.
// If contextProvider's transaction name is NULL and we have a thread inherited transaction, then let's use that one
final ITrxManager trxManager = getTrxManager();
String trxName = getTrxName(contextProvider);
if (trxManager.isNull(trxName))
{
final IContextAware ctxAware = InterfaceWrapperHelper.getContextAware(contextProvider);
if (ctxAware.isAllowThreadInherited()) // it's ok to check and if there is a thread inherited trx, use that.
{
final ITrx trxThreadInherited = trxManager.get(ITrx.TRXNAME_ThreadInherited, OnTrxMissingPolicy.ReturnTrxNone);
if (trxThreadInherited != null)
{
trxName = ITrx.TRXNAME_ThreadInherited;
}
}
}
return create(ctx, cl, trxName);
}
/**
* Convenient method to create a new instance of given class, using current context and current transaction.
*/
public static <T> T newInstance(final Class<T> modelClass)
{
final Properties ctx = Env.getCtx();
final String trxName = ITrx.TRXNAME_ThreadInherited;
return create(ctx, modelClass, trxName);
}
/**
* Convenient method to create a new instance of given class, using current context and no transaction.
*/
public static <T> T newInstanceOutOfTrx(final Class<T> modelClass)
{
final Properties ctx = Env.getCtx();
final String trxName = ITrx.TRXNAME_None;
return create(ctx, modelClass, trxName);
}
/**
* This method is heavily used throughout metasfresh and allows us to do the following things:
* <ul>
* <li>Create interfaces from {@link GridTab}s (see {@link GridTabWrapper}), {@link PO}'s (see {@link POWrapper}) and POJOs (see {@link POWrapper}).<br>
* This way, a developer can create business logic that deals with e.g. <code>I_C_Order</code>s and does not have to care whether the actual underlying project is a <code>GridTab</code> or a <code>PO</code>.<br>
* She can therefore for example create one method that makes some validations and call that method from both a callout and a model interceptor/validator.<br>
* In both cases this method can create the required interface from the underlying <code>GridTab</code> or <code>PO</code> instance</li>
* <li>Logically separate columns and fields that belong to different modules.<br>
* An example: we have one module/project for handling units and another one for EDI. Both of them "own" different columns of the <code>C_OrderLine</code> table,<br>
* but they do not have a functional relationship (I doubt it, but let's say so for the sake of argument).<br>
* The goal is to avoid mixing the model definition and business logic. To achieve this, we have two different project specific <code>I_C_OrderLine</code> interfaces.<br>
* One interface is in the handling units project, where we declare the HU-related columns, getters and setters, and the other interface is in the EDI project, where we declare the EDI-related column names, getters and setters.<br>
* Both interfaces extend the "original" <code>org.compiere.model.I_C_OrderLine</code> interface, so they have the generic properties like <code>QtyOrdered</code>, <code>M_Product_ID</code> etc. <b>plus</b> the project specific ones.<br>
* The magic is once again done by this method, which returns an instance of the required <code>I_C_OrderLine</code> interface for the underlying <code>GridTab</code> or <code>PO</code>,
* with only the properties that are declared by that interface.<br>
* Also note that the interface passed to {@link InterfaceWrapperHelper#create(Object, Class, boolean)} does not necessarily have to implement a "generic" interface from <code>org.compiere.model</code>.<br>
* Instead, we can also use some interface like <code>IProductAware</code> that just declares product related properties.
* </li>
* </ul>
*
* @param model the underlying {@link PO}, {@link GridTab} or POJO for which we need an instance of <code>cl</code>
* @param cl the interface we need an instance of
* @return an instance of <code>cl</code> which actually wraps <code>model</code> or <code>null</code> if model was <code>null</code>
*/
public static <T> T create(@Nullable final Object model, final Class<T> cl)
{
final boolean useOldValues = false;
return create(model, cl, useOldValues);
}
/**
* See {@link #create(Object, Class)} for additional infos.
*
* @param modelClass model class
* @param useOldValues <ul>
* <li>true if old values shall be used
* <li>false if model's old values flag shall BE PRESERVED. i.e. if it was "true" we shall use old values, if it was "false" we shall NOT use old values.
* </ul>
* @deprecated Because this method is tricky and we consider to make it private, please use:
* <ul>
* <li>{@link #create(Object, Class)}
* <li>or {@link #createOld(Object, Class)}
* </ul>
*/
@Deprecated
public static <T> T create(
@Nullable final Object model,
@NonNull final Class<T> modelClass,
final boolean useOldValues)
{
if (model == null)
{
return null;
}
else if (modelClass.isInstance(model) && !useOldValues)
{
@SuppressWarnings("unchecked") final T modelCasted = (T)model;
return modelCasted;
}
else
{
return helpers.wrap(model, modelClass, useOldValues);
}
}
/**
* Wraps given the <code>model</code> and uses the <b>old</b> values for all model getters.
* See {@link #create(Object, Class)} for more informations.
*/
public static <T> T createOld(final T model, final Class<T> cl)
{
final boolean useOldValues = true;
return create(model, cl, useOldValues);
}
public static <T> T create(final Properties ctx, final Class<T> cl, @Nullable final String trxName)
{
if (getInMemoryDatabaseForModel(cl) != null)
{
return POJOWrapper.create(ctx, cl, trxName);
}
return POWrapper.create(ctx, cl, trxName);
}
/**
* Loads the record with the given <code>id</code>.
* Also see {@link #create(Object, Class)} for more informations.
* <p>
* Note: if you want to load a record from <code>(AD_Table_ID, Reference_ID)</code>,<br>
* then it's probably better to use e.g. {@link org.adempiere.util.lang.impl.TableRecordReference#of(int, int)}.
*/
public static <T> T create(final Properties ctx, final int id, @NonNull final Class<T> cl, @Nullable final String trxName)
{
if (getInMemoryDatabaseForModel(cl) != null)
{
return POJOWrapper.create(ctx, id, cl, trxName);
}
return POWrapper.create(ctx, id, cl, trxName);
}
/**
* Loads the record with the given <code>id</code>. Similar to {@link #create(Properties, int, Class, String)}, but explicitly specifies the table name.<br>
* This is useful in case the table name can't be deduced from the given <code>cl</code>.
* <p>
* Notes:
* <li>this method might or might not benefit from caching, depending on how {@link IModelCacheService} was configured.
* <li>if you want to load a record from <code>(AD_Table_ID, Reference_ID)</code>,<br>
* then it's probably better to use {@link org.adempiere.util.lang.impl.TableRecordReference#of(int, int)}.
*/
public static <T> T create(final Properties ctx, final String tableName, final int id, final Class<T> cl, final String trxName)
{
if (getInMemoryDatabaseForTableName(tableName) != null)
{
return POJOWrapper.create(ctx, tableName, id, cl, trxName);
}
return POWrapper.create(ctx, tableName, id, cl, trxName);
}
public static <T> T loadOutOfTrx(@NonNull final RepoIdAware id, final Class<T> modelClass)
{
return loadOutOfTrx(id.getRepoId(), modelClass);
}
/**
* Loads given model, out of transaction.
* NOTE: to be used, mainly for loading master data models.
* NOTE: when we are where we want to be, this will only be invoked from repositories!
*
* @param id model's ID
* @return loaded model
*/
public static <T> T loadOutOfTrx(final int id, final Class<T> modelClass)
{
return create(Env.getCtx(), id, modelClass, ITrx.TRXNAME_None);
}
public static <T> T load(@NonNull final RepoIdAware id, @NonNull final Class<T> modelClass)
{
return load(id.getRepoId(), modelClass);
}
public static <T> T loadNotNull(@NonNull final RepoIdAware id, @NonNull final Class<T> modelClass)
{
final T record = load(id, modelClass);
if (record == null)
{
throw new AdempiereException("No " + modelClass.getSimpleName() + " found for " + id);
}
return record;
}
/**
* Loads given model, using thread inherited transaction.
*
* @param id model's ID
* @return loaded model
*/
public static <T> T load(final int id, @NonNull final Class<T> modelClass)
{
return create(Env.getCtx(), id, modelClass, ITrx.TRXNAME_ThreadInherited);
}
public static <T> T loadOrNew(@Nullable final RepoIdAware id, final Class<T> modelClass)
{
return id == null ? newInstance(modelClass) : load(id.getRepoId(), modelClass);
}
@Deprecated
public static <T> T loadOrNew(@Nullable final RepoIdAware id, final Class<T> modelClass, final Object contextProvider)
{
return id == null ? newInstance(modelClass, contextProvider) : load(id.getRepoId(), modelClass);
}
public static <T> List<T> loadByIds(final Set<Integer> ids, final Class<T> modelClass)
{
return loadByIds(ids, modelClass, ITrx.TRXNAME_ThreadInherited, UnaryOperator.identity());
}
public static <T> List<T> loadByRepoIdAwares(@NonNull final Set<? extends RepoIdAware> repoIdAwares, final Class<T> modelClass)
{
final ImmutableSet<Integer> ids = RepoIdAwares.asRepoIdsSet(repoIdAwares);
return loadByIds(ids, modelClass, ITrx.TRXNAME_ThreadInherited, UnaryOperator.identity());
}
public static <RT, MT> List<MT> loadByRepoIdAwares(@NonNull final Set<? extends RepoIdAware> repoIdAwares, @NonNull final Class<RT> modelClass, @NonNull Function<RT, MT> modelMapper)
{
final ImmutableSet<Integer> ids = RepoIdAwares.asRepoIdsSet(repoIdAwares);
return loadByIds(ids, modelClass, ITrx.TRXNAME_ThreadInherited, modelMapper);
}
public static <T> List<T> loadByIdsOutOfTrx(final Set<Integer> ids, final Class<T> modelClass)
{
return loadByIds(ids, modelClass, ITrx.TRXNAME_None, UnaryOperator.identity());
}
public static <T> List<T> loadByRepoIdAwaresOutOfTrx(@NonNull final Collection<? extends RepoIdAware> repoIdAwares, final Class<T> modelClass)
{
final ImmutableSet<Integer> ids = RepoIdAwares.asRepoIdsSet(repoIdAwares);
return loadByIds(ids, modelClass, ITrx.TRXNAME_None, UnaryOperator.identity());
}
private static <RT, MT> List<MT> loadByIds(final Set<Integer> ids, final Class<RT> modelClass, final String trxName, final Function<RT, MT> modelMapper)
{
if (getInMemoryDatabaseForModel(modelClass) != null)
{
return POJOWrapper.loadByIds(ids, modelClass, trxName, modelMapper);
}
return POWrapper.loadByIds(ids, modelClass, trxName, modelMapper);
}
/**
* Converts given list to target type by calling {@link #create(Object, Class)} for each item.
*
* @param list list to be converted
* @param clazz target model class
* @return converted list to given model
*/
public static <T, S> List<T> createList(final List<S> list, final Class<T> clazz)
{
if (list == null)
{
return null;
}
return list.stream()
.map(item -> create(item, clazz))
.collect(Collectors.toList());
}
public static <T, S> List<T> wrapToImmutableList(final List<S> list, final Class<T> clazz)
{
if (list == null || list.isEmpty())
{
return ImmutableList.of();
}
return list.stream()
.map(model -> create(model, clazz))
.collect(GuavaCollectors.toImmutableList());
}
public static void refresh(final Object model)
{
final boolean discardChanges = false;
refresh(model, discardChanges);
}
/**
* Refresh all models that were given using {@link #refresh(Object)}.
* <p>
* NOTE: developers are encouraged to use this method because here we would be able to do more optimizations.
*/
public static <T> void refreshAll(final Iterable<T> models)
{
if (models == null)
{
return;
}
for (final Object model : models)
{
refresh(model);
}
}
/**
* Like {@link #refreshAll(Iterable)}, but uses {@link #refresh(Object, String)} instead.
*/
public static <T> void refreshAll(final Iterable<T> models, final String trxName)
{
if (models == null)
{
return;
}
for (final Object model : models)
{
refresh(model, trxName);
}
}
/**
* Mark the model as staled. It means that it needs to be reloaded first in case some values need to be retrieved.
* <p>
* NOTE: this method is currently refreshing the model right away, because we did not implement it.
*/
public static void markStaled(final Object model)
{
// TODO: we need to implement it
refresh(model);
}
/**
* Reload given model from database.
*
* @param discardChanges hint for actual handler to tell that if there are any unsaved changes, it's ok to discard them.
*/
public static void refresh(final Object model, final boolean discardChanges)
{
helpers.refresh(model, discardChanges);
}
/**
* Refreshes the given model, and if the model is handled by {@link POWrapper} or {@link POJOWrapper}, then uses the given <code>trxName</code>.
*/
public static void refresh(final Object model, final String trxName)
{
helpers.refresh(model, trxName);
}
public static void setTrxName(final Object model, @Nullable final String trxName)
{
final boolean ignoreIfNotHandled = false;
setTrxName(model, trxName, ignoreIfNotHandled);
}
/**
* @param model
* @param trxName
* @param ignoreIfNotHandled <code>true</code> and the given model can not be handled (no PO, GridTab etc), then don't throw an exception,
* @throws AdempiereException if the given model is neither handled by {@link POWrapper} nor by {@link POJOWrapper} and ignoreIfNotHandled is <code>false</code>.
*/
public static void setTrxName(final Object model, final String trxName, final boolean ignoreIfNotHandled)
{
helpers.setTrxName(model, trxName, ignoreIfNotHandled);
}
private static ITrxManager getTrxManager()
{
// TODO: consider using as a class field because this method is/will accessed many times
return Services.get(ITrxManager.class);
}
/**
* Sets trxName to {@link ITrx#TRXNAME_ThreadInherited}.
*/
public static void setThreadInheritedTrxName(final Object model)
{
setTrxName(model, ITrx.TRXNAME_ThreadInherited);
}
/**
* Set current thread inerited transaction name to given models.
*/
public static void setThreadInheritedTrxName(final Collection<?> models)
{
if (models == null || models.isEmpty())
{
return;
}
for (final Object model : models)
{
setTrxName(model, ITrx.TRXNAME_ThreadInherited);
}
}
public static void saveAll(@NonNull final Collection<?> models)
{
if (models.isEmpty())
{
return;
}
models.forEach(InterfaceWrapperHelper::saveRecord);
}
/**
* Does the same as {@link #save(Object)},
* but this method can be static-imported into repository implementations which usually have their own method named "save()".
*/
public static void saveRecord(final Object model)
{
save(model);
}
public static void save(final Object model)
{
final Object modelToSave = extractModelToSave(model);
if (modelToSave == null)
{
final AdempiereException ex = new AdempiereException("Saving null model ignored. Possible development issue. Ignored.");
logger.warn(ex.getLocalizedMessage(), ex);
}
else if (GridTabWrapper.isHandled(modelToSave))
{
GridTabWrapper.save(modelToSave);
}
else if (POWrapper.isHandled(modelToSave))
{
POWrapper.save(modelToSave);
}
else if (POJOWrapper.isHandled(modelToSave))
{
POJOWrapper.save(modelToSave);
}
else
{
final AdempiereException ex = new AdempiereException("Model not handled: " + modelToSave + "(class=" + modelToSave.getClass() + "). Ignored.");
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(ex);
logger.warn("Could not save the given model; message={}; AD_Issue_ID={}", ex.getLocalizedMessage(), issueId);
}
}
public static void setCtx(@NonNull final Object model, @NonNull final Properties ctx)
{
if (POWrapper.isHandled(model))
{
POWrapper.setCtx(model, ctx);
}
else if (POJOWrapper.isHandled(model))
{
POJOWrapper.setCtx(model, ctx);
}
else
{
final AdempiereException ex = new AdempiereException("Model not handled: " + model + "(class=" + model.getClass() + "). Ignored.");
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(ex);
logger.warn("Could not set ctx to given model; message={}; AD_Issue_ID={}", ex.getLocalizedMessage(), issueId);
}
}
private static Object extractModelToSave(final Object model)
{
final Object modelToSave;
if (model instanceof IModelWrapper)
{
modelToSave = ((IModelWrapper)model).getModel();
}
else
{
modelToSave = model;
}
return modelToSave;
}
public static void save(final Object model, @Nullable final String trxName)
{
if (model == null)
{
final AdempiereException ex = new AdempiereException("Saving null model ignored. Possible development issue. Ignored.");
logger.warn(ex.getLocalizedMessage(), ex);
}
final String trxNameOld = getTrxName(model);
setTrxName(model, trxName);
try
{
save(model);
}
finally
{
// Restore the trxName
setTrxName(model, trxNameOld);
}
}
/**
* Get context from model.
*/
public static Properties getCtx(@Nullable final Object model)
{
return getCtx(model, false);
}
/**
* Get context from model and setting in context AD_Client_ID and AD_Org_ID according to the model if useClientOrgFromModel is true
*
* @param model may be null
* @param useClientOrgFromModel ignored, unless the given model is {@link ModelContextAware} or just a "normal" model.
*/
public static Properties getCtx(
@Nullable final Object model,
final boolean useClientOrgFromModel)
{
if (model == null)
{
return Env.getCtx();
}
else if (model instanceof ModelContextAware)
{
// we have an IContextAware that is based on a model, so we can act on the value of the given useClientOrgFromModel
return ((ModelContextAware)model).getCtx(useClientOrgFromModel);
}
else if (model instanceof IContextAware)
{
return ((IContextAware)model).getCtx();
}
else if (model instanceof Properties)
{
return (Properties)model; // this *is* already the ctx
}
else
{
return helpers.getCtx(model, useClientOrgFromModel);
}
}
/**
* IMPORTANT: only call with <b>model interfaces</b> such as {@code I_AD_Table}, {@code C_Order} (legacy classes like `MProduct` and {@link IContextAware}s will also work) and the like.
* Despite the parameter type being "Object" it does not work with all objects.
*/
public static String getTrxName(@Nullable final Object model)
{
final boolean ignoreIfNotHandled = false;
return getTrxName(model, ignoreIfNotHandled);
}
/**
* IMPORTANT: only call with <b>model interfaces</b> such as {@code I_AD_Table}, {@code C_Order} (legacy classes like `MProduct` and {@link IContextAware}s will also work) and the like.
* Despite the parameter type being "Object" it does not work with all objects.
*
* @param ignoreIfNotHandled if <code>true</code> and the given model can not be handeled (no PO, GridTab etc), then just return {@link ITrx#TRXNAME_None} without throwing an exception.
*/
@Nullable
public static String getTrxName(@Nullable final Object model, final boolean ignoreIfNotHandled)
{
if (model == null)
{
return ITrx.TRXNAME_None;
}
else if (model instanceof IContextAware)
{
return ((IContextAware)model).getTrxName();
}
else if (model instanceof Properties)
{
return ITrx.TRXNAME_None;
}
else
{
return helpers.getTrxName(model, ignoreIfNotHandled);
}
}
public static IContextAware getContextAware(final Object model)
{
if (model instanceof IContextAware)
{
return (IContextAware)model;
}
else
{
return new ModelContextAware(model);
}
}
/**
* Does the same as {@link #delete(Object)},
* but this method can be static-imported into repository implementations which usually have their own method named "delete()".
*/
public static void deleteRecord(@NonNull final Object model)
{
delete(model);
}
public static void delete(@NonNull final Object model)
{
final boolean failIfProcessed = true;
delete(model, failIfProcessed);
}
public static void delete(@NonNull final Object model, final boolean failIfProcessed)
{
if (POWrapper.isHandled(model))
{
POWrapper.delete(model, failIfProcessed);
}
else if (POJOWrapper.isHandled(model))
{
POJOWrapper.delete(model, failIfProcessed);
}
else
{
throw new IllegalStateException("delete is not supported for " + model);
}
}
public static void deleteAll(@NonNull final Collection<?> models, final boolean failIfProcessed)
{
if (models.isEmpty())
{
return;
}
models.forEach(model -> InterfaceWrapperHelper.delete(model, failIfProcessed));
}
public static void deleteAll(@NonNull final Collection<?> models)
{
if (models.isEmpty())
{
return;
}
models.forEach(InterfaceWrapperHelper::delete);
}
/**
* @return underlying {@link PO} or null
*/
public static <T extends PO> T getPO(final Object model)
{
final boolean strict = false;
return helpers.getPO(model, strict);
}
public static <T extends PO> T getStrictPO(final Object model)
{
final boolean strict = true;
return helpers.getPO(model, strict);
}
public static int getId(@Nullable final Object model)
{
if (model == null)
{
return -1;
}
else if (model instanceof ITableRecordReference)
{
return ((ITableRecordReference)model).getRecord_ID();
}
else
{
return helpers.getId(model);
}
}
public static boolean isActive(@NonNull final Object model)
{
final boolean throwExIfColumnNotFound = false;
final boolean useOverrideColumnIfAvailable = false;
final Object valueObj = getValue(model, COLUMNNAME_IsActive, throwExIfColumnNotFound, useOverrideColumnIfAvailable);
return StringUtils.toBoolean(valueObj);
}
/**
* Introducing this exception to be thrown instead of ADempiereException. Reason: It's a pain if you have a breakpoint on "AdempiereException" and the debugger stops every 2 seconds because
* InterfaceWrapperHelper throws it.
*/
/* package */
static class MissingTableNameException extends AdempiereException
{
private static MissingTableNameException notFound(final Class<?> modelClass)
{
return new MissingTableNameException("@NotFound@ @TableName@ (class=" + modelClass + ")");
}
private static MissingTableNameException notFound(final Class<?> modelClass, final String fallbackTableName)
{
return new MissingTableNameException("@NotFound@ @TableName@ (class=" + modelClass + ", fallbackTableName=" + fallbackTableName + ")");
}
private static MissingTableNameException notMatching(final Class<?> modelClass, final String modelClassTableName, final String expectedTableName)
{
return new MissingTableNameException("modelClass's table name is not matching the expected table name:"
+ "\n modelClass=" + modelClass
+ "\n modelClassTableName=" + modelClassTableName
+ "\n expectedTableName=" + expectedTableName);
}
private MissingTableNameException(final String message)
{
super(message);
}
}
private static IModelClassInfo getModelClassInfoOrNull(@Nullable final Class<?> clazz)
{
return ModelClassIntrospector
.getInstance()
.getModelClassInfo(clazz);
}
/**
* Checks static variable "Table_Name" of given interface and returns it's content.
*
* @return tableName associated with given interface
* @throws AdempiereException if "Table_Name" static variable is not defined or is not accessible
*/
@NonNull
public static String getTableName(final Class<?> modelClass) throws AdempiereException
{
final String modelClassTableName = getTableNameOrNull(modelClass);
if (modelClassTableName == null)
{
throw MissingTableNameException.notFound(modelClass);
}
return modelClassTableName;
}
/**
* Checks static variable "Table_Name" of given interface and returns it's content.
*
* @return tableName associated with given interface or null if interface has no Table_Name
*/
public static String getTableNameOrNull(final Class<?> clazz)
{
final IModelClassInfo modelClassInfo = getModelClassInfoOrNull(clazz);
if (modelClassInfo == null)
{
return null;
}
return modelClassInfo.getTableName();
}
/**
* Extracts the table name from given modelClass.
* If the modelClass does not have a table name it will return <code>expectedTableName</code> if that's not null.
* If the modelClass has a table name but it's not matching the expectedTableName (if not null) an exception will be thrown.
* If the modelClass does not hava a table name and <code>expectedTableName</code> is null an exception will be thrown.
*
* @return model table name; never returns null
*/
public static String getTableName(final Class<?> modelClass, @Nullable final String expectedTableName)
{
final String modelClassTableName = getTableNameOrNull(modelClass);
// Case: there is no expected/default table name
// => fail if modelClass has no table name either.
if (expectedTableName == null)
{
if (modelClassTableName == null)
{
throw MissingTableNameException.notFound(modelClass, expectedTableName);
}
return modelClassTableName;
}
// Case: there is an expected/default table name
else
{
// Sub-case: no model class table name => return the default/expected one
if (modelClassTableName == null)
{
return expectedTableName;
}
// Sub-case: model class table name matches the expected one => perfect, return it
else if (modelClassTableName.equals(expectedTableName))
{
return modelClassTableName;
}
// Sub-case: model class table name DOES NOT match the expected one => fail
else
{
throw MissingTableNameException.notMatching(modelClass, modelClassTableName, expectedTableName);
}
}
}
public static boolean isModelInterface(@Nullable final Class<?> modelClass)
{
if (modelClass == null)
{
return false;
}
final IModelClassInfo modelClassInfo = getModelClassInfoOrNull(modelClass);
if (modelClassInfo == null)
{
return false;
}
return modelClassInfo.getTableName() != null;
}
public static int getTableId(@NonNull final Class<?> clazz)
{
final String tableName = getTableName(clazz);
return TableIdsCache.instance.getTableId(tableName)
.map(AdTableId::getRepoId)
.orElse(-1);
}
public static AdTableId getAdTableId(@NonNull final Class<?> clazz)
{
final String tableName = getTableName(clazz);
return TableIdsCache.instance.getTableId(tableName)
.orElseThrow(() -> new AdempiereException("No AD_Table_ID found for " + tableName));
}
/**
* @return AD_Table_ID or <code>-1</code>.
*/
public static int getTableIdOrNull(final Class<?> clazz)
{
final String tableName = getTableNameOrNull(clazz);
if (tableName == null)
{
return -1;
}