com.mongodb.DBObject

Here are the examples of the java api com.mongodb.DBObject taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

252 Examples 7

19 Source : DBObjectUtil.java
with Apache License 2.0
from zhangtr

/**
 * 从列表中替换已存在的数据
 *
 * @param list
 * @param obj
 * @return
 */
public static List<DBObject> upsertDBObject(List<DBObject> list, DBObject obj) {
    if (list == null) {
        // 列表不存在,添加
        list = new ArrayList<>();
        list.add(obj);
    } else {
        // 列表存在,找id相同数据,有数据替换,没有数据添加
        int existFlag = -1;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).get("id").equals(obj.get("id"))) {
                existFlag = i;
            }
        }
        if (existFlag >= 0) {
            list.remove(existFlag);
        }
        list.add(obj);
    }
    return list;
}

19 Source : DBObjectUtil.java
with Apache License 2.0
from zhangtr

/**
 * 从列表中删除已存在的数据
 *
 * @param list
 * @param obj
 * @return
 */
public static List<DBObject> removeDBObject(List<DBObject> list, DBObject obj) {
    if (list == null || list.size() < 1) {
        return null;
    }
    int existFlag = -1;
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).get("id").equals(obj.get("id"))) {
            existFlag = i;
        }
    }
    if (existFlag >= 0) {
        list.remove(existFlag);
    }
    return list;
}

19 Source : PasswordsDbMongo.java
with GNU General Public License v2.0
from yeriomin

@Override
public String get(String email) {
    BasicDBObject query = new BasicDBObject(FIELD_EMAIL, email);
    DBObject object = collection.findOne(query);
    String preplacedword = null;
    if (null != object) {
        preplacedword = (String) object.get(FIELD_PreplacedWORD);
    }
    return preplacedword;
}

19 Source : UpdateVo.java
with GNU General Public License v3.0
from xsonorg

private void log(DBObject query, DBObject update) {
    if (log.isInfoEnabled()) {
        if (null != query) {
            log.info("query:" + query.toString());
        }
        if (null != update) {
            log.info("update:" + update.toString());
        }
    }
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

private DBObject getQuery() {
    if (null != this.condition) {
        DBObject query = new BasicDBObject();
        this.condition.setQuery(query, null);
        return query;
    }
    return null;
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

private void log(DBObject fields, DBObject query, DBObject orderByObject) {
    if (log.isInfoEnabled()) {
        if (null != fields) {
            log.info("field:" + fields.toString());
        }
        if (null != query) {
            log.info("query:" + query.toString());
        }
        if (null != orderByObject) {
            log.info("order:" + orderByObject.toString());
        }
    }
}

19 Source : InsertVo.java
with GNU General Public License v3.0
from xsonorg

private void log(DBObject doreplacedent) {
    if (log.isInfoEnabled()) {
        if (null != doreplacedent) {
            log.info("doreplacedent:" + doreplacedent.toString());
        }
    }
}

19 Source : DeleteVo.java
with GNU General Public License v3.0
from xsonorg

private void log(DBObject query) {
    if (log.isInfoEnabled()) {
        if (null != query) {
            log.info("query:" + query.toString());
        }
    }
}

19 Source : AdminActionLogDTO.java
with Apache License 2.0
from turms-im

/**
 * @author James Chen
 */
@Data
public final clreplaced AdminActionLogDTO {

    private final String account;

    private final Date logDate;

    private final String ip;

    private final String action;

    private final DBObject params;

    private final DBObject body;
}

19 Source : AdminAction.java
with Apache License 2.0
from turms-im

/**
 * @author James Chen
 */
@Data
public final clreplaced AdminAction {

    private final String account;

    private final Date logDate;

    private final String ip;

    private final String action;

    private final DBObject params;

    private final DBObject body;
}

19 Source : DataPointIdReaderConverter.java
with MIT License
from spring2go

@Override
public DataPointId convert(DBObject object) {
    Date date = (Date) object.get("date");
    String account = (String) object.get("account");
    return new DataPointId(account, date);
}

19 Source : AbstractMongoSessionConverterTest.java
with Apache License 2.0
from spring-projects

@Nullable
MongoSession convertToSession(DBObject session) {
    return (MongoSession) getMongoSessionConverter().convert(session, TypeDescriptor.valueOf(DBObject.clreplaced), TypeDescriptor.valueOf(MongoSession.clreplaced));
}

19 Source : StorageManager.java
with Apache License 2.0
from SanShanYouJiu

public static State saveFileByInputStream(InputStream is, String path, String suffix) {
    State state = null;
    File tmpFile = getTmpFile();
    byte[] dataBuf = new byte[2048];
    BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
        int count = 0;
        while ((count = bis.read(dataBuf)) != -1) {
            bos.write(dataBuf, 0, count);
        }
        bos.flush();
        bos.close();
        // 原本的代码
        // state = saveTmpFile(tmpFile, path);
        // 存入云中
        DBObject metedata = new BasicDBObject();
        // 元数据
        try {
            staticueditorFileService.saveFile(new FileInputStream(tmpFile), path, suffix, metedata);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new BaseState(false, AppInfo.IO_ERROR);
        }
        state = new BaseState(true);
        state.putInfo("size", tmpFile.length());
        state.putInfo("replacedle", tmpFile.getName());
        if (!state.isSuccess()) {
            tmpFile.delete();
        }
        return state;
    } catch (IOException e) {
    }
    return new BaseState(false, AppInfo.IO_ERROR);
}

19 Source : StorageManager.java
with Apache License 2.0
from SanShanYouJiu

/**
 * 存到七牛云中
 *
 * @param is
 * @param path
 * @param maxSize
 * @return
 */
public static State saveFileByInputStream(InputStream is, String path, String suffix, long maxSize) {
    State state = null;
    File tmpFile = getTmpFile();
    byte[] dataBuf = new byte[2048];
    BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
        int count = 0;
        while ((count = bis.read(dataBuf)) != -1) {
            bos.write(dataBuf, 0, count);
        }
        bos.flush();
        bos.close();
        if (tmpFile.length() > maxSize) {
            tmpFile.delete();
            return new BaseState(false, AppInfo.MAX_SIZE);
        }
        // 原本的方式
        // state = saveTmpFile(tmpFile, path);
        DBObject metedata = new BasicDBObject();
        // 对应的博客ID
        // metedata.put("blog_id",)
        try {
            staticueditorFileService.saveFile(new FileInputStream(tmpFile), path, suffix, metedata);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new BaseState(false, AppInfo.IO_ERROR);
        }
        state = new BaseState(true);
        state.putInfo("size", tmpFile.length());
        state.putInfo("replacedle", tmpFile.getName());
        if (!state.isSuccess()) {
            tmpFile.delete();
        }
        return state;
    } catch (IOException e) {
    }
    return new BaseState(false, AppInfo.IO_ERROR);
}

