Package com.ikanow.infinit.e.data_model.api

Examples of com.ikanow.infinit.e.data_model.api.ResponsePojo$TextSerializer


    return rp;
  }
 
  public ResponsePojo getFileContents(String userIdStr, String sourceKey, String relativePath, boolean isAdmin)
  {
    ResponsePojo rp = new ResponsePojo();
   
    try  {
      BasicDBObject query = new BasicDBObject(SourcePojo.key_, sourceKey);
      if ( !isAdmin )
        query.put(SourcePojo.communityIds_, new BasicDBObject(MongoDbManager.in_, SocialUtils.getUserCommunities(userIdStr)));
      BasicDBObject fields = new BasicDBObject(SourcePojo.url_, 1);
      fields.put(SourcePojo.extractType_, 1);
      fields.put(SourcePojo.file_, 1);
      fields.put(SourcePojo.isApproved_, 1);
      SourcePojo source = SourcePojo.fromDb(DbManager.getIngest().getSource().findOne(query, fields), SourcePojo.class);

      // TEST for security shenanigans
      String baseRelativePath = new File(".").getCanonicalPath();
      String actualRelativePath = new File(relativePath).getCanonicalPath();
      if (!actualRelativePath.startsWith(baseRelativePath)) {
        throw new RuntimeException("Access denied: " + relativePath);
      }     
      //(end security shenanigans)
     
      if (null == source) {
        throw new RuntimeException("Document source not found: " + sourceKey);
      }
      if ((null != source.getExtractType()) && !source.getExtractType().equals("File")) {
        throw new RuntimeException("Document source not a file: " + sourceKey + ", " + source.getExtractType());       
      }
      if (!source.isApproved()) {
        throw new RuntimeException("Document source not approved, access denied: " + sourceKey);       
      }
      String fileURL = source.getUrl() + relativePath;
      byte[] bytes = FileHarvester.getFile(fileURL, source);
      if ( bytes == null )
      {
        //fail
        rp.setResponse(new ResponseObject("Doc Info",false,"Could not find document: " + relativePath));
        return rp;
      }
      else
      {           
        DocumentFileInterface dfp = new DocumentFileInterface();
        dfp.bytes = bytes;
        dfp.mediaType = getMediaType(fileURL);
        rp.setResponse(new ResponseObject("Doc Info",true,"Document bytes returned successfully"));
        rp.setData(dfp, null);
        return rp;
      }     
    }
    catch (Exception e)
    {
      // If an exception occurs log the error
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Doc Info",false,"error returning feed: " + e.getMessage()));
    }
    // Return Json String representing the user
    return rp;
  }//TESTED
View Full Code Here


public class FeatureHandler {

  public ResponsePojo suggestAlias(String entity, String updateItem, String cookieLookup)
  {
    ResponsePojo rp = new ResponsePojo();
    return rp;
  }
View Full Code Here

   * @param updateItem
   * @return
   */
  public ResponsePojo approveAlias(String updateItem)
  {
    ResponsePojo rp = new ResponsePojo();
    return rp;
  }
View Full Code Here

    return rp;
  }
 
  public ResponsePojo declineAlias(String updateItem)
  {
    ResponsePojo rp = new ResponsePojo();
    return rp;
  }
View Full Code Here

    return rp;
  }
 
  public ResponsePojo allAlias(String cookieLookup)
  {
    ResponsePojo rp = new ResponsePojo();
    return rp;
  }   
View Full Code Here

    return rp;
  }   
 
  public ResponsePojo getEntityFeature(String updateItem)
  {
    ResponsePojo rp = new ResponsePojo();
    return rp;
  }   
