Example usage for com.mongodb BasicDBList BasicDBList

List of usage examples for com.mongodb BasicDBList BasicDBList

Introduction

In this page you can find the example usage for com.mongodb BasicDBList BasicDBList.

Prototype

BasicDBList

Source Link

Usage

From source file:com.redhat.lightblue.mongo.crud.DocTranslator.java

License:Open Source License

public static void populateCaseInsensitiveField(Object doc, Path field) {
    if (doc == null) {
        return;//from   www  .j  a  v  a  2s  .co m
    } else if (field.numSegments() == 1) {
        DBObject docObj = (DBObject) doc;
        if (docObj.get(field.head(0)) == null) {
            // no value, so nothing to populate
            DBObject dbo = (DBObject) docObj.get(HIDDEN_SUB_PATH.toString());
            if (dbo != null && dbo.get(field.head(0)) != null) {
                dbo.removeField(field.head(0));
            }
            return;
        } else if (docObj.get(field.head(0)) instanceof List) {
            // primitive list - add hidden field to doc and populate list
            List<String> objList = (List<String>) docObj.get(field.head(0));
            BasicDBList hiddenList = new BasicDBList();
            objList.forEach(s -> hiddenList.add(s.toUpperCase()));
            DBObject dbo = (DBObject) docObj.get(HIDDEN_SUB_PATH.toString());
            if (dbo == null) {
                docObj.put(HIDDEN_SUB_PATH.toString(), new BasicDBObject(field.head(0), hiddenList));
            } else {
                dbo.put(field.head(0), hiddenList);
            }
        } else {
            // add hidden field to doc, populate field
            DBObject dbo = (DBObject) docObj.get(HIDDEN_SUB_PATH.toString());
            if (dbo == null) {
                docObj.put(HIDDEN_SUB_PATH.toString(),
                        new BasicDBObject(field.head(0), docObj.get(field.head(0)).toString().toUpperCase()));
            } else {
                dbo.put(field.head(0), docObj.get(field.head(0)).toString().toUpperCase());
            }
        }
    } else if (field.head(0).equals(Path.ANY)) {
        // doc is a list
        List<?> docList = ((List<?>) doc);
        docList.forEach(key -> populateCaseInsensitiveField(key, field.suffix(-1)));
    } else {
        DBObject docObj = (DBObject) doc;
        populateCaseInsensitiveField(docObj.get(field.head(0)), field.suffix(-1));
    }
}

From source file:com.sitewhere.mongodb.device.MongoZone.java

License:Open Source License

/**
 * Copy information from SPI into Mongo DBObject.
 * /*  w  w  w.  java 2  s.co m*/
 * @param source
 * @param target
 */
public static void toDBObject(IZone source, BasicDBObject target) {
    target.append(PROP_TOKEN, source.getToken());
    target.append(PROP_SITE_TOKEN, source.getSiteToken());
    target.append(PROP_NAME, source.getName());
    target.append(PROP_BORDER_COLOR, source.getBorderColor());
    target.append(PROP_FILL_COLOR, source.getFillColor());
    target.append(PROP_OPACITY, source.getOpacity());

    BasicDBList coords = new BasicDBList();
    if (source.getCoordinates() != null) {
        for (ILocation location : source.getCoordinates()) {
            BasicDBObject coord = new BasicDBObject();
            coord.put(MongoDeviceLocation.PROP_LATITUDE, location.getLatitude());
            coord.put(MongoDeviceLocation.PROP_LONGITUDE, location.getLongitude());
            if (location.getElevation() != null) {
                coord.put(MongoDeviceLocation.PROP_ELEVATION, location.getElevation());
            }
            coords.add(coord);
        }
    }
    target.append(PROP_COORDINATES, coords);

    MongoSiteWhereEntity.toDBObject(source, target);
    MongoMetadataProvider.toDBObject(source, target);
}

From source file:com.sitewhere.mongodb.tenant.MongoTenantManagement.java

License:Open Source License

