Example usage for com.mongodb DBObject keySet

List of usage examples for com.mongodb DBObject keySet

Introduction

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

Prototype

Set<String> keySet();

Source Link

Document

Returns this object's fields' names

Usage

From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java

License:Apache License

@Override
public Model save(final Model model) {

    final URI schemaUri = model.getSchemaUri();
    final String collectionName = convertToCollectionName(schemaUri);

    final Keys keys = model.getKeys();
    DBObject mongoKeys = createMongoKeys(keys);

    if (!_Mongo.collectionExists(collectionName)) {
        final DBCollection mongoCollection = _Mongo.getCollection(collectionName);

        final DBObject collectionIndex = new BasicDBObject();
        final Set<String> indexKeySet = mongoKeys.keySet();
        for (final String indexKey : indexKeySet) {
            collectionIndex.put(indexKey, 1);
        }//from  w  w  w.  j  av a 2 s.  com

        final DBObject options = new BasicDBObject();
        options.put("background", true);

        mongoCollection.ensureIndex(collectionIndex, options);
    }

    final DBObject mongoObject;
    try {
        mongoObject = convertToMongoObject(model);
    } catch (ModelWritingException e) {
        throw new ServiceException("Failed to convert WRML model instance to a mongoDB object.", e, this);
    }

    final DBCollection mongoCollection = _Mongo.getCollection(collectionName);
    if (mongoCollection == null) {
        // Should not happen
        final String logMessage = getConfiguration().getName() + " - Collection should exist. Name:\n"
                + collectionName;

        LOG.error(logMessage);
        throw new ServiceException(logMessage, null, this);
    }

    final DBObject existingMongoObject = mongoCollection.findOne(mongoKeys);
    if (existingMongoObject != null) {
        mongoObject.put("_id", existingMongoObject.get("_id"));
    }

    String errorMessage = null;
    Throwable throwable = null;
    try {
        final WriteResult mongoWriteResult = mongoCollection.save(mongoObject);
        errorMessage = mongoWriteResult.getError();
    } catch (Throwable t) {
        errorMessage = t.getMessage();
        throwable = t;
    }

    if (errorMessage != null || throwable != null) {
        final String logMessage = getConfiguration().getName() + " - Error saving model (" + errorMessage
                + ").";

        LOG.error(logMessage);
        throw new ServiceException(logMessage, throwable, this);
    }

    // TODO: Should this return the saved model instead (using get?)?
    return model;

}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

License:Open Source License

/**
 * Utility method which can be used to create an IndexModel.
 *
 * @param fieldName   the attribute on which the index is to be created.
 * @param sortOrder   the sort order of the index to be created.
 * @param indexOption json string of the options of the index to be created.
 * @return IndexModel.//w  w w  .  j  a  v  a2  s  . c  o  m
 */
