Package com.ikanow.infinit.e.data_model.store.social.sharing

Examples of com.ikanow.infinit.e.data_model.store.social.sharing.SharePojo


    }//TESTED
    Map<ObjectId, BasicDBObject> shareContentCache = new HashMap<ObjectId, BasicDBObject>();
    List<SharePojo> sharesToUpdate = new LinkedList<SharePojo>();
    // Step through the aliases, update the content
    // Loop 1 update
    SharePojo shareForNewAliases = null;
    Set<String> erroredAliases = new HashSet<String>();
    HashMultimap<ObjectId, String> shareToAliasMapping = HashMultimap.create();
    for (EntityFeaturePojo alias: aliasesToUpdate) {
      List<SharePojo> sharesForThisAlias = aliasMapping.get(alias.getIndex());
      if ((null == sharesForThisAlias) && bUpsert) { // This is a new alias and not ignoring upserts
        if (null == shareForNewAliases) { // Haven't yet assigned such a share
          shareForNewAliases = this.upsertSharePrep(communityIdStr, shareContentCache, aliasMapping);
          if (null == shareForNewAliases) {
            erroredAliases.add(alias.getIndex());
            continue;
          }
          sharesToUpdate.add(shareForNewAliases);
        }
        BasicDBObject shareContent =  shareContentCache.get(shareForNewAliases.get_id()); // (exists by construction)
        shareContent.put(alias.getIndex(), alias.toDb());
        shareToAliasMapping.put(shareForNewAliases.get_id(), alias.getIndex());
      }//TESTED
      else if (null != sharesForThisAlias) {
        for (SharePojo share: sharesForThisAlias) {
          BasicDBObject shareContent =  shareContentCache.get(share.get_id());
          if (null == shareContent) {
View Full Code Here


  }//TESTED
 
  // ALIAS UTILITIES:
 
  private SharePojo upsertSharePrep(String communityIdStr, Map<ObjectId, BasicDBObject> shareContentCache, Map<String, List<SharePojo>> aliasMapping) {
    SharePojo shareForNewAliases = null;
    BasicDBObject contentForNewAliases = null;
    for (List<SharePojo> shares: aliasMapping.values()) {
      if (!shares.isEmpty()) {
        shareForNewAliases = shares.iterator().next();
        try {
          String json = shareForNewAliases.getShare();
          contentForNewAliases = (BasicDBObject) JSON.parse(json);
          shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases);
          break;
        }
        catch (Exception e) {} // Try a different share
      }
    }//TESTED
    if (null == shareForNewAliases) { // Didn't find one, so going to have to create something
      EntityFeaturePojo discard = new EntityFeaturePojo();
      discard.setDisambiguatedName("DISCARD");
      discard.setType("SPECIAL");
      discard.setIndex("DISCARD");
      EntityFeaturePojo docDiscard = new EntityFeaturePojo();
      docDiscard.setDisambiguatedName("DOCUMENT_DISCARD");
      docDiscard.setType("SPECIAL");
      docDiscard.setIndex("DOCUMENT_DISCARD");
      contentForNewAliases = new BasicDBObject("DISCARD", discard.toDb());
      contentForNewAliases.put("DOCUMENT_DISCARD", docDiscard);
      ResponseObject response = new ResponseObject();
      shareForNewAliases = this.addShareJSON("Alias Share: " + communityIdStr, "An alias share for a specific community", "infinite-entity-alias", "{}", response);
      if ((null == shareForNewAliases) || !response.isSuccess()) {
        return null;
      }//TESTED
     
      // Remove share from personal community
      try {
        ShareCommunityPojo currCommunity =  shareForNewAliases.getCommunities().iterator().next();
        String removeCommunityIdStr = currCommunity.get_id().toString();
        if (!communityIdStr.equals(removeCommunityIdStr)) { // (obv not if this is my community somehow, don't think that's possible)
          this.removeShareFromCommunity(shareForNewAliases.get_id().toString(), removeCommunityIdStr, response);
          if (!response.isSuccess()) {
            return null;       
          }
        }
      }
      catch (Exception e) {} // do nothing I guess, not in any communities?
     
      this.addShareToCommunity(shareForNewAliases.get_id().toString(), "aliasComm", communityIdStr, response);
      if (!response.isSuccess()) {
        return null;       
      }
    }//TESTED
    shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases);
    return shareForNewAliases;
  }//TESTED
View Full Code Here

        throw new RuntimeException(errorString.toString()); // (handled below)
      }
     
      // 4) Add the results to the original data
     
      SharePojo savedQueryShare = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(
          new BasicDBObject(SharePojo._id_, savedQuery._parentShare.get_id())), SharePojo.class);
     
      if (null != savedQueryShare) {
        DocumentQueueControlPojo toModify = DocumentQueueControlPojo.fromApi(savedQueryShare.getShare(), DocumentQueueControlPojo.class);
        List<BasicDBObject> docs = (List<BasicDBObject>) rp.getData();
        if ((null != docs) && !docs.isEmpty()) {
          if (null == toModify.getQueueList()) {
            toModify.setQueueList(new ArrayList<ObjectId>(docs.size()));
          }
          ObjectId ignoreBeforeId = toModify.getLastDocIdInserted();
          ObjectId maxDocId = toModify.getLastDocIdInserted();

          //DEBUG
          //System.out.println("before, num docs=" + toModify.getQueueList().size() + " adding " + docs.size() + " from " + ignoreBeforeId);
         
          // Some alerting preamble
          StringBuffer alertText = null;
          StringBuffer alertTitle = null;
          String rootUrl = new PropertiesManager().getURLRoot().replace("/api/", "");
          int maxDocsToAdd = 10; // (default)
          boolean alert = false;
          if ((null != toModify.getQueryInfo().getAlert()) && (null != toModify.getQueryInfo().getAlert().getEmailAddresses())
              && !toModify.getQueryInfo().getAlert().getEmailAddresses().isEmpty())
          {
            alert = true;
            alertText = new StringBuffer();
            if (null != toModify.getQueryInfo().getAlert().getMaxDocsToInclude()) {
              maxDocsToAdd = toModify.getQueryInfo().getAlert().getMaxDocsToInclude();
              if (maxDocsToAdd < 0) {
                maxDocsToAdd = Integer.MAX_VALUE;
              }
            }                       
            createAlertPreamble(alertText, toModify.getQueryInfo().getQuery(), savedQuery._parentShare.get_id(), rootUrl);
          }//TESTED
         
          // Add new docs...

          int numDocsAdded = 0;
          for (BasicDBObject doc: docs) {
            ObjectId docId = doc.getObjectId(DocumentPojo._id_);
            if (null != docId) {
              if (null != ignoreBeforeId) {
                if (docId.compareTo(ignoreBeforeId) <= 0) { // ie docId <= ignoreBeforeId
                  continue;
                }
              }//(end check if this doc has already been seen)             
             
              toModify.getQueueList().add(0, docId);

              //Alerting
              if (alert) {
                // (this fn checks if the max number of docs have been added):
                createAlertDocSummary(alertText, numDocsAdded, maxDocsToAdd, doc, rootUrl);
                numDocsAdded++;
              }
             
              if (null == maxDocId) {
                maxDocId = docId;
              }
              else if (maxDocId.compareTo(docId) < 0) { // ie maxDocId < docId
                maxDocId = docId;
              }
            }//TESTED (test5)
          }//(end loop over new docs)
         
          // More alerting
          if (alert && (numDocsAdded > 0)) {
            alertTitle = new StringBuffer("IKANOW: Queue \"").append(toModify.getQueueName()).append("\" has ").append(numDocsAdded).append(" new");
            if (numDocsAdded == 1) {
              alertTitle.append(" document.");
            }
            else {
              alertTitle.append(" documents.");             
            }
            // (terminate the doc list)
            if (maxDocsToAdd > 0) {
              alertText.append("</ol>");
              alertText.append("\n");
            }
           
            String to = (Arrays.toString(toModify.getQueryInfo().getAlert().getEmailAddresses().toArray()).replaceAll("[\\[\\]]", "")).replace(',', ';');
            try {
              new SendMail(null, to, alertTitle.toString(), alertText.toString()).send("text/html");
            }
            catch (Exception e) {
              //DEBUG
              //e.printStackTrace();
            }
          }//TESTED
         
          // Remove old docs...
         
          int maxDocs = query.output.docs.numReturn;
          if (null != toModify.getMaxDocs()) { // override
            maxDocs = toModify.getMaxDocs();
          }
         
          if (toModify.getQueueList().size() > maxDocs) {
            toModify.setQueueList(toModify.getQueueList().subList(0, maxDocs));
          }//TESTED (test2.2)

          //DEBUG
          //System.out.println("after, num docs=" + toModify.getQueueList().size() + " at " + maxDocId);
         
          // Update share info:
          toModify.setLastDocIdInserted(maxDocId);
         
          // We've modified the share so update it:
          savedQueryShare.setShare(toModify.toApi());
          savedQueryShare.setModified(new Date());
          DbManager.getSocial().getShare().save(savedQueryShare.toDb());
         
        }//(end found some docs)
       
      }//(end found share)
     