19 Source : UserResource.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Retrieve a user's profile.
 *
 * @param id The ID of the user.
 * @return The user's profile, as a JSON object. Private fields such as preplacedword and salt are not
 *     returned.
 */
@GET
@Path("/{id}")
@Produces("application/json")
public Response getUser(@PathParam("id") String id) {
    // Validate the JWT.  The JWT must belong to the 'users' or 'orchestrator' group.
    // We do not check if the user is retrieving their own profile, or someone else's.
    try {
        validateJWT(new HashSet<String>(Arrays.asList("users", "orchestrator")));
    } catch (JWTException jwte) {
        return Response.status(Status.UNAUTHORIZED).type(MediaType.TEXT_PLAIN).enreplacedy(jwte.getMessage()).build();
    }
    // Retrieve the user from the database.
    DB database = mongo.getMongoDB();
    DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
    DBObject user = dbCollection.findOne(new ObjectId(id));
    // If the user did not exist, return an error.  Otherwise, only return the public
    // fields (exclude things like the preplacedword).
    if (user == null) {
        return Response.status(Status.BAD_REQUEST).enreplacedy("The user not Found.").build();
    }
    JsonObject responsePayload = new User(user).getPublicJsonObject();
    return Response.ok(responsePayload, MediaType.APPLICATION_JSON).build();
}

19 Source : UserResource.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Delete a user.
 *
 * @param id The ID of the user to delete.
 * @return Nothing.
 */
