1 package fr.ifremer.adagio.synchro.intercept.internal;
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 import java.sql.SQLException;
27
28 import com.google.common.base.Preconditions;
29
30 import fr.ifremer.adagio.synchro.SynchroTechnicalException;
31 import fr.ifremer.adagio.synchro.dao.SynchroTableDao;
32 import fr.ifremer.adagio.synchro.intercept.SynchroInterceptorBase;
33 import fr.ifremer.adagio.synchro.intercept.SynchroWriteBuffer;
34
35 public class RemoteIdWriteInterceptor extends SynchroInterceptorBase {
36
37 private final String tableName;
38
39 private final int columnIndex;
40
41 private final boolean isNullable;
42
43 public RemoteIdWriteInterceptor(fr.ifremer.adagio.synchro.intercept.SynchroInterceptor next, String tableName, int columnIndex, boolean isNullable) {
44 super(next);
45 Preconditions.checkArgument(columnIndex >= 0);
46 this.tableName = tableName;
47 this.columnIndex = columnIndex;
48 this.isNullable = isNullable;
49 }
50
51 public RemoteIdWriteInterceptor(String tableName, int columnIndex, boolean isNullable) {
52 super();
53 Preconditions.checkArgument(columnIndex >= 0);
54 this.tableName = tableName;
55 this.columnIndex = columnIndex;
56 this.isNullable = isNullable;
57 }
58
59 protected void doOnWrite(Object[] data, SynchroTableDao dao, SynchroWriteBuffer buffer) throws SQLException {
60 Integer remoteId = (Integer) data[columnIndex];
61 if (remoteId == null) {
62 return;
63 }
64
65 Integer localId = dao.getIdFromRemoteId(tableName, remoteId);
66 if (localId == null) {
67
68 if (!isNullable) {
69 throw new SynchroTechnicalException(String.format("Could not retrieve ID corresponding to REMOTE_ID=%s, for table %s",
70 remoteId, tableName));
71 }
72
73
74 buffer.addMissingRemoteId(tableName, columnIndex, null, remoteId);
75 data[columnIndex] = null;
76 }
77 else {
78 data[columnIndex] = localId;
79 }
80 }
81
82 @Override
83 public boolean enableOnWrite() {
84 return true;
85 }
86 }