View Full Code Here

  public static DocumentQueueControlPojo getSavedQueryToRun()
  {
    DocumentQueueControlPojo toReturn = null;
    try {
      SharePojo savedQueryShare = SharePojo.fromDb(DbManager.getCustom().getSavedQueryCache().findAndRemove(new BasicDBObject()), SharePojo.class);
      if (null == savedQueryShare) { // nothing to process
        return null;
      }//TESTED (test1)
      toReturn = DocumentQueueControlPojo.fromApi(savedQueryShare.getShare(), DocumentQueueControlPojo.class);
     
      // Get the user communities and append the query if possible
      Set<ObjectId> userAccess = AuthUtils.getCommunities(savedQueryShare.getOwner().get_id());
      if (userAccess.isEmpty()) {
        return toReturn; // (_parentShare is null so will be discarded)
      }
      if (null != toReturn.getQueryInfo().getQueryId()) {
        BasicDBObject queryQuery = new BasicDBObject(SharePojo._id_, toReturn.getQueryInfo().getQueryId());
        queryQuery.put(ShareCommunityPojo.shareQuery_id_, new BasicDBObject(DbManager.in_, userAccess));
        SharePojo shareContainingQuery = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(queryQuery), SharePojo.class);

        if (null == shareContainingQuery) {
          return toReturn; // (_parentShare is null so will be discarded)
        }
        toReturn.getQueryInfo().setQuery(AdvancedQueryPojo.fromApi(shareContainingQuery.getShare(), AdvancedQueryPojo.class));
      }//TESTED (test6)
     
      if (null != toReturn.getQueryInfo().getQuery()) {
        // Check the communityIds...
        if (null != toReturn.getQueryInfo().getQuery().communityIds) {
View Full Code Here

      //query.getQueryInfo().setFrequencyOffset(null);
    }   
    if (6 == testNum) {
      query.getQueryInfo().setQueryId(fixedShareId_2);
     
      SharePojo queryShare = new SharePojo();
      queryShare.set_id(fixedShareId_2);
      queryShare.setType("infinite-saved-query");
      queryShare.setTitle("test query " + testNum);
      queryShare.setDescription("test query " + testNum);
      queryShare.setShare(query.getQueryInfo().getQuery().toApi());   
      addSocial(queryShare);
      DbManager.getSocial().getShare().save(queryShare.toDb());

      query.getQueryInfo().setQuery(null);
    }
   
    // Build a template share
    SharePojo share = new SharePojo();
    if (testNum == 2) {
      share.set_id(fixedShareId_2);   
      query.setQueueList(new ArrayList<ObjectId>(5));
      for (int i = 0; i < 5; ++i) {
        query.getQueueList().add(new ObjectId());
      }
    }
    else {
      share.set_id(fixedShareId_1);
    }
    share.setType(DocumentQueueControlPojo.SavedQueryQueue);
    share.setTitle("test" + testNum);
    share.setDescription("test1" + testNum);
    share.setShare(query.toApi());   
    addSocial(share);
   
    DbManager.getSocial().getShare().save(share.toDb());
  }
View Full Code Here

        }
      }
      BasicDBObject query = new BasicDBObject(SharePojo._id_, new ObjectId(shareid));
      query.put(ShareCommunityPojo.shareQuery_id_, new BasicDBObject(MongoDbManager.in_, communityIds));

      SharePojo share = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(query),SharePojo.class);
     
      if (null == share) {
        throw new RuntimeException("Can't find JAR file or share or custom table or source, or insufficient permissions");
      }
     
      // The JAR owner needs to be an admin:
      //TODO (INF-2118): At some point would like there to be a choice ... if not admin then must inherit the Infinit.e sandbox version
      // ... there seemed to be some issues with that however so for now will just allow all admin jars and no non-admin jars
      // (see other INF-2118 branch)
      if (prop_custom.getHarvestSecurity()) {
        if (!AuthUtils.isAdmin(share.getOwner().get_id())) {
          throw new RuntimeException("Permissions error: only administrators can upload custom JARs");
        }
      }//TESTED (by hand)
           
      String extension = ".cache";
      if ((null != share.getMediaType()) && (share.getMediaType().contains("java-archive"))) {
        extension = ".cache.jar";
      }
      else if ((null != share.getMediaType()) && (share.getMediaType().contains("gzip"))) {
        extension = ".cache.tgz";
      }
      else if ((null != share.getMediaType()) && (share.getMediaType().contains("zip"))) {
        extension = ".cache.zip";
      }
      String tempFileName = assignNewJarLocation(prop_custom, shareid + extension);
      File tempFile = new File(tempFileName);
     
      // Compare dates (if it exists) to see if we need to update the cache)
     
      if (!tempFile.exists() || (tempFile.lastModified() < share.getModified().getTime())) {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFileName));
        if ( share.getBinaryId() != null )
        {     
          GridFSDBFile file = DbManager.getSocial().getShareBinary().find(share.getBinaryId());           
          file.writeTo(out);       
        }
        else
        {
          out.write(share.getBinaryData());
        }
      }//TESTED
     
      return tempFileName;
    }
View Full Code Here

          }//TESTED (by hand)
         
          // b) try getting the source
          BasicDBObject shareQuery = new BasicDBObject(SharePojo._id_, sourceId);
          shareQuery.put(SharePojo.ShareCommunityPojo.shareQuery_id_, new BasicDBObject(DbManager.in_, _userCommunities));
          SharePojo share = SharePojo.fromDb(MongoDbManager.getSocial().getShare().findOne(shareQuery), SharePojo.class);         
          if (null == share) {
            addErrMessage("Couldn't find share, or don't have read access: " + sourceInfo);
            return null;
          }
          _savedCredentials.put(sourceInfo, (retVal = (BasicDBObject) com.mongodb.util.JSON.parse(share.getShare())));
        }
        catch (Exception e) {
          StringBuffer sbErr = new StringBuffer();
          Globals.populateStackTrace(sbErr, e);
          addErrMessage("Unknown error: " + sbErr.toString());
          return null; // (do nothing)
        }
      }//TESTED (including cache, by hand)
      catch (Exception e) {
        // Source info is a share type
        BasicDBObject shareQuery = new BasicDBObject(SharePojo.type_, sourceInfo);
        shareQuery.put(SharePojo.ShareOwnerPojo.shareQuery_id_, _callingUserId);
       
        List<SharePojo> credentialShares = SharePojo.listFromDb(DbManager.getSocial().getShare().find(shareQuery), SharePojo.listType());
        if ((null == credentialShares) || credentialShares.isEmpty()) {
          addErrMessage("Couldn't find shares of this type, or don't have read access: " + sourceInfo);
          return null;         
        }//TESTED (by hand)
        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)
              retVal.putAll((BSONObject)x);
            }
          }
          catch (Exception ee) {
            StringBuffer sbErr = new StringBuffer();
            Globals.populateStackTrace(sbErr, e);
            addErrMessage("Failed to parse: " + share.get_id() + " : " + share.getTitle() + ": " + sbErr.toString());           
          }
        }//TESTED (by hand)
        if (retVal.isEmpty()) {
          addErrMessage("Failed to add any fields from: " + sourceInfo);
          return null;
View Full Code Here

    {
      BasicDBObject dbo = (BasicDBObject)DbManager.getSocial().getShare().findOne(query);
      if (null != dbo) {
        byte[] bytes = (byte[]) dbo.remove("binaryData");
       
        SharePojo share = SharePojo.fromDb(dbo, SharePojo.class);
        share.setBinaryData(bytes);
       
        //new way of handling bytes, if has a binaryid, get bytes from there and set
 
        if (returnContent) {         
          if (null != share.getBinaryId()) {
            share.setBinaryData(getGridFile(share.getBinaryId()));           
          }//TESTED
          else if (null != share.getDocumentLocation()) {
            try {
              if ((null != share.getType()) && share.getType().equalsIgnoreCase("binary")) {
                File x = new File(share.getDocumentLocation().getCollection());
                share.setBinaryData(FileUtils.readFileToByteArray(x));
              }//TESTED
              else { // text
                share.setShare(getReferenceString(share));               
              }//TESTED
            }
            catch (Exception e) {
              rp.setResponse(new ResponseObject("Get Share", false, "Unable to get share reference: " + e.getMessage()));           
              return rp;
            }//TESTED
         
          // (else share.share already set)
        }
        else { // don't return content
          share.setShare(null);         
        }//TESTED
       
        rp.setData(share, new SharePojoApiMap(memberOf));               
        rp.setResponse(new ResponseObject("Share", true, "Share returned successfully"));
      }
View Full Code Here

      List<SharePojo> shares = SharePojo.listFromDb(dbc, SharePojo.listType());
      if (!shares.isEmpty()) {
       
        Iterator<SharePojo> shareIt = shares.iterator();
        while (shareIt.hasNext()) {
          SharePojo share = shareIt.next();
          if (null != share.getDocumentLocation()) {
            try {
              if ((null == share.getType()) || !share.getType().equalsIgnoreCase("binary")) {
                // (ignore binary references)
                share.setShare(this.getReferenceString(share));
              }//TESTED
            }
            catch (Exception e) { // couldn't access data, just remove data from list
              share.setShare("{}");
            }
          }
        }//TESTED
       
        rp.setData(shares, new SharePojoApiMap(memberOf));
View Full Code Here

  {
    ResponsePojo rp = new ResponsePojo();   
    try
    {     
      // Create a new SharePojo object
      SharePojo share = new SharePojo();
      share.setCreated(new Date());
      share.setModified(new Date());
      share.setType(type);
      share.setTitle(title);
      share.setDescription(description);     
      HashSet<ObjectId> endorsedSet = new HashSet<ObjectId>();
      share.setEndorsed(endorsedSet); // (you're always endorsed within your personal community)
      endorsedSet.add(new ObjectId(ownerIdStr));       
      share.setMediaType(mediatype);
      ObjectId id = new ObjectId();
      share.set_id(id);
     
      // Get ShareOwnerPojo object and personal community
      PersonPojo owner = getPerson(new ObjectId(ownerIdStr));
      share.setOwner(getOwner(owner));
      share.setCommunities(getPersonalCommunity(owner));

      // Serialize the ID and Dates in the object to MongoDB format
      //Save the binary objects into separate db
      ObjectId gridid = saveGridFile(bytes);
      share.setBinaryId(gridid);
     
      // Save the document to the share collection
      DbManager.getSocial().getShare().save(share.toDb());
      rp.setResponse(new ResponseObject("Share", true, "New binary share added successfully. ID in data field"));
      rp.setData(id.toString(), null);
    }
    catch (Exception e)
    {
View Full Code Here

TOP

Related Classes of com.ikanow.infinit.e.data_model.store.social.sharing.SharePojo

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.