@Override
public ISearchResults<ITenant> listTenants(ITenantSearchCriteria criteria) throws SiteWhereException {
    DBCollection tenants = getMongoClient().getTenantsCollection();
    BasicDBObject dbCriteria = new BasicDBObject();
    if (criteria.getTextSearch() != null) {
        try {//  www . j  a v  a 2  s. c  o  m
            Pattern regex = Pattern.compile(Pattern.quote(criteria.getTextSearch()));
            DBObject idSearch = new BasicDBObject(MongoTenant.PROP_ID, regex);
            DBObject nameSearch = new BasicDBObject(MongoTenant.PROP_NAME, regex);
            BasicDBList or = new BasicDBList();
            or.add(idSearch);
            or.add(nameSearch);
            dbCriteria.append("$or", or);
        } catch (PatternSyntaxException e) {
            LOGGER.warn("Invalid regex for searching tenant list. Ignoring.");
        }
    }
    if (criteria.getUserId() != null) {
        dbCriteria.append(MongoTenant.PROP_AUTH_USERS, criteria.getUserId());
    }
    BasicDBObject sort = new BasicDBObject(MongoTenant.PROP_NAME, 1);
    ISearchResults<ITenant> list = MongoPersistence.search(ITenant.class, tenants, dbCriteria, sort, criteria);
    SiteWherePersistence.tenantListLogic(list.getResults(), criteria);
    return list;
}

From source file:com.sitewhere.tenant.persistence.mongodb.MongoTenantManagement.java

License:Open Source License

@Override
public ISearchResults<ITenant> listTenants(ITenantSearchCriteria criteria) throws SiteWhereException {
    MongoCollection<Document> tenants = getMongoClient().getTenantsCollection();
    Document dbCriteria = new Document();
    if (criteria.getTextSearch() != null) {
        try {/*from w ww.j  a  v a2 s  . c o m*/
            Pattern regex = Pattern.compile(Pattern.quote(criteria.getTextSearch()));
            DBObject idSearch = new BasicDBObject(MongoTenant.PROP_ID, regex);
            DBObject nameSearch = new BasicDBObject(MongoTenant.PROP_NAME, regex);
            BasicDBList or = new BasicDBList();
            or.add(idSearch);
            or.add(nameSearch);
            dbCriteria.append("$or", or);
        } catch (PatternSyntaxException e) {
            LOGGER.warn("Invalid regex for searching tenant list. Ignoring.");
        }
    }
    if (criteria.getUserId() != null) {
        dbCriteria.append(MongoTenant.PROP_AUTH_USERS, criteria.getUserId());
    }
    Document sort = new Document(MongoTenant.PROP_NAME, 1);
    ISearchResults<ITenant> list = MongoPersistence.search(ITenant.class, tenants, dbCriteria, sort, criteria,
            LOOKUP);
    TenantManagementPersistenceLogic.tenantListLogic(list.getResults(), criteria);
    return list;
}

From source file:com.softinstigate.restheart.hal.Representation.java

License:Open Source License

/**
 *
 * @param link/*from w  ww.j  av  a 2  s  .  com*/
 * @param inArray
 */
public void addLink(Link link, boolean inArray) {
    BasicDBList linkArray = (BasicDBList) links.get(link.getRef());

    if (linkArray == null) {
        linkArray = new BasicDBList();
        links.append(link.getRef(), linkArray);
    }

    linkArray.add(link.getDBObject().get(link.getRef()));

    links.put(link.getRef(), linkArray);
}

From source file:com.softinstigate.restheart.hal.Representation.java

License:Open Source License

/**
 *
 * @param rel/*from w  ww.  j  av a  2  s.  co  m*/
 * @param rep
 */
public void addRepresentation(String rel, Representation rep) {
    BasicDBList repArray = (BasicDBList) embedded.get(rel);

    if (repArray == null) {
        repArray = new BasicDBList();

        embedded.append(rel, repArray);
    }

    repArray.add(rep.getDBObject());
}

From source file:com.softinstigate.restheart.handlers.applicationlogic.GetRoleHandler.java

License:Open Source License