private static IndexModel createIndexModel(String fieldName, Integer sortOrder, String indexOption) {
    Document indexDocument = new Document(fieldName, sortOrder);
    if (indexOption == null) {
        return new IndexModel(indexDocument);
    } else {
        IndexOptions indexOptions = new IndexOptions();
        Document indexOptionDocument;
        try {
            indexOptionDocument = Document.parse(indexOption);
            for (Map.Entry<String, Object> indexEntry : indexOptionDocument.entrySet()) {
                Object value = indexEntry.getValue();
                switch (indexEntry.getKey()) {
                case "unique":
                    indexOptions.unique(Boolean.parseBoolean(value.toString()));
                    break;
                case "background":
                    indexOptions.background(Boolean.parseBoolean(value.toString()));
                    break;
                case "name":
                    indexOptions.name(value.toString());
                    break;
                case "sparse":
                    indexOptions.sparse(Boolean.parseBoolean(value.toString()));
                    break;
                case "expireAfterSeconds":
                    indexOptions.expireAfter(Long.parseLong(value.toString()), TimeUnit.SECONDS);
                    break;
                case "version":
                    indexOptions.version(Integer.parseInt(value.toString()));
                    break;
                case "weights":
                    indexOptions.weights((Bson) value);
                    break;
                case "languageOverride":
                    indexOptions.languageOverride(value.toString());
                    break;
                case "defaultLanguage":
                    indexOptions.defaultLanguage(value.toString());
                    break;
                case "textVersion":
                    indexOptions.textVersion(Integer.parseInt(value.toString()));
                    break;
                case "sphereVersion":
                    indexOptions.sphereVersion(Integer.parseInt(value.toString()));
                    break;
                case "bits":
                    indexOptions.bits(Integer.parseInt(value.toString()));
                    break;
                case "min":
                    indexOptions.min(Double.parseDouble(value.toString()));
                    break;
                case "max":
                    indexOptions.max(Double.parseDouble(value.toString()));
                    break;
                case "bucketSize":
                    indexOptions.bucketSize(Double.parseDouble(value.toString()));
                    break;
                case "partialFilterExpression":
                    indexOptions.partialFilterExpression((Bson) value);
                    break;
                case "collation":
                    DBObject collationOptions = (DBObject) value;
                    Collation.Builder builder = Collation.builder();
                    for (String collationKey : collationOptions.keySet()) {
                        String collationObj = value.toString();
                        switch (collationKey) {
                        case "locale":
                            builder.locale(collationObj);
                            break;
                        case "caseLevel":
                            builder.caseLevel(Boolean.parseBoolean(collationObj));
                            break;
                        case "caseFirst":
                            builder.collationCaseFirst(CollationCaseFirst.fromString(collationObj));
                            break;
                        case "strength":
                            builder.collationStrength(CollationStrength.valueOf(collationObj));
                            break;
                        case "numericOrdering":
                            builder.numericOrdering(Boolean.parseBoolean(collationObj));
                            break;
                        case "normalization":
                            builder.normalization(Boolean.parseBoolean(collationObj));
                            break;
                        case "backwards":
                            builder.backwards(Boolean.parseBoolean(collationObj));
                            break;
                        case "alternate":
                            builder.collationAlternate(CollationAlternate.fromString(collationObj));
                            break;
                        case "maxVariable":
                            builder.collationMaxVariable(CollationMaxVariable.fromString(collationObj));
                            break;
                        default:
                            log.warn("Annotation 'IndexBy' for the field '" + fieldName + "' contains "
                                    + "unknown 'Collation' Option key : '" + collationKey + "'. Please "
                                    + "check your query and try again.");
                            break;
                        }
                    }
                    if (builder.build().getLocale() != null) {
                        indexOptions.collation(builder.build());
                    } else {
                        throw new MongoTableException("Annotation 'IndexBy' for the field '" + fieldName + "'"
                                + " do not contain option for locale. Please check your query and try again.");
                    }
                    break;
                case "storageEngine":
                    indexOptions.storageEngine((Bson) value);
                    break;
                default:
                    log.warn("Annotation 'IndexBy' for the field '" + fieldName + "' contains unknown option "
                            + "key : '" + indexEntry.getKey() + "'. Please check your query and try again.");
                    break;
                }
            }
        } catch (JsonParseException | NumberFormatException e) {
            throw new MongoTableException("Annotation 'IndexBy' for the field '" + fieldName + "' contains "
                    + "illegal value(s) for index option. Please check your query and try again.", e);
        }
        return new IndexModel(indexDocument, indexOptions);
    }
}

From source file:pl.nask.hsn2.os.entities.MongoEntity.java

License:Open Source License

public static MongoEntity fromDBObject(DBObject source) {
    MongoEntity me = new MongoEntity();
    for (String key : source.keySet()) {
        me.put(key, source.get(key));/*from  w ww .  j a v  a2 s. c  om*/
    }
    return me;
}

From source file:uk.ac.imperial.presage2.db.mongodb.Environment.java

License:Open Source License

