Package com.mongodb

Examples of com.mongodb.BasicDBList


        retVal = new BasicDBObject();
        for (SharePojo share: credentialShares) {
          try {
            Object x = com.mongodb.util.JSON.parse(share.getShare());
            if (x instanceof BasicDBList) { // It's a list add all the k/vs from all the array els
              BasicDBList xl = (BasicDBList)x;
              for (Object o: xl) {
                retVal.putAll((BSONObject)o);               
              }
            }
            else { // (normal case, it's an object just add all k/vs)
View Full Code Here


      engine.put("output", returnVal);

      // Use BasicDBObject directly so I can reduce memory usage by setting the initial capacity depending on the size of the JSON array
//      BasicDBObject objFactory = new BasicDBObject();
//      engine.put("objFactory", objFactory);
      BasicDBList listFactory = new BasicDBList();
      engine.put("listFactory", listFactory);
      BasicDBList outList = new BasicDBList();
      engine.put("outList", outList);
 
      engine.eval("s1(output);");

      return outList;
View Full Code Here

        BasicDBObject dbo = (BasicDBObject) dbc.next();
        String sSourceKey = dbo.getString(SourcePojo.key_);
       
        // DON'T DEDUP LOGIC:
        if (!source.getDuplicateExistingUrls()) {
          BasicDBList communities = (BasicDBList) dbo.get(SourcePojo.communityIds_);
          for (Object communityIdObj: communities) {
            ObjectId communityId = (ObjectId) communityIdObj;
            if (source.getCommunityIds().contains(communityId)) { // Not allowed to duplicate off this
              _sameCommunitySources.add(sSourceKey);
              bMatchedInCommunity = true;
View Full Code Here

    if (bAdmin) {
      return true;
    }
    else {
      for (DBObject dbo: dbc) {
        BasicDBList commList = (BasicDBList) dbo.get(SourcePojo.communityIds_);
        if (null != commList) {
          if (commList.size() > 1) {
            return false;
          }
        }
      }
    }
View Full Code Here

     
      // Now do some authentication:
      // Check communities first since that involves no external DB queries:
      boolean isAuthorized = false;
      if (_isShare) {
        BasicDBList communities = (BasicDBList) _resultObj.get(SharePojo.communities_);
        for (Object communityObj: communities) {
          BasicDBObject communityDbo = (BasicDBObject) communityObj;
          ObjectId commId = communityDbo.getObjectId("_id");
          if (communityIdsStr.contains(commId.toString())) {
            isAuthorized = true;
            break;
          }
        }
      }//TESTED (7.*)
      else { //_isCustom
        BasicDBList communities = (BasicDBList) _resultObj.get(CustomMapReduceJobPojo.communityIds_);       
        for (Object communityObj: communities) {
          ObjectId commId = (ObjectId) communityObj;
          if (communityIdsStr.equals(commId)) {
            isAuthorized = true;
            break;
View Full Code Here

    if (standaloneEventAggregator.bSimulateAggregation) {
      bSummaries = false;
    }
    String sDocIsoPubDate = null;
 
    BasicDBList lev = (BasicDBList)(doc.get(DocumentPojo.associations_));
    if (null != lev)
    {
      for(Iterator<?> e0 = lev.iterator(); e0.hasNext();)
      {
        BasicDBObject e = (BasicDBObject)e0.next();
       
        String sEvType = e.getString(AssociationPojo.assoc_type_);
        boolean bIsFact = false;
View Full Code Here

    double score = 100.0;
   
    if (null != _asyncRequestsPerQuery) {
      int added = 0;
      BasicDBObject doc = null;
      BasicDBList bsonArray = new BasicDBList();
      PeekingIterator<FederatedRequest> it = Iterators.peekingIterator(_asyncRequestsPerQuery.iterator());
      while (it.hasNext()) {
       
        FederatedRequest request = it.next();
        if (null == request.cachedDoc) { // no cached doc
          try {
            if (null == request.cachedResult) {  // no cached value       
              if (null != request.importThread) {
                // 1) wait for the thread to finish
                if (null == request.endpointInfo.queryTimeout_secs) {
                  request.endpointInfo.queryTimeout_secs = 300;
                }
                for (int timer = 0; timer < request.endpointInfo.queryTimeout_secs; timer++) {
                  try {
                    request.importThread.join(1000L);
                    if (!request.importThread.isAlive()) {
                      break;
                    }
                  }//TESTED (by hand)
                  catch (Exception e) {
                   
                  }
                }
                if (request.importThread.isAlive()) {
                  request.errorMessage = new RuntimeException("Script timed out");
                }//TESTED (by hand)
               
                // 2) Get the results
                if (null != request.errorMessage) {
                  if (_testMode) {
                    throw new RuntimeException(request.errorMessage);
                  }
                }
                else if (null == request.scriptResult) {               
                  if (_testMode) {
                    throw new RuntimeException("Script mode: no cached result found from: " + request.requestParameter);
                  }
                }
                else {
                  String url = buildScriptUrl(request.mergeKey, request.queryIndex);
                  if (_cacheMode) { // (don't cache python federated queries in test mode)
                    this.cacheApiResponse(url, request.scriptResult, request.endpointInfo);
                  }
                  bsonArray.add(request.scriptResult);               
                }
              } // end script mode
              else { // HTTP mode
                Response endpointResponse = request.responseFuture.get();
                request.asyncClient.close();
                request.asyncClient = null;
   
                String jsonStr = endpointResponse.getResponseBody();
                String url = endpointResponse.getUri().toURL().toString();
               
                Object bsonUnknownType = com.mongodb.util.JSON.parse(jsonStr);
                BasicDBObject bson = null;
                if (bsonUnknownType instanceof BasicDBObject) {
                  bson = (BasicDBObject) bsonUnknownType;
                }
                else if (bsonUnknownType instanceof BasicDBList) {
                  bson = new BasicDBObject("array", bsonUnknownType);
                }
                else if (bsonUnknownType instanceof String) {
                  bson = new BasicDBObject("value", bsonUnknownType);                 
                }
               
                //DEBUG
                if (_DEBUG) _logger.debug("DEB: postQA1: " + url + ": " + jsonStr);
               
                if (null != bson) {
                  MongoDbUtil.enforceTypeNamingPolicy(bson, 0);
                  this.cacheApiResponse(url, bson, request.endpointInfo);
                  bsonArray.add(bson);
                }
              }//(end script vs request method)
            }//TESTED (3.1, 4.2)
            else { // (just used cached value)
              //DEBUG
              if (_DEBUG) _logger.debug("DEB: postQA2: " + request.cachedResult.toString());
             
              bsonArray.add((BasicDBObject)request.cachedResult.get(SimpleFederatedCache.cachedJson_));
            }//TESTED (4.1, 4.3)
          }
          catch (Exception e) {
            //DEBUG
            if (null == request.subRequest) {
              _logger.error("Error with script: " + e.getMessage());
              if (_testMode) {
                throw new RuntimeException("Error with script: " + e.getMessage(), e);
              }           
            }
            else {
              _logger.error("Error with " + request.subRequest.endPointUrl + ": " + e.getMessage());
              if (_testMode) {
                throw new RuntimeException("Error with " + request.subRequest.endPointUrl + ": " + e.getMessage(), e);
              }
            }
          }
          if (!it.hasNext() || (request.mergeKey != it.peek().mergeKey)) { // deliberate ptr arithmetic
            String url = buildScriptUrl(request.mergeKey, request.queryIndex);
           
            //DEBUG
            if (_DEBUG) _logger.debug("DEB: postQA3: " + url + ": " + bsonArray);         
           
            doc = createDocFromJson(bsonArray, url, request, request.endpointInfo);
          }
        } // (end if no cached doc)
        else { // cached doc, bypass lots of processing because no merging and doc already built
          doc = request.cachedDoc;
        }//TESTED (by hand)
         
        if (null != doc) {
          // Cache the document unless already cached (or caching disabled)
          if ((null == request.cachedDoc) && _cacheMode &&
              ((null == request.endpointInfo.cacheTime_days) || (request.endpointInfo.cacheTime_days >= 0)))
          {
            if (null != request.cachedDoc_expired) {
              ObjectId updateId = request.cachedDoc_expired.getObjectId(DocumentPojo.updateId_);
              if (null != updateId) {
                doc.put(DocumentPojo.updateId_, updateId);
              }
              else {
                doc.put(DocumentPojo.updateId_, request.cachedDoc_expired.getObjectId(DocumentPojo._id_));
              }
              BasicDBObject docUpdate = new BasicDBObject(DocumentPojo.url_, doc.getString(DocumentPojo.url_));
              docUpdate.put(DocumentPojo.sourceKey_, doc.getString(DocumentPojo.sourceKey_));
              DbManager.getDocument().getMetadata().remove(docUpdate);
             
              //DEBUG
              if (_DEBUG) _logger.debug("DEB: postQA4a: re-cached ... " + docUpdate.toString() + ": " + doc.getObjectId(DocumentPojo.updateId_));
            }
            //DEBUG
            if (_DEBUG) _logger.debug("DEB: postQA4b: cached ... " + doc);         
            DbManager.getDocument().getMetadata().save(doc);

          }//TESTED (by hand, 3 cases: cached not expired, cached expired first time, cached expired multiple times)
         
          if (!grabbedScores) {
            if (!docs.isEmpty()) {
              BasicDBObject topDoc = docs.get(0);
              aggregateSignif = topDoc.getDouble(DocumentPojo.aggregateSignif_, aggregateSignif);
              queryRelevance = topDoc.getDouble(DocumentPojo.queryRelevance_, queryRelevance);
              score = topDoc.getDouble(DocumentPojo.score_, score);
              grabbedScores = true;
             
              // OK would also like to grab the original matching entity
              BasicDBList ents = (BasicDBList) topDoc.get(DocumentPojo.entities_);
              if (null != ents) {
                for (Object entObj: ents) {
                  BasicDBObject ent = (BasicDBObject)entObj;
                  String entIndex = ent.getString(EntityPojo.index_, "");
                  if (entIndex.equals(request.queryIndex)) {
                    ents = (BasicDBList) doc.get(DocumentPojo.entities_);
                    if (null != ents) {
                      ents.add(ent);
                    }
                    break;
                  }
                }
              }//TESTED (by hand)
View Full Code Here

 
  // UTILITY
 
  public BasicDBObject createDocFromJson(BasicDBList jsonList, String url, FederatedRequest request, SourceFederatedQueryConfigPojo endpointInfo) {
    BasicDBObject doc = null; // (don't create unless needed)
    BasicDBList ents = null;
    StringBuffer entVals = null;
    HashSet<String> entDedup = null;
   
    if (_testMode) { // In test mode, need to return the JSON even if no entities are specified
      doc = new BasicDBObject();
    }
    if (null != endpointInfo.docConversionMap) {
      for (Map.Entry<String, String> docInfo: endpointInfo.docConversionMap.entrySet()) {
        for (Object jsonObj: jsonList) {
          BasicDBObject json = (BasicDBObject)jsonObj;
          try {
            String key = docInfo.getKey();
            // (allow user to not prepend array: if they don't want to)
            if ((1 == json.size()) && json.containsKey((Object)"array")) {
              if (!key.startsWith("array:") &&
                  !key.startsWith(":array") && !key.startsWith("$:array") &&
                  !key.startsWith("::") && !key.startsWith("$::"))
              {
                if (key.startsWith(":")) { // jpath
                  key = ":array" + key;
                }
                else if (key.startsWith("$:")) { // jpath
                  key = "$:array" + key.substring(1);
                }
                else {
                  key = "array:" + key;
                }                 
              }               
            }//TESTED (by hand)
            if (key.startsWith(":")) { // jpath
              key = "$" + key;
            }
            // NOTE: *not* org.json.JSONArray
            JSONArray candidateEntities = null;
            if (key.startsWith("$")) {
              JSONArray candidateEntities_tmp = JsonPath.read(json.toString(), key.replace(':', '.'));
              if (null != candidateEntities_tmp) {
                candidateEntities = new JSONArray();
                for (Object o: candidateEntities_tmp) {
                  if (o instanceof String) {
                    candidateEntities.add(o);
                  }
                  else if (o instanceof JSONArray) {
                    candidateEntities.addAll((JSONArray)o);
                  }
                }//TESTED (displayUrl vs entities, 3.2)
              }             
              //DEBUG
              //System.out.println(candidateEntities);
             
            }//(TESTED (permutations above by hand))
            else {
              String s = (String) MongoDbUtil.getProperty(json, key.replace(':', '.'));
              if (null != s) {
                candidateEntities = new JSONArray();
                candidateEntities.add(s);
              }
            }//TESTED (3.1)                     
           
            if (null != candidateEntities) for (int i = 0; i < candidateEntities.size(); ++i) {
              Object o = candidateEntities.get(i);
              if (!(o instanceof String)) {
                continue;
              }
              String s = o.toString();
              if (null == doc) {
                doc = new BasicDBObject();
                //(various fields added below)
              }
              if (docInfo.getValue().equalsIgnoreCase(DocumentPojo.displayUrl_)) {
                doc.put(DocumentPojo.displayUrl_, s);
              }//TESTED (3.1, 4.*)
              else { // Entities!
                if (null == ents) {
                  ents = new BasicDBList();
                }
                String index = s.toLowerCase() + "/" + docInfo.getValue().toLowerCase();
               
                if (null == entDedup) {
                  entDedup = new HashSet<String>();
                }
                else if (entDedup.contains(index)) { // Entity deduplication
                  continue;
                }//TESTED (3.2)
                entDedup.add(index);
               
                if (null == entVals) {
                  entVals = new StringBuffer(": ");
                }
                else {
                  entVals.append(", ");
                }
                entVals.append(s);
               
                String dimension = null;
                if (null != endpointInfo.typeToDimensionMap) {
                  try {
                    dimension = EntityPojo.Dimension.valueOf(endpointInfo.typeToDimensionMap.get(docInfo.getValue())).toString();
                  }
                  catch (Exception e) {}
                }
                if (null == dimension) {
                  dimension = EntityPojo.Dimension.What.toString();
                }//TESTED (by hand)
               
                // (alternative to "made up" values would be to go looking in the existing docs/ents?)
                // (we'll try to avoid that for now...)
                BasicDBObject ent = new BasicDBObject();
                ent.put(EntityPojo.disambiguated_name_, s);
                ent.put(EntityPojo.type_, docInfo.getValue());
                ent.put(EntityPojo.dimension_, dimension);
                ent.put(EntityPojo.relevance_, 1.0);
                ent.put(EntityPojo.doccount_, 1L); // (ie relative to this query)
                ent.put(EntityPojo.averageFreq_, 1.0);
                ent.put(EntityPojo.datasetSignificance_, 10.0); // (ie relative to this query)
                ent.put(EntityPojo.frequency_, 1.0);
                ent.put(EntityPojo.index_, index);
                ent.put(EntityPojo.queryCoverage_, 100.0); // (ie relative to this query)
                ent.put(EntityPojo.totalfrequency_, 1.0); // (ie relative to this query)
                ents.add(ent);
              }//TESTED (3.1, 4.*)
            }
          }
          catch (Exception e) {
            //(do nothing? null or the wrong type)
View Full Code Here

  // Deduplication logic
 
  static boolean community_areDuplicates(TempDocBucket lhs, TempDocBucket rhs) {
    if (lhs.url.equals(rhs.url)) {
      // These are probably duplicates, we'll do some more tests...
      BasicDBList lhsEnts = (BasicDBList) lhs.dbo.get(DocumentPojo.entities_);
      BasicDBList rhsEnts = (BasicDBList) rhs.dbo.get(DocumentPojo.entities_);
     
      if (!((null != lhsEnts) ^ (null != rhsEnts))) // ie both null or neither null
      {
        if (null != lhsEnts) {
          if (lhsEnts.size() != rhsEnts.size()) {
            return false;
          }//TESTED
          if (lhsEnts.size() > 0) {
            BasicDBObject lhsFirstEnt = (BasicDBObject) lhsEnts.get(0);
            BasicDBObject rhsFirstEnt = (BasicDBObject) rhsEnts.get(0);
            String lhsIndex = lhsFirstEnt.getString(EntityPojo.index_);
            String rhsIndex = rhsFirstEnt.getString(EntityPojo.index_);
            if ((null != lhsIndex) && (null != rhsIndex)) {
              if (!lhsIndex.equals(rhsIndex)) {
                return false;
              }
            }
          }//(end "random" entity test)
          //TESTED
        }
      } // (end entity count test)
     
      // Finally we'll just count the events:
      BasicDBList lhsEvents = (BasicDBList) lhs.dbo.get(DocumentPojo.associations_);
      BasicDBList rhsEvents = (BasicDBList) rhs.dbo.get(DocumentPojo.associations_);
      if (!((null != lhsEvents) ^ (null != rhsEvents))) // ie both null or neither null
      {
        if (null != lhsEvents) {
          if (lhsEvents.size() != rhsEvents.size()) {
            return false;
          }//TESTED         
        }
      }//(end event count test)
           
View Full Code Here

 
  // Combine duplicate documents
 
  static void community_combineDuplicateDocs(TempDocBucket masterDoc) {
    //(source key)
    BasicDBList masterSourceKeyList = (BasicDBList) masterDoc.dbo.get(DocumentPojo.sourceKey_);
    String masterSourceKey = (masterSourceKeyList.size() > 0) ? (String)masterSourceKeyList.get(0) : null;
    HashSet<String> sourceKeySet = null;
    //(community Id)
    BasicDBList masterCommunityList = (BasicDBList) masterDoc.dbo.get(DocumentPojo.communityId_);
    ObjectId masterCommunityId = (masterCommunityList.size() > 0) ? (ObjectId)masterCommunityList.get(0) : null;
    HashSet<ObjectId> communityIdSet = null;
    //(source title)
    BasicDBList masterSourceList = null;
    String masterSource = null;
    HashSet<String> sourceSet = null;
    //(mediaType)
    BasicDBList masterTypeList = null;
    String masterType = null;
    HashSet<String> typeSet = null;
    //(tags)
    BasicDBList masterTagList = null;
    String masterTag = null;
    HashSet<String> tagSet = null;
   
    for (TempDocBucket slave = masterDoc.dupList; null != slave; slave = slave.dupList) {
      String sourceKey = slave.dbo.getString(DocumentPojo.sourceKey_);
      int nCommunityPos = sourceKey.indexOf('#');
      if ((nCommunityPos > 0) && (null != sourceKey)) {
        sourceKey = sourceKey.substring(0, nCommunityPos);
      }//TESTED
     
      // Always combine communities:
      ObjectId communityIdObj = (ObjectId) slave.dbo.get(DocumentPojo.communityId_);
      communityIdSet = combineElements(communityIdSet, TypeErasureWorkaround.Type.OBJECTID, masterCommunityList, masterCommunityId, slave, null, communityIdObj);
     
      if ((null != masterSourceKey) && (null != sourceKey) && sourceKey.equals(masterSourceKey)) {
        continue;
      }//TESTED
     
      // else fall through to...
     
      // Combine source keys:
      sourceKeySet = combineElements(sourceKeySet, TypeErasureWorkaround.Type.STRING, masterSourceKeyList, masterSourceKey, slave, null, sourceKey);
     
      // Combine source titles:
      masterSourceList = (BasicDBList) masterDoc.dbo.get(DocumentPojo.source_);
      masterSource = (masterSourceList.size() > 0) ? (String)masterSourceList.get(0) : null;
      String slaveSource =  slave.dbo.getString(DocumentPojo.source_);
      sourceSet = combineElements(sourceSet, TypeErasureWorkaround.Type.STRING, masterSourceList, masterSource, slave, null, slaveSource);
     
      // Combine media types:
      masterTypeList = (BasicDBList) masterDoc.dbo.get(DocumentPojo.mediaType_);
      masterType = (masterTypeList.size() > 0) ? (String)masterTypeList.get(0) : null;
      String slaveType =  slave.dbo.getString(DocumentPojo.mediaType_);
      typeSet = combineElements(typeSet, TypeErasureWorkaround.Type.STRING, masterTypeList, masterType, slave, null, slaveType);
     
      // Combine tags:
      masterTagList = (BasicDBList) masterDoc.dbo.get(DocumentPojo.tags_);
      masterTag = (masterTagList.size() > 0) ? (String)masterTagList.get(0) : null;
      BasicDBList slaveTagList =  (BasicDBList) slave.dbo.get(DocumentPojo.tags_);
      tagSet = combineElements(tagSet, TypeErasureWorkaround.Type.STRING, masterTagList, masterTag, slave, slaveTagList, null);
     
    } // (end loop over slaves)
   
    // Now use any sets created to fill in
View Full Code Here

TOP

Related Classes of com.mongodb.BasicDBList

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.