@DELETE
@Path("/{id}")
public Response deleteUser(@PathParam("id") String id) {
    // Validate the JWT.  The JWT must be in the 'users' group.  We do not check
    // to see if the user is deleting their own profile.
    try {
        validateJWT(new HashSet<String>(Arrays.asList("users")));
    } catch (JWTException jwte) {
        return Response.status(Status.UNAUTHORIZED).type(MediaType.TEXT_PLAIN).enreplacedy(jwte.getMessage()).build();
    }
    // Retrieve the user from the database.
    DB database = mongo.getMongoDB();
    DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
    ObjectId dbId = new ObjectId(id);
    DBObject dbUser = dbCollection.findOne(dbId);
    // If the user did not exist, return an error.  Otherwise, remove the user.
    if (dbUser == null) {
        return Response.status(Status.BAD_REQUEST).enreplacedy("The user name was not Found.").build();
    }
    dbCollection.remove(new BasicDBObject(User.DB_ID, dbId));
    return Response.ok().build();
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

private OAuthClient innerReadClient(String providerId, String clientId) throws OAuthStoreException {
    try {
        DBCollection col = getClientCollection();
        BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
        d.append(PROVIDERID, providerId);
        DBObject dbo = col.findOne(d);
        if (dbo == null) {
            System.out.println("CustomStoreSample readClient Did not find clientId " + clientId + " under " + providerId);
            return null;
        }
        System.out.println("CustomStoreSample readClient Found clientId " + clientId + " under " + providerId + " _id " + dbo.get("_id"));
        return createOAuthClientHelper(dbo);
    } catch (Exception e) {
        throw new OAuthStoreException("Failed to readClient " + clientId + " under " + providerId, e);
    }
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public OAuthToken readToken(String providerId, String lookupKey) throws OAuthStoreException {
    for (int i = 0; i < RETRY_COUNT; i++) {
        try {
            DBCollection col = getTokenCollection();
            DBObject dbo = col.findOne(createTokenKeyHelper(providerId, lookupKey));
            if (dbo == null) {
                System.out.println("CustomStoreSample readToken Did not find lookupKey " + lookupKey);
                return null;
            }
            System.out.println("CustomStoreSample readToken Found lookupKey " + lookupKey + " under " + providerId + " _id " + dbo.get("_id"));
            return createOAuthTokenHelper(dbo);
        } catch (Exception e) {
            if (i < RETRY_COUNT && isNetworkFailure(e)) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                }
            } else {
                throw new OAuthStoreException("CustomStoreSample Failed to readToken " + lookupKey, e);
            }
        }
    }
    throw new OAuthStoreException("CustomStoreSample Failed to readToken after " + RETRY_COUNT + "tries: " + lookupKey);
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

private OAuthToken createOAuthTokenHelper(DBObject dbo) {
    return new OAuthToken((String) dbo.get(LOOKUPKEY), (String) dbo.get(UNIQUEID), (String) dbo.get(PROVIDERID), (String) dbo.get(TYPE), (String) dbo.get(SUBTYPE), (long) dbo.get(CREATEDAT), (int) dbo.get(LIFETIME), (long) dbo.get(EXPIRES), (String) dbo.get(TOKENSTRING), (String) dbo.get(CLIENTID), (String) dbo.get(USERNAME), (String) dbo.get(SCOPE), (String) dbo.get(REDIRECTURI), (String) dbo.get(STATEID), (String) dbo.get(PROPS));
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

private OAuthClient createOAuthClientHelper(DBObject dbo) {
    return new OAuthClient((String) dbo.get(PROVIDERID), (String) dbo.get(CLIENTID), (String) dbo.get(CLIENTSECRET), (String) dbo.get(DISPLAYNAME), (boolean) dbo.get(ENABLED), (String) dbo.get(METADATA));
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public OAuthConsent readConsent(String providerId, String username, String clientId, String resource) throws OAuthStoreException {
    try {
        DBCollection col = getConsentCollection();
        DBObject dbo = col.findOne(createConsentKeyHelper(providerId, username, clientId, resource));
        if (dbo == null) {
            System.out.println("CustomStoreSample readConsent Did not find username " + username);
            return null;
        }
        System.out.println("CustomStoreSample readConsent Found clientId " + clientId + " under " + providerId + " _id " + dbo.get("_id"));
        return new OAuthConsent(clientId, (String) dbo.get(USERNAME), (String) dbo.get(SCOPE), resource, providerId, (long) dbo.get(EXPIRES), (String) dbo.get(PROPS));
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on readConsent for " + username, e);
    }
}

19 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private String getAlgorithm(String clientId, String providerId) throws Exception {
    DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
    BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
    d.append(PROVIDERID, providerId == null ? DEFAULT_COMPID : providerId);
    DBObject dbo = col.findOne(d);
    if (dbo == null) {
        System.out.println("getAlgorithm: Could not find client " + clientId + " providerId " + providerId);
        return "null_client";
    }
    String cs = (String) dbo.get(METADATA);
    JSONObject clientMetadata = JSONObject.parse(cs);
    String algorithm = (String) clientMetadata.get(HASH_ALGORITHM);
    if (algorithm == null) {
        return "null_algorithm";
    }
    return algorithm;
}

19 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private String getSalt(String clientId, String providerId) throws Exception {
    DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
    BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
    d.append(PROVIDERID, providerId == null ? DEFAULT_COMPID : providerId);
    DBObject dbo = col.findOne(d);
    if (dbo == null) {
        System.out.println("getSalt: Could not find client " + clientId + " providerId " + providerId);
        return "null_client";
    }
    String cs = (String) dbo.get(METADATA);
    JSONObject clientMetadata = JSONObject.parse(cs);
    String salt = (String) clientMetadata.get(HASH_SALT);
    if (salt == null) {
        return "null_salt";
    }
    return salt;
}

19 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private String gereplacederation(String clientId, String providerId) throws Exception {
    DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
    BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
    d.append(PROVIDERID, providerId == null ? DEFAULT_COMPID : providerId);
    DBObject dbo = col.findOne(d);
    if (dbo == null) {
        System.out.println("gereplacederation: Could not find client " + clientId + " providerId " + providerId);
        return "null_client";
    }
    String cs = (String) dbo.get(METADATA);
    JSONObject clientMetadata = JSONObject.parse(cs);
    String iteration = String.valueOf(clientMetadata.get(HASH_ITERATIONS));
    if (iteration == null) {
        return "null_iteration";
    }
    return iteration;
}

19 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private String getSecretType(String clientId, String providerId) throws Exception {
    DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
    BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
    d.append(PROVIDERID, providerId == null ? DEFAULT_COMPID : providerId);
    DBObject dbo = col.findOne(d);
    if (dbo == null) {
        System.out.println("getSecretType: Could not find client " + clientId + " providerId " + providerId);
        return "null_client";
    }
    String cs = (String) dbo.get(CLIENTSECRET);
    System.out.println("oAuth20MongoSetup " + cs);
    if (cs == null) {
        return "null_secret";
    } else if (cs.equals("")) {
        return "empty_secret";
    } else if (cs.startsWith("{xor}")) {
        return "xor";
    } else if (cs.startsWith("{hash}")) {
        return "hash";
    } else {
        return "plain";
    }
}

19 Source : MongoTestServlet.java
with Eclipse Public License 1.0
from OpenLiberty

public static void find(DB db, String key, String expectedValue) throws IOException {
    DBCollection col = db.getCollection(COLLECTION);
    DBObject dbo = col.findOne(new BasicDBObject(KEY, key));
    String actualValue = (String) dbo.get(DATA);
    System.out.println("found key=" + key + " value=" + actualValue + " from dbName=" + db.getName());
    replacedertEquals(expectedValue, actualValue);
}

19 Source : MongoDb310Test.java
with Apache License 2.0
from newrelic

@Trace(dispatcher = true)
public static void demoAggregation(PokemonMaster master) throws InterruptedException {
    System.out.println("===Aggregate Operations===");
    System.out.print("Aggregation results (Average Attack by type desc): ");
    for (DBObject pokemon : master.demoAggregationResults()) {
        System.out.print(pokemon.get("_id") + "::" + pokemon.get("AverageAttack") + ", ");
    }
    System.out.println();
    System.out.print("Aggregation Cursor  (Average Attack by type desc): ");
    for (DBObject pokemon : master.demoAggregationCursor()) {
        System.out.print(pokemon.get("_id") + "::" + pokemon.get("AverageAttack") + ", ");
    }
    System.out.println();
}

19 Source : MongoDb310Test.java
with Apache License 2.0
from newrelic

@Trace(dispatcher = true)
public static void demoCRUD(PokemonMaster master) throws InterruptedException {
    System.out.println("===Basic CRUD===");
    DBObject newPokemon = new BasicDBObject("name", "Togepi").append("number", 175);
    System.out.println("(C) Insert results: " + master.demoInsert(newPokemon));
    System.out.print("(R) Find one fire type: " + master.demoFindOne("fire"));
    System.out.print(". Find: Original 150: ");
    for (DBObject pokemon : master.demoFind()) {
        System.out.print(pokemon.get("name") + " ");
    }
    System.out.println();
    System.out.println("(U) Update results: " + master.demoUpdate(newPokemon, new BasicDBObject("type", "fairy")));
    System.out.println("(D) Delete results: " + master.demoRemove(newPokemon));
}

19 Source : DBObjectToAuthorConverter.java
with Apache License 2.0
from linnykoleh

@Override
public Author convert(DBObject source) {
    final Author author = new Author();
    author.setCountry(source.get("country").toString().split(" ")[0]);
    author.setFirstName(source.get("name").toString().split(" ")[0]);
    author.setLastName(source.get("name").toString().split(" ")[1]);
    return author;
}

19 Source : EvalResultHandler.java
with Apache License 2.0
from johrstrom

public String handle(DBObject o) {
    return JSON.serialize(o);
}

19 Source : MongodbQueryResult.java
with Apache License 2.0
from itfsw

/**
 * ---------------------------------------------------------------------------
 *
 * ---------------------------------------------------------------------------
 * @author: hewei
 * @time:2017/11/2 16:46
 * ---------------------------------------------------------------------------
 */
public clreplaced MongodbQueryResult extends AbstractResult {

    private DBObject query;

    /**
     * 构造函数
     * @param queryJson
     * @param query
     */
    public MongodbQueryResult(String queryJson, DBObject query) {
        this.queryJson = queryJson;
        this.query = query;
    }

    /**
     * Getter method for property <tt>query</tt>.
     * @return property value of query
     * @author hewei
     */
    @Override
    public DBObject getQuery() {
        return query;
    }

    /**
     * to string
     * @return
     */
    @Override
    public String toString() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValuereplacedtring(query);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

19 Source : MongodbBuilder.java
with Apache License 2.0
from itfsw

/**
 * 构建
 * @param query
 * @return
 * @throws IOException
 * @throws ParserNotFoundException
 */
@Override
public MongodbQueryResult build(String query) throws IOException, ParserNotFoundException {
    DBObject result = (DBObject) super.parse(query);
    return new MongodbQueryResult(query, result);
}

19 Source : MongoDBResultSet.java
with Apache License 2.0
from bbossgroups

/**
 * <p>Description: </p>
 * <p></p>
 * <p>Copyright (c) 2018</p>
 * @Date 2019/8/3 12:27
 * @author biaoping.yin
 * @version 1.0
 */
public clreplaced MongoDBResultSet extends LastValue implements TranResultSet {

    private DBCursor dbCursor;

    private DBObject record;

    public MongoDBResultSet(ImportContext importContext, DBCursor dbCursor) {
        this.importContext = importContext;
        this.dbCursor = dbCursor;
    }

    @Override
    public Object getValue(int i, String colName, int sqlType) throws ESDataImportException {
        return getValue(colName);
    }

    @Override
    public Object getValue(String colName) throws ESDataImportException {
        Object value = record.get(colName);
        if (value != null) {
            if (colName.equals("_id") && value instanceof ObjectId) {
                return ((ObjectId) value).toString();
            }
        }
        return value;
    }

    @Override
    public Object getValue(String colName, int sqlType) throws ESDataImportException {
        return getValue(colName);
    }

    @Override
    public Date getDateTimeValue(String colName) throws ESDataImportException {
        Object value = getValue(colName);
        if (value == null)
            return null;
        return TranUtil.getDateTimeValue(colName, value, importContext);
    }

    @Override
    public Boolean next() throws ESDataImportException {
        boolean hasNext = dbCursor.hasNext();
        if (hasNext) {
            record = dbCursor.next();
        }
        return hasNext;
    }

    @Override
    public TranMeta getMetaData() {
        return new DefaultTranMetaData(record.keySet());
    }

    public Object getKeys() {
        return record.keySet();
    }

    @Override
    public Object getRecord() {
        return record;
    }

    @Override
    public void stop() {
    }

    @Override
    public Object getMetaValue(String fieldName) {
        return null;
    }
}

19 Source : MongoDBImportConfig.java
with Apache License 2.0
from bbossgroups

public void setFetchFields(DBObject fetchFields) {
    this.fetchFields = fetchFields;
}

19 Source : MongoDBImportConfig.java
with Apache License 2.0
from bbossgroups

public void setQuery(DBObject query) {
    this.query = query;
}

19 Source : MongoDBExportBuilder.java
with Apache License 2.0
from bbossgroups

public MongoDBExportBuilder setFetchFields(DBObject fetchFields) {
    this.fetchFields = fetchFields;
    return this;
}

19 Source : MongoDBExportBuilder.java
with Apache License 2.0
from bbossgroups

public MongoDBExportBuilder setQuery(DBObject dbObject) {
    this.query = dbObject;
    return this;
}

19 Source : DBObjectToStringContentTypeConverter.java
with Apache License 2.0
from AxonFramework

@Override
public String convert(DBObject original) {
    return ((BasicDBObject) original).toJson();
}

19 Source : DBObjectHierarchicalStreamWriter.java
with Apache License 2.0
from AxonFramework

/**
 * HierarchicalStreamWriter implementation that writes objects into a MongoDB DBObject structure. Use the {@link
 * DBObjectHierarchicalStreamReader} to read the object back.
 *
 * @author Allard Buijze
 * @since 2.0
 */
public clreplaced DBObjectHierarchicalStreamWriter implements ExtendedHierarchicalStreamWriter {

    private final Deque<BSONNode> itemStack = new ArrayDeque<>();

    private final DBObject root;

    /**
     * Initialize the writer to write the object structure to the given {@code root} DBObject.
     * <p>
     * Note that the given {@code root} DBObject must not contain any data yet.
     *
     * @param root The root DBObject to which the serialized structure will be added. Must not contain any data.
     */
    public DBObjectHierarchicalStreamWriter(DBObject root) {
        replacedert.isTrue(root.keySet().isEmpty(), () -> "The given root object must be empty.");
        this.root = root;
    }

    @Override
    public void startNode(String name) {
        if (itemStack.isEmpty()) {
            itemStack.push(new BSONNode(name));
        } else {
            itemStack.push(itemStack.peek().addChildNode(name));
        }
    }

    @Override
    public void addAttribute(String name, String value) {
        itemStack.peek().setAttribute(name, value);
    }

    @Override
    public void setValue(String text) {
        itemStack.peek().setValue(text);
    }

    @Override
    public void endNode() {
        BSONNode closingElement = itemStack.pop();
        if (itemStack.isEmpty()) {
            // we've popped the last one, so we're done
            root.putAll(closingElement.asDBObject());
        }
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
    }

    @Override
    public HierarchicalStreamWriter underlyingWriter() {
        return this;
    }

    @Override
    public void startNode(String name, Clreplaced clazz) {
        startNode(name);
    }
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testTopLevelArrayStructureContainingOneObjectMutipleFields() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = asList(mf("field1", true, "[0]"), mf("field2", true, "[0]"));
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    Object[] row = new Object[2];
    row[0] = "value1";
    row[1] = 12L;
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.ARRAY, false);
    replacedertEquals(JSON.serialize(result), "[ { \"field1\" : \"value1\" , \"field2\" : 12}]");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testModifierSetComplexArrayGrouping() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(2);
    MongoDbOutputData data = new MongoDbOutputData();
    IVariables vars = new Variables();
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "bob.fred[0].george");
    mf.m_modifierUpdateOperation = "$set";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    mf = mf("field2", true, "bob.fred[0].george");
    mf.m_modifierUpdateOperation = "$set";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    IRowMeta rm = new RowMeta();
    rm.addValueMeta(new ValueMetaString("field1"));
    rm.addValueMeta(new ValueMetaString("field2"));
    Object[] dummyRow = new Object[] { "value1", "value2" };
    DBObject modifierUpdate = data.getModifierUpdateObject(paths, rm, dummyRow, vars, MongoTopLevel.RECORD);
    replacedertTrue(modifierUpdate != null);
    replacedertTrue(modifierUpdate.get("$set") != null);
    DBObject setOpp = (DBObject) modifierUpdate.get("$set");
    // in this case, we have the same path up to the array (bob.fred). The
    // remaining
    // terminal fields should be grouped into one record "george" as the first
    // entry in
    // the array - so there should be one entry for $set
    replacedertEquals(setOpp.keySet().size(), 1);
    // check the resulting update structure
    replacedertEquals(JSON.serialize(modifierUpdate), "{ \"$set\" : { \"bob.fred\" : [ { \"george\" : { \"field1\" : \"value1\" , \"field2\" : \"value2\"}}]}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testTopLevelObjectStructureTwoLevelNested() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(2);
    MongoDbOutputMeta.MongoField mf = new MongoDbOutputMeta.MongoField();
    mf.m_incomingFieldName = "field1";
    mf.m_mongoDocPath = "nestedDoc.secondNested";
    mf.m_useIncomingFieldNameAsMongoFieldName = true;
    paths.add(mf);
    mf = new MongoDbOutputMeta.MongoField();
    mf.m_incomingFieldName = "field2";
    mf.m_mongoDocPath = "nestedDoc";
    mf.m_useIncomingFieldNameAsMongoFieldName = true;
    paths.add(mf);
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    Object[] row = new Object[2];
    row[0] = "value1";
    row[1] = 12L;
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.RECORD, false);
    replacedertEquals(JSON.serialize(result), "{ \"nestedDoc\" : { \"secondNested\" : { \"field1\" : \"value1\"} , \"field2\" : 12}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testInsertHopFieldThatContainsJsonIntoOneLevelNestedDoc() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(3);
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "");
    paths.add(mf);
    mf = mf("field2", true, "nestedDoc");
    paths.add(mf);
    mf = mf("jsonField", true, "nestedDoc");
    mf.m_JSON = true;
    paths.add(mf);
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    rmi.addValueMeta(new ValueMetaString("jsonField"));
    Object[] row = new Object[3];
    row[0] = "value1";
    row[1] = 12L;
    row[2] = "{\"jsonDocField1\" : \"aval\", \"jsonDocField2\" : 42}";
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.RECORD, false);
    replacedertEquals(JSON.serialize(result), "{ \"field1\" : \"value1\" , \"nestedDoc\" : { \"field2\" : 12 , \"jsonField\" : { \"jsonDocField1\" : \"aval\"" + " , \"jsonDocField2\" : 42}}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testModifierPushComplexObject() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(2);
    MongoDbOutputData data = new MongoDbOutputData();
    IVariables vars = new Variables();
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "bob.fred[].george");
    mf.m_modifierUpdateOperation = "$push";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    mf = mf("field2", true, "bob.fred[].george");
    mf.m_modifierUpdateOperation = "$push";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    IRowMeta rm = new RowMeta();
    rm.addValueMeta(new ValueMetaString("field1"));
    rm.addValueMeta(new ValueMetaString("field2"));
    Object[] dummyRow = new Object[] { "value1", "value2" };
    DBObject modifierUpdate = data.getModifierUpdateObject(paths, rm, dummyRow, vars, MongoTopLevel.RECORD);
    replacedertTrue(modifierUpdate != null);
    replacedertTrue(modifierUpdate.get("$push") != null);
    DBObject setOpp = (DBObject) modifierUpdate.get("$push");
    // in this case, we have the same path up to the array (bob.fred). The
    // remaining
    // terminal fields should be grouped into one record "george" for $push to
    // append
    // to the end of the array
    replacedertEquals(setOpp.keySet().size(), 1);
    replacedertEquals(JSON.serialize(modifierUpdate), "{ \"$push\" : { \"bob.fred\" : { \"george\" : { \"field1\" : \"value1\" , \"field2\" : \"value2\"}}}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testGetQueryObjectThatContainsJsonNestedDoc() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(3);
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "");
    mf.m_updateMatchField = true;
    paths.add(mf);
    mf = mf("field2", true, "");
    mf.m_updateMatchField = true;
    paths.add(mf);
    mf = mf("jsonField", true, "");
    mf.m_updateMatchField = true;
    mf.m_JSON = true;
    paths.add(mf);
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    rmi.addValueMeta(new ValueMetaString("jsonField"));
    Object[] row = new Object[3];
    row[0] = "value1";
    row[1] = 12L;
    row[2] = "{\"jsonDocField1\" : \"aval\", \"jsonDocField2\" : 42}";
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject query = MongoDbOutputData.getQueryObject(paths, rmi, row, vs, MongoTopLevel.RECORD);
    replacedertEquals(JSON.serialize(query), "{ \"field1\" : \"value1\" , \"field2\" : 12 , \"jsonField\" : { \"jsonDocField1\" : \"aval\" , " + "\"jsonDocField2\" : 42}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testTopLevelArrayStructureWithObjects() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = asList(mf("field1", true, "[0]"), mf("field2", true, "[1]"));
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    Object[] row = new Object[2];
    row[0] = "value1";
    row[1] = 12L;
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.ARRAY, false);
    replacedertEquals(JSON.serialize(result), "[ { \"field1\" : \"value1\"} , { \"field2\" : 12}]");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

/**
 * PDI-11045. Here we test backwards compatibility for old ktrs that were developed before 11045.
 * In these ktrs query paths had to be specified a second time in the transform in order to get
 * them into the update/upsert object. Now we replacedume that there will never be a situation where
 * the user might not want the match fields present in the update object
 *
 * @throws HopException
 */
@Test
public void testUpdateObjectBackwardsCompatibility() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(2);
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "");
    mf.m_updateMatchField = true;
    paths.add(mf);
    // same as previous field (but not a match condition). Prior to PDI-11045 the
    // user had to specify the match conditions a second time (but not marked in the
    // transform as a match condition) in order to get them into the update/upsert object
    mf = mf("field1", true, "");
    mf.m_updateMatchField = false;
    paths.add(mf);
    mf = mf("field2", true, "");
    paths.add(mf);
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    Object[] row = new Object[2];
    row[0] = "value1";
    row[1] = 12L;
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.RECORD, false);
    // here we expect that field1 does *not* occur twice in the update object
    replacedertEquals(JSON.serialize(result), "{ \"field1\" : \"value1\" , \"field2\" : 12}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testTopLevelArrayStructureContainingObjectWithArray() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(2);
    MongoDbOutputMeta.MongoField mf = new MongoDbOutputMeta.MongoField();
    mf.m_incomingFieldName = "field1";
    mf.m_mongoDocPath = "[0].inner[0]";
    mf.m_useIncomingFieldNameAsMongoFieldName = true;
    paths.add(mf);
    mf = new MongoDbOutputMeta.MongoField();
    mf.m_incomingFieldName = "field2";
    mf.m_mongoDocPath = "[0].inner[1]";
    mf.m_useIncomingFieldNameAsMongoFieldName = true;
    paths.add(mf);
    IRowMeta rmi = new RowMeta();
    rmi.addValueMeta(new ValueMetaString("field1"));
    rmi.addValueMeta(new ValueMetaInteger("field2"));
    Object[] row = new Object[2];
    row[0] = "value1";
    row[1] = 12L;
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rmi, row, MongoTopLevel.ARRAY, false);
    replacedertEquals(JSON.serialize(result), "[ { \"inner\" : [ { \"field1\" : \"value1\"} , { \"field2\" : 12}]}]");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testInsertHopFieldThatContainsJsonIntoTopLevelRecord() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(3);
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "");
    paths.add(mf);
    mf = mf("field2", true, "");
    paths.add(mf);
    mf = mf("jsonField", true, "");
    mf.m_JSON = true;
    paths.add(mf);
    IRowMeta rm = new RowMeta();
    rm.addValueMeta(new ValueMetaString("field1"));
    rm.addValueMeta(new ValueMetaInteger("field2"));
    rm.addValueMeta(new ValueMetaString("jsonField"));
    Object[] row = new Object[3];
    row[0] = "value1";
    row[1] = 12L;
    row[2] = "{\"jsonDocField1\" : \"aval\", \"jsonDocField2\" : 42}";
    IVariables vs = new Variables();
    for (MongoDbOutputMeta.MongoField f : paths) {
        f.init(vs);
    }
    DBObject result = hopRowToMongo(paths, rm, row, MongoTopLevel.RECORD, false);
    replacedertEquals(JSON.serialize(result), "{ \"field1\" : \"value1\" , \"field2\" : 12 , \"jsonField\" : { \"jsonDocField1\" : \"aval\" , " + "\"jsonDocField2\" : 42}}");
}

