Skip to main content
summaryrefslogtreecommitdiffstats
blob: 2052d3728fe50629e3af13cd4611b8a14fb6c394 (plain) (blame)
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
/*
 * Copyright (c) 2011, 2012, 2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.emf.cdo.server.internal.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

/**
 * @author Eike Stepper
 */
public class Coll
{
  protected MongoDBStore store;

  protected DBCollection collection;

  public Coll(MongoDBStore store, String name)
  {
    this.store = store;
    collection = store.getDB().getCollection(name);
  }

  public MongoDBStore getStore()
  {
    return store;
  }

  public DBCollection getCollection()
  {
    return collection;
  }

  public void ensureIndex(String element, String field, boolean asc)
  {
    DBObject index = new BasicDBObject();
    index.put(element + "." + field, asc ? 1 : -1);

    collection.ensureIndex(index);
  }

  public void ensureIndex(String element, String... fields)
  {
    DBObject index = new BasicDBObject();
    for (String field : fields)
    {
      index.put(element + "." + field, 1);

    }

    collection.ensureIndex(index);
  }

  /**
   * @author Eike Stepper
   */
  public abstract class Query<RESULT>
  {
    private DBObject ref;

    public Query(DBObject ref)
    {
      this.ref = ref;
    }

    public DBObject getRef()
    {
      return ref;
    }

    public RESULT execute()
    {
      return execute(collection.find(ref));
    }

    public RESULT execute(DBObject keys)
    {
      return execute(collection.find(ref, keys));
    }

    protected RESULT execute(DBCursor cursor)
    {
      try
      {
        while (cursor.hasNext())
        {
          DBObject doc = cursor.next();
          RESULT result = handleDoc(doc);
          if (result != null)
          {
            return result;
          }
        }

        return null;
      }
      finally
      {
        cursor.close();
      }
    }

    protected abstract RESULT handleDoc(DBObject doc);
  }
}

Back to the top