@Override
public Map<String, String> getProperties(int timestep) {
    Map<String, String> properties = new HashMap<String, String>();
    DBObject tState = this.getState(timestep);
    for (String key : tState.keySet()) {
        // skip simId key
        if (key.equals("simId") || key.equals("_id") || key.equals("time")) {
            continue;
        }/*w  w w  . ja  v a  2  s.  c om*/
        properties.put(key, tState.get(key).toString());
    }
    return Collections.unmodifiableMap(properties);
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToGephi.java

License:Apache License

public void exportGexf(File outputFile) throws IOException, GraphModelException, RevisionLogException {
    //Load colour mappings, if any
    Map<String, Color> nodeColorMappings = new HashMap<>();
    if (colorPropsFile != null) {
        nodeColorMappings.putAll(loadColorMappings(colorPropsFile));
    }// w  w w  .j  a v a  2 s  .co m

    // Init a gephi project - and therefore a workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    // Get a graph model - it exists because we have a workspace
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();

    // Create a directed graph based on this graph model
    DirectedGraph directedGraph = graphModel.getDirectedGraph();
    // Add column for node type
    AttributeController ac = Lookup.getDefault().lookup(AttributeController.class);
    AttributeModel attributeModel = ac.getModel();

    //        AttributeColumn nodeTypeCol = attributeModel.getNodeTable().addColumn(
    //                "nodeType",
    //                AttributeType.STRING );

    Map<String, AttributeColumn> nodeAttrNameToAttributeCol = new HashMap<>();

    // Create Gephi nodes
    //        Iterable<Node> nodeItr = new DeserialisingIterable<>(nodeDao.iterateAll(), marshaller, Node.class);
    //        for (Node node : nodeItr) {
    for (DBObject node : nodeDao.iterateAll()) {
        String uidStr = (String) node.get(NodeDAO.FIELD_UID);
        String name = (String) node.get(NodeDAO.FIELD_NAME);
        String type = (String) node.get(NodeDAO.FIELD_TYPE);
        Color nodeColour = DEFAULT_COLOR;
        if (nodeColorMappings.containsKey(type)) {
            nodeColour = nodeColorMappings.get(type);
        }

        org.gephi.graph.api.Node gephiNode = graphModel.factory().newNode(uidStr);
        if (name == null || name.isEmpty()) {
            gephiNode.getNodeData().setLabel(uidStr);
        } else {
            gephiNode.getNodeData().setLabel(name);
        }
        float[] rgbColorComp = nodeColour.getRGBColorComponents(null);
        gephiNode.getNodeData().setColor(rgbColorComp[0], rgbColorComp[1], rgbColorComp[2]);
        //      gephiNode.getNodeData().setColor(nodeColour.getRed(), nodeColour.
        //              getGreen(), nodeColour.getBlue());
        //            gephiNode.getNodeData().getAttributes().setValue( nodeTypeCol.getIndex(), node.getType() );

        for (String nodeAttrName : node.keySet()) {
            Object val = node.get(nodeAttrName);
            if (nodeAttrName.equals("_id")) {
                continue;
            }
            if (val instanceof BasicDBList) {
                val = val.toString();
            }
            if (val == null) {
                continue;
            }
            AttributeColumn attrCol = nodeAttrNameToAttributeCol.get(nodeAttrName);
            if (attrCol == null) {
                attrCol = attributeModel.getNodeTable().addColumn(nodeAttrName, AttributeType.parse(val));
                nodeAttrNameToAttributeCol.put(nodeAttrName, attrCol);
            }
            //        logger.info("nodeAttrName: " + nodeAttrName + ", val: " + val + ", type: " + val.getClass().getName());
            //        logger.info("attrCol: " + attrCol);
            gephiNode.getNodeData().getAttributes().setValue(attrCol.getIndex(), val);
        }

        directedGraph.addNode(gephiNode);
    }

    // Create Gephi edges; currently with a standard weight of 1
    // and no set color
    Iterable<Edge> edgeItr = new DeserialisingIterable<>(edgeDao.iterateAll(), marshaller, Edge.class);
    for (Edge edge : edgeItr) {
        String fromUidStr = edge.getFromUid();
        String toUidStr = edge.getToUid();
        org.gephi.graph.api.Edge gephiEdge = graphModel.factory().newEdge(directedGraph.getNode(fromUidStr),
                directedGraph.getNode(toUidStr), 1f, true);
        gephiEdge.getEdgeData().setLabel(edge.getType());
        directedGraph.addEdge(gephiEdge);
    }

    // Print out a summary of the full graph
    System.out.println("Complete Nodes: " + directedGraph.getNodeCount() + " Complete Edges: "
            + directedGraph.getEdgeCount());

    // This line is a hack to get around a weird NullPointerException
    // which crops up when exporting to gexf. See url below for details:
    // https://forum.gephi.org/viewtopic.php?f=27&t=2337
    DynamicModel dynamicModel = Lookup.getDefault().lookup(DynamicController.class).getModel();

    // Export full graph in GEXF format
    ExportController ec = Lookup.getDefault().lookup(ExportController.class);
    System.out.println(outputFile.getAbsoluteFile());
    ec.exportFile(outputFile);

}

From source file:uk.ac.ncl.aries.entanglement.shell.EntanglementShell.java

License:Apache License

@Command
public void printPropertiesOfNamedNode(String nodeType, String wellKnownName)
        throws RevisionLogException, GraphModelException {
    DBObject node = nodeDao.getByName(nodeType, wellKnownName);
    if (node == null) {
        System.out.println("No node with name: " + wellKnownName);
        return;//ww  w  . j av  a  2s. com
    }
    StringBuilder sb = new StringBuilder("Annotations for node: ");
    sb.append(wellKnownName).append("\n");
    for (String propName : node.keySet()) {
        Object val = node.get(propName);
        sb.append("  * ").append(val.getClass().getName()).append(": ").append(propName).append(" --> ")
                .append(val).append("\n");
    }
    System.out.println(sb);
}