19 Source : MongoDbOutputTest.java
with Apache License 2.0
from apache

@Test
public void testModifierPushComplexObjectWithJsonNestedDoc() throws Exception {
    List<MongoDbOutputMeta.MongoField> paths = new ArrayList<>(3);
    MongoDbOutputData data = new MongoDbOutputData();
    IVariables vars = new Variables();
    MongoDbOutputMeta.MongoField mf = mf("field1", true, "bob.fred[].george");
    mf.m_modifierUpdateOperation = "$push";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    mf = mf("field2", true, "bob.fred[].george");
    mf.m_modifierUpdateOperation = "$push";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.init(vars);
    paths.add(mf);
    mf = mf("jsonField", true, "bob.fred[].george");
    mf.m_modifierUpdateOperation = "$push";
    mf.m_modifierOperationApplyPolicy = "Insert&Update";
    mf.m_JSON = true;
    mf.init(vars);
    paths.add(mf);
    IRowMeta rm = new RowMeta();
    rm.addValueMeta(new ValueMetaString("field1"));
    rm.addValueMeta(new ValueMetaString("field2"));
    rm.addValueMeta(new ValueMetaString("jsonField"));
    Object[] dummyRow = new Object[] { "value1", "value2", "{\"jsonDocField1\" : \"aval\", \"jsonDocField2\" : 42}" };
    DBObject modifierUpdate = data.getModifierUpdateObject(paths, rm, dummyRow, vars, MongoTopLevel.RECORD);
    replacedertTrue(modifierUpdate != null);
    replacedertTrue(modifierUpdate.get("$push") != null);
    DBObject setOpp = (DBObject) modifierUpdate.get("$push");
    // in this case, we have the same path up to the array (bob.fred). The
    // remaining
    // terminal fields should be grouped into one record "george" for $push to
    // append
    // to the end of the array
    replacedertEquals(setOpp.keySet().size(), 1);
    replacedertEquals(JSON.serialize(modifierUpdate), "{ \"$push\" : { \"bob.fred\" : { \"george\" : { \"field1\" : \"value1\" , \"field2\" : \"value2\" , " + "\"jsonField\" : " + "{ \"jsonDocField1\" : \"aval\" , \"jsonDocField2\" : 42}}}}}");
}

See More Examples