/**
 * Handles the request./*from ww  w  .j a  v a2 s.c om*/
 *
 * @param exchange
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getMethod() == METHOD.OPTIONS) {
        exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET");
        exchange.getResponseHeaders().put(HttpString.tryFromString("Access-Control-Allow-Headers"),
                "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge");
        exchange.setResponseCode(HttpStatus.SC_OK);
        exchange.endExchange();
    } else if (context.getMethod() == METHOD.GET) {
        String authHeader = exchange.getRequestHeaders().getFirst("Authorization");

        if (authHeader != null && authHeader.startsWith("Basic ")) {
            authHeader = authHeader.replaceAll("^Basic ", "");

            byte[] __idAndPwd;

            try {
                __idAndPwd = DatatypeConverter.parseBase64Binary(authHeader);
            } catch (IllegalArgumentException iae) {
                __idAndPwd = null;
            }

            if (__idAndPwd != null) {
                String[] idAndPwd = new String(__idAndPwd, StandardCharsets.UTF_8).split(":");

                if (idAndPwd.length == 2) {
                    Account a = idm.verify(idAndPwd[0], new PasswordCredential(idAndPwd[1].toCharArray()));

                    if (a != null) {
                        BasicDBList _roles = new BasicDBList();

                        _roles.addAll(a.getRoles());

                        BasicDBObject root = new BasicDBObject();

                        root.append("authenticated", true);
                        root.append("roles", _roles);

                        Representation rep = new Representation(url);
                        rep.addProperties(root);

                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE,
                                Representation.HAL_JSON_MEDIA_TYPE);
                        exchange.setResponseCode(HttpStatus.SC_OK);
                        exchange.getResponseSender().send(rep.toString());
                        exchange.endExchange();
                        return;
                    }
                }
            }
        }

        BasicDBObject root = new BasicDBObject();

        root.append("authenticated", false);
        root.append("roles", null);

        Representation rep = new Representation("/_logic/roles/mine");
        rep.addProperties(root);

        if (sendChallenge) {
            exchange.getResponseHeaders().add(WWW_AUTHENTICATE, challenge);
            exchange.setResponseCode(HttpStatus.SC_UNAUTHORIZED);
        } else {
            exchange.setResponseCode(HttpStatus.SC_OK);
        }

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, Representation.HAL_JSON_MEDIA_TYPE);
        exchange.getResponseSender().send(rep.toString());

        exchange.endExchange();
    } else {
        exchange.setResponseCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
        exchange.endExchange();
    }
}

From source file:com.softinstigate.restheart.utils.ResponseHelper.java

License:Open Source License

private static BasicDBList getStackTraceJson(Throwable t) {
    if (t == null || t.getStackTrace() == null) {
        return null;
    }/*from  w w w .ja  v a 2  s  .  com*/

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    t.printStackTrace(pw);

    String st = sw.toString();

    st = st.replaceAll("\t", "  ");

    String[] lines = st.split("\n");

    BasicDBList list = new BasicDBList();

    list.addAll(Arrays.asList(lines));
    return list;
}

From source file:com.syncleus.maven.plugins.mongodb.ReplSetInitiateConfig.java

License:Open Source Community License

public BasicDBObject makeCommand() {
    final BasicDBObject cmd = new BasicDBObject();
    if (_id != null && !_id.isEmpty())
        cmd.put("_id", _id);
    if (version != null)
        cmd.put("version", version);
    if (members != null && members.length > 0) {
        final BasicDBList dbMembers = new BasicDBList();
        for (final MembersConfig member : members)
            dbMembers.add(member.makeCommand());
        cmd.put("members", dbMembers);
    }//from w  w  w . j  a v  a  2 s.c o m
    if (settings != null)
        cmd.put("settings", settings.makeCommand());
    return cmd;
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Builds the points part for the Json used to prepopulate.
 * @param resolution//from   w  ww.  jav  a  2s.  co m
 */
private BasicDBList buildPrepopulatedPoints(Resolution resolution) {
    BasicDBList prepopulatedData = new BasicDBList();
    int offsetOrigin = 0;
    int numValues = 0;

    switch (resolution) {
    case SECOND:
        numValues = 60;
        break;
    case MINUTE:
        numValues = 60;
        break;
    case HOUR:
        numValues = 24;
        break;
    case DAY:
        numValues = 32;
        offsetOrigin = 1;
        break;
    case MONTH:
        numValues = 13;
        offsetOrigin = 1;
        break;
    default:
        // should never be reached
    } // switch

    for (int i = offsetOrigin; i < numValues; i++) {
        prepopulatedData
                .add(new BasicDBObject("offset", i).append("samples", 0).append("sum", 0).append("sum2", 0)
                        .append("min", Double.POSITIVE_INFINITY).append("max", Double.NEGATIVE_INFINITY));
    } // for

    return prepopulatedData;
}