View Full Code Here

  }
 
  @Get
  public Representation get()
  {
    ResponsePojo rp = new ResponsePojo();
     Date startTime = new Date();     
    
     if ( needCookie )
     {
       cookieLookup = RESTTools.cookieLookup(cookie);      
       if ( cookieLookup == null )
       {
         rp = new ResponsePojo();
         rp.setResponse(new ResponseObject("Cookie Lookup",false,"Cookie session expired or never existed, please login first"));
       }
       else
       {
         boolean isAdmin = RESTTools.adminLookup(cookieLookup);
         if ( action.equals("doc"))
         {
           rp = this.docHandler.getInfo(cookieLookup, sourcekey, docid, bReturnFullText, returnRawData, isAdmin);
           //return full text takes precedence over raw data
         }
         else if ( action.equals("file"))
         {
          rp = this.docHandler.getFileContents(cookieLookup, sourcekey, docid, isAdmin);
         }
        
         if ( !bReturnFullText && returnRawData && rp.getResponse().isSuccess() )
         {   
           try
           {
             //return the bytes like we do in shares
             DocumentFileInterface dfp = (DocumentFileInterface) rp.getData();
             if (null != dfp) {
               ByteArrayOutputRepresentation rep = new ByteArrayOutputRepresentation(MediaType.valueOf(dfp.mediaType));
               rep.setOutputBytes(dfp.bytes);
               return rep;
             }
           }
           catch (Exception ex )
           {
             rp = new ResponsePojo(new ResponseObject("Doc Info", false, "error converting bytes to output"));
          
         }
       }
     }
     else
     {
       //no methods that dont need cookies
     }
    
    
     Date endTime = new Date();
     rp.getResponse().setTime(endTime.getTime() - startTime.getTime());
     return new StringRepresentation(rp.toApi(), MediaType.APPLICATION_JSON);
  }
View Full Code Here

  public Representation get()
  {
    StringBuffer errorString = new StringBuffer("Query error");
    String data = null;
    MediaType mediaType = MediaType.APPLICATION_JSON; // (or RSS, or XML)
    ResponsePojo rp = null;

    String cookieLookup = null;
    try {
      // First off, check the cookie is valid:
      boolean bNotRss = !_requestDetails.output.format.equalsIgnoreCase("rss");
      // maybe don't need cookie for RSS?
      // Do a quick bit of further error checking here too:
      if (bNotRss) {
        if (!_requestDetails.output.format.equalsIgnoreCase("xml") &&
            !_requestDetails.output.format.equalsIgnoreCase("kml") &&
            !_requestDetails.output.format.equalsIgnoreCase("json"))
        {
          rp = new ResponsePojo();
          rp.setResponse(new ResponseObject("Output Format", false, "Unsupported output.format"));           
          data = rp.toApi();         
          return new StringRepresentation(data, mediaType);
        }
      }
     
      // Perform cookie lookup (for RSS may allow us to skip other auth logic)     
      cookieLookup = RESTTools.cookieLookup(_cookie);
     
      if (!bNotRss) { // RSS case
        ObjectId userId = null;
       
        //Set the commids to whatever is given in the query to
        _communityIdStrList = "";
        for ( ObjectId comm : _requestDetails.communityIds )
        {
          _communityIdStrList += "," + comm.toString();
        }
        _communityIdStrList = _communityIdStrList.substring(1);
        // Authentication:
        if (null == cookieLookup)
        { // (else don't need to both)
          Map<String, String> queryOptions = this.getQuery().getValuesMap();
          String sKey = queryOptions.get("key");
          String sKeyCmp = null;
          if (null != sKey) { // Key allowed to be 1 or 2 things: hash of query or password...
            sKeyCmp = PasswordEncryption.encrypt(this._queryJson); //encrypt
          }
          if ((null == sKeyCmp) || !sKeyCmp.equals(sKey)) {
            // User/password also allowed, TBD this will require SSL
            String user = queryOptions.get("user");
            String password = queryOptions.get("password");
            AuthenticationPojo authuser = null;
            if ((null != user) && (null != password)) {
              authuser = PasswordEncryption.validateUser(user,password, false);
            }
            if ( authuser == null )
            {
              // Don't have either authentication or key, bomb out...
              rp = new ResponsePojo();
              rp.setResponse(new ResponseObject("Cookie Lookup", false, "Cookie session expired or never existed, please login first or use valid key or user/pass"));
              data = rp.toApi();   
              mediaType = MediaType.APPLICATION_JSON;
              return new StringRepresentation(data, mediaType);
            }
            userId = authuser.getProfileId();
            cookieLookup = userId.toString();
           
          }
          //no other auth was used, try using the commid
          if ( null == cookieLookup )
          {
            userId = _requestDetails.communityIds.get(0);
            cookieLookup = userId.toString();
          }
          // Check user still exists, leave quietly if not
          try {
            BasicDBObject personQuery = new BasicDBObject("_id", userId);
            if (null == DbManager.getSocial().getPerson().findOne(personQuery)) {
              cookieLookup = null;
            }
          }
          catch (Exception e) { // unknown error, bail
            cookieLookup = null;           
          }
        }
        // end authentication for RSS
        // Also, since we're RSS, there's a bunch of output params that we know we don't need:
       
        // (output and output.docs are guaranteed to exist)
        _requestDetails.output.aggregation = null;
        _requestDetails.output.docs.ents = false;
        _requestDetails.output.docs.events = false;
        _requestDetails.output.docs.facts = false;
        _requestDetails.output.docs.summaries = false;
        _requestDetails.output.docs.eventsTimeline = false;
        _requestDetails.output.docs.metadata = false;
        //set cookielookup to first commid
       
      }
     
      // Fail out otherwise perform query
     
      if (cookieLookup == null) // wrong password, or rss-user doesn't exist
      {
        rp = new ResponsePojo();
        rp.setResponse(new ResponseObject("Cookie Lookup", false, "Cookie session expired or never existed, please login first"));
        data = rp.toApi();
      }
      else
      {
        //check communities are valid before using
        if ( SocialUtils.validateCommunityIds(cookieLookup, _communityIdStrList) )
          rp = _queryController.doQuery(cookieLookup, _requestDetails, _communityIdStrList, errorString);
        else {
          errorString.append(": Community Ids are not valid for this user");
          RESTTools.logRequest(this);
        }
       
        if (null == rp) { // Error handling including RSS
          rp = new ResponsePojo();
          rp.setResponse(new ResponseObject("Query Format", false, errorString.toString()));         
          data = rp.toApi();
        }       
        else { // Valid response, output handle all output formats

          // Output type
          // JSON
          //if (null != _requestDetails.output || _requestDetails.output.format.equalsIgnoreCase("json")) {
          // Modified based on logic (never able to get to xml or rss based on above logic)
          if (null == _requestDetails.output.format || _requestDetails.output.format.equalsIgnoreCase("json")) {
            data = rp.toApi();
          }
          else if (_requestDetails.output.format.equalsIgnoreCase("xml")) { // XML
            mediaType = MediaType.APPLICATION_XML;
            // Output type
            // Xml
            XmlOutput xml = new XmlOutput();
            data = xml.getFeeds(rp);
           
          }
          else if(_requestDetails.output.format.equalsIgnoreCase("kml")) {
            mediaType = MediaType.APPLICATION_XML;
            // Output type
            // Kml
            KmlOutput kml = new KmlOutput();
            data = kml.getDocs(rp);
          }
          else if (_requestDetails.output.format.equalsIgnoreCase("rss")) { // RSS
           
            mediaType = MediaType.APPLICATION_XML;
            RssOutput rss = new RssOutput();
           
            // print out the rss since we know that the response is not null
            data = rss.getDocs(rp);             
          }
          else { // Not pleasant after all this just to return an error :(
            rp = new ResponsePojo();
            rp.setResponse(new ResponseObject("Output Format", false, "Unsupported output.format"));           
            data = rp.toApi();
          }
        }
      }//TESTED
    }
    catch (Exception e) {
      // (LOGS TO CATALINA.OUT IF THE LOG MESSAGES AREN'T NECESSARY)
      e.printStackTrace();
     
      errorString.append(" userid=").append(cookieLookup).append(" groups=").append(_communityIdStrList);
      errorString.append( " error='").append(e.getMessage()).append("' stack=");
      Globals.populateStackTrace(errorString, e);
      if (null != e.getCause()) {
        errorString.append("[CAUSE=").append(e.getCause().getMessage()).append("]");
        Globals.populateStackTrace(errorString, e.getCause());       
      }
      String error = errorString.toString();
      _logger.error(error);
     
      //getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
      rp = new ResponsePojo();
      rp.setResponse(new ResponseObject("Query", false, error));
      data = rp.toApi();
    }//TESTED
   
    // One last check to ensure data has value (ugly ugly ugly)
    if (data == null ) {
      rp = new ResponsePojo();
      rp.setResponse(new ResponseObject("Query", false, errorString.toString()));
      data = rp.toApi();
    }
    return new StringRepresentation(data, mediaType);
  }   
View Full Code Here

   * @param userid
   * @return
   */
  public ResponsePojo getJobOrJobs(String userid, String jobIdOrTitle)
  {
    ResponsePojo rp = new ResponsePojo();   
    try
    {
      DBObject dbo = DbManager.getSocial().getPerson().findOne(new BasicDBObject(CustomMapReduceJobPojo._id_,
                                    new ObjectId(userid)));
      if (dbo != null )
      {
        PersonPojo pp = PersonPojo.fromDb(dbo, PersonPojo.class);
        HashSet<ObjectId> communities = new HashSet<ObjectId>();
        for ( PersonCommunityPojo pcp : pp.getCommunities())
          communities.add(pcp.get_id());
        BasicDBObject commquery = new BasicDBObject(
            CustomMapReduceJobPojo.communityIds_, new BasicDBObject(MongoDbManager.in_,communities));
        if (null != jobIdOrTitle) {
          try {
            if (jobIdOrTitle.contains(",")) {
              String[] jobidstrs = jobIdOrTitle.split("\\s*,\\s*");
              ObjectId[] jobids = new ObjectId[jobidstrs.length];
              for (int i = 0; i < jobidstrs.length; ++i) {
                jobids[i] = new ObjectId(jobidstrs[i]);
              }
              commquery.put(CustomMapReduceJobPojo._id_, new BasicDBObject(MongoDbManager.in_, jobids));
            }
            else {
              ObjectId jobid = new ObjectId(jobIdOrTitle);
              commquery.put(CustomMapReduceJobPojo._id_, jobid);
            }
          }
          catch (Exception e) { // Must be a jobtitle
            if (jobIdOrTitle.contains(",")) {
              String[] jobtitles = jobIdOrTitle.split("\\s*,\\s*");
              commquery.put(CustomMapReduceJobPojo.jobtitle_, new BasicDBObject(MongoDbManager.in_, jobtitles));
            }
            else {
              commquery.put(CustomMapReduceJobPojo.jobtitle_, jobIdOrTitle);
            }
          }
        }
        DBCursor dbc = DbManager.getCustom().getLookup().find(commquery);   
        if ((0 == dbc.count()) && (null != jobIdOrTitle)) {
          rp.setResponse(new ResponseObject("Custom Map Reduce Get Jobs",false,"No jobs to find"));         
        }
        else {
          rp.setResponse(new ResponseObject("Custom Map Reduce Get Jobs",true,"succesfully returned jobs"));
          List<CustomMapReduceJobPojo> jobs = CustomMapReduceJobPojo.listFromDb(dbc, CustomMapReduceJobPojo.listType());
          // Extra bit of code, need to eliminate partial community matches, eg if job belongs to A,B and we only belong to A
          // then obviously we can't see the job since it contains data from B
          Iterator<CustomMapReduceJobPojo> jobsIt = jobs.iterator();
          while (jobsIt.hasNext()) {
            CustomMapReduceJobPojo job = jobsIt.next();
            if (!communities.containsAll(job.communityIds)) {
              jobsIt.remove();
            }
          }//TOTEST
          rp.setData(jobs, new CustomMapReduceJobPojoApiMap(communities));
        }
      }
      else
      {
        rp.setResponse(new ResponseObject("Custom Map Reduce Get Jobs",false,"error retrieving users communities"));
      }     
    }
    catch (Exception e)
    {
      // If an exception occurs log the error
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Custom Map Reduce Get Jobs",false,"error retrieving jobs"));
    }
    return rp;
  }
View Full Code Here

   * @param forced
   * @return
   */
  public static ResponsePojo removeJob(String userid, String jobidortitle, boolean removeJar, boolean forced)
  {
    ResponsePojo rp = new ResponsePojo();   
   
    List<Object> searchTerms = new ArrayList<Object>();
    try
    {
      ObjectId jid = new ObjectId(jobidortitle);
      searchTerms.add(new BasicDBObject(CustomMapReduceJobPojo._id_,jid));
    }
    catch (Exception ex)
    {
      //oid failed, will only add title
    }
    searchTerms.add(new BasicDBObject(CustomMapReduceJobPojo.jobtitle_,jobidortitle));
       
    try
    {
      //find admin entry);
      DBObject dbo = DbManager.getCustom().getLookup().findOne(new BasicDBObject(DbManager.or_,searchTerms.toArray()));     
      if ( dbo != null )
      {       
        CustomMapReduceJobPojo cmr = CustomMapReduceJobPojo.fromDb(dbo, CustomMapReduceJobPojo.class);
        //make sure user is allowed to see results
        if ( forced || RESTTools.adminLookup(userid) || cmr.submitterID.toString().equals(userid) )
        {
          //make sure job is not running
          if ( ( cmr.jobidS == null ) || cmr.jobidS.equals( "CHECKING_COMPLETION" ) || cmr.jobidS.equals( "" ) ) // (< robustness, sometimes server gets stuck here...)
          {
            // Remove index
            if (CustomOutputIndexingEngine.isIndexed(cmr)) {
              CustomOutputIndexingEngine.deleteOutput(cmr)
            }//TESTED (by hand)
           
            //remove results and job
            DbManager.getCustom().getLookup().remove(new BasicDBObject(CustomMapReduceJobPojo._id_, cmr._id));
            DbManager.getCollection(cmr.getOutputDatabase(), cmr.outputCollection).drop();
            DbManager.getCollection(cmr.getOutputDatabase(), cmr.outputCollectionTemp).drop();

            // Delete HDFS directory, if one is used
            if ((null != cmr.exportToHdfs) && cmr.exportToHdfs) {
              HadoopUtils.deleteHadoopDir(cmr);
            }
           
            //remove jar file if unused elsewhere?
            if ( removeJar )
            {
              ResponsePojo sharerp = removeJarFile(cmr.jarURL, cmr.submitterID.toString());
              if ( sharerp.getResponse().isSuccess() )
              {
                rp.setResponse(new ResponseObject("Remove Custom Map Reduce Job",true,"Job, results, and jar removed successfully."));
              }
              else
              {
                rp.setResponse(new ResponseObject("Remove Custom Map Reduce Job",true,"Job and results removed successfully.  Removing the jar had an error: " + sharerp.getResponse().getMessage()));
              }
            }
            else
            {
              rp.setResponse(new ResponseObject("Remove Custom Map Reduce Job",true,"Job and results removed successfully.  Manually remove the jar if you are done with it."));
View Full Code Here

TOP

Related Classes of com.ikanow.infinit.e.data_model.api.ResponsePojo$TextSerializer

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.