aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/cacher/common/MongoHelperSingleton.java
blob: 63638f14668c06bdcda345a180ba4ff373f504b6 (plain)
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
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.cacher.common;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.mongodb.*;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.DBCollectionUpdateOptions;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.onap.aai.cacher.model.CacheEntry;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Creates and returns a mongo instance
 */

@Component
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MongoHelperSingleton {

    private final static EELFLogger EELF_LOGGER = EELFManager.getInstance().getLogger(MongoHelperSingleton.class);

    private DB db;

    private MongoDatabase mongoDatabase;

    @Autowired
    public MongoHelperSingleton(DB db, MongoDatabase mongoDatabase) {
        this.mongoDatabase = mongoDatabase;
        this.db = db;
    }

    public DB getDb() {
        return db;
    }

    public void createCollection(String name) {
        try {
            db.getCollection(name);
            EELF_LOGGER.info("Collection " + name + " created successfully");
        } catch (Exception e) {
            AAIException aaiException = new AAIException("AAI_4000");
            ErrorLogHelper.logException(aaiException);
        }
    }

    public boolean addToMongo(String collectionName, Object document) {
        try {
            DBCollection collection = db.getCollection(collectionName);
            WriteResult result;
            if (document instanceof List) {
                result = collection.insert((List<BasicDBObject>) document);
                return result.wasAcknowledged();
            } else if (document instanceof BasicDBObject) {
                result = collection.insert((BasicDBObject) document);
                return result.wasAcknowledged();
            } else {
                EELF_LOGGER.error("The cachekey object to add was of unknown type");
                return false;
            }
        } catch (MongoException ex) {
            AAIException aaiException = new AAIException("AAI_5105");
            ErrorLogHelper.logException(aaiException);
            return false;
        } catch (Exception e) {
            AAIException aaiException = new AAIException("AAI_4000");
            ErrorLogHelper.logException(aaiException);
            return false;
        }
    }

    public boolean updateInMongo(String collectionName, BasicDBObject searchQuery, Object document,
            DBCollectionUpdateOptions updateOptions) {
        try {
            DBCollection collection = db.getCollection(collectionName);
            WriteResult result;
            result = collection.update(searchQuery, (BasicDBObject) document, updateOptions);
            return result.wasAcknowledged();
        } catch (MongoException ex) {
            AAIException aaiException = new AAIException("AAI_5105");
            ErrorLogHelper.logException(aaiException);
            return false;
        } catch (Exception e) {
            AAIException aaiException = new AAIException("AAI_4000");
            ErrorLogHelper.logException(aaiException);
            return false;
        }
    }

    public String deleteFromMongo(String collectionName, Map<String, String> whereClause) {
        DBCollection collection = db.getCollection(collectionName);
        DBObject searchQuery = new BasicDBObject();
        for (Map.Entry<String, String> entry : whereClause.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            searchQuery.put(key, value);
        }
        try {
            WriteResult result = collection.remove(searchQuery);
            if (result.getN() > 0) {
                return "DELETED";
            } else {
                return "NOT_FOUND";
            }
        } catch (MongoException ex) {
            AAIException aaiException = new AAIException("AAI_5105");
            ErrorLogHelper.logException(aaiException);
            return "EXCEPTION_THROWN";
        }
    }

    public void dropCollection(String collectionName) {
        db.getCollection(collectionName).drop();
    }

    public Response buildResponse(Status status, String result) {
        return Response.status(status).type(MediaType.APPLICATION_JSON).entity(result).build();
    }

    public Response buildExceptionResponse(AAIException aaiException) {
        ErrorLogHelper.logException(aaiException);
        return Response.status(aaiException.getErrorObject().getHTTPResponseCode())
                .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(
                        Lists.newArrayList(MediaType.APPLICATION_JSON_TYPE), aaiException, new ArrayList<>()))
                .build();
    }

    public boolean insertReplace(CacheEntry cacheEntry) {
        MongoCollection<Document> collection = mongoDatabase.getCollection(cacheEntry.getCollection());

        Document findQuery = Document.parse(cacheEntry.getFindQuery().toString());
        Document payload = Document.parse(cacheEntry.getPayload().toString());

        if (!cacheEntry.isNested()) {
            UpdateResult updateResult = collection.replaceOne(findQuery, payload, new UpdateOptions().upsert(true));

            return updateResult.wasAcknowledged();
        } else {
            CacheEntry localCacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry().deepCopy(cacheEntry).build();
            Document nestedFind = Document.parse(localCacheEntry.getNestedFind().toString());

            // if exists remove
            if (collection.count(nestedFind) > 0L) {
                mongoPull(localCacheEntry, collection, nestedFind);
            }

            ArrayList<Document> filters = this.getFiltersAndUpdateNestedField(localCacheEntry);
            Document doc = new Document();
            doc.put(localCacheEntry.getNestedField(), payload);
            Document push = new Document();
            push.put("$push", doc);

            collection.findOneAndUpdate(findQuery, push,
                    new FindOneAndUpdateOptions().arrayFilters(filters).upsert(true));

            return collection.count(nestedFind) > 0L;
        }
    }

    public boolean delete(CacheEntry cacheEntry) {

        MongoCollection<Document> collection = mongoDatabase.getCollection(cacheEntry.getCollection());

        Document findQuery = Document.parse(cacheEntry.getFindQuery().toString());

        if (!cacheEntry.isNested()) {
            if (collection.count(findQuery) == 0L) {
                return true;
            }
            DeleteResult deleteResult = collection.deleteOne(findQuery);
            return deleteResult.wasAcknowledged();

        } else {
            Document nestedFind = Document.parse(cacheEntry.getNestedFind().toString());
            if (collection.count(nestedFind) == 0L) {
                return true;
            }

            mongoPull(cacheEntry, collection, nestedFind);
            return collection.count(nestedFind) == 0L;

        }
    }

    public Optional<Document> getObject(CacheEntry cacheEntry) {
        MongoCollection<Document> collection = mongoDatabase.getCollection(cacheEntry.getCollection());
        Document resultingObject;

        if (!cacheEntry.isNested()) {
            resultingObject = collection.find(Document.parse(cacheEntry.getFindQuery().toString())).first();
        } else {
            List<Document> aggregate = getAggregateFromFind(cacheEntry.getNestedFind());
            AggregateIterable<Document> aggregateResult = collection.aggregate(aggregate);
            resultingObject = aggregateResult.first();
            if (resultingObject != null) {
                resultingObject = (Document) (resultingObject.get("output"));
            }
        }

        return Optional.ofNullable(resultingObject);
    }

    private List<Document> getAggregateFromFind(JsonObject nestedFind) {
        Document nestedFindDocument = Document.parse(nestedFind.toString());
        List<Document> aggregate = new ArrayList<>();
        List<String> keys = new ArrayList<>(nestedFindDocument.keySet());
        for (int i = 0; i < keys.size(); i++) {
            if (!keys.get(i).contains(".")) {
                aggregate.add(new Document("$match", new Document(keys.get(i), nestedFindDocument.get(keys.get(i)))));
            } else {
                aggregate.add(new Document("$unwind", "$" + keys.get(i).substring(0, keys.get(i).lastIndexOf('.'))));
                aggregate.add(new Document("$match", new Document(keys.get(i), nestedFindDocument.get(keys.get(i)))));
            }
            if (i == keys.size() - 1) {
                aggregate.add(new Document("$project", new Document("_id", 0).append("output",
                        "$" + keys.get(i).substring(0, keys.get(i).lastIndexOf('.')))));
            }
        }
        return aggregate;
    }

    protected void mongoPull(CacheEntry cacheEntry, MongoCollection<Document> collection, Document nestedFind) {
        CacheEntry localCacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry().deepCopy(cacheEntry).build();
        ArrayList<Document> filters = this.getFiltersAndUpdateNestedField(localCacheEntry);

        Document pullObj = new Document();
        pullObj.put(localCacheEntry.getNestedField(),
                Document.parse(localCacheEntry.getNestedFieldIdentifierObj().toString()));
        Document pull = new Document();
        pull.put("$pull", pullObj);
        collection.findOneAndUpdate(nestedFind, pull, new FindOneAndUpdateOptions().arrayFilters(filters).upsert(true));
        // TODO remove wrapping if there are no entries in array.

    }

    private ArrayList<Document> getFiltersAndUpdateNestedField(CacheEntry cacheEntry) {

        if (StringUtils.countMatches(cacheEntry.getNestedField(), ".$.") < 2) {
            return new ArrayList<>();
        }

        ArrayList<Document> filters = new ArrayList<>();
        List<String> keys = cacheEntry.getNestedFind().entrySet().stream().map(Map.Entry::getKey)
                .filter(s -> !s.equals("_id")).sorted((s, t1) -> {
                    if (StringUtils.countMatches(s, ".") > StringUtils.countMatches(t1, ".")) {
                        return 1;
                    }
                    return s.compareTo(t1);
                }).collect(Collectors.toList());
        String filterKey;
        String filterValue;
        String key;
        char filterIndex = 'a';
        StringBuilder newNestedField = new StringBuilder();
        List<String> fieldSplit = Arrays.asList(cacheEntry.getNestedField().split("\\.\\$"));
        for (int i = 0; i < fieldSplit.size(); i++) {
            final String subSplit = StringUtils.join(fieldSplit.subList(0, i + 1), "");
            key = keys.stream().filter(s -> s.startsWith(subSplit)).findFirst().get();
            filterIndex += i;
            filterKey = filterIndex + "." + key.substring(key.lastIndexOf(".") + 1);
            filterValue = cacheEntry.getNestedFind().get(key).getAsString();
            newNestedField.append(fieldSplit.get(i));
            if (i + 1 != fieldSplit.size()) {
                newNestedField.append(".$[").append(filterIndex).append("]");
                filters.add(new Document().append(filterKey, filterValue));
            }

        }
        cacheEntry.setNestedField(newNestedField.toString());

        return filters;
    }

}