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

Examples of com.ikanow.infinit.e.data_model.api.ResponsePojo.ResponseObject


  {     
    ResponsePojo rp = new ResponsePojo();
   
    //validate term object to be a lat,lng or location
    if ( term == null )
      rp.setResponse(new ResponseObject("Suggestions Geo", false, "search term is required, was not provided"));
   
    boolean isLatLng = false;
    Double[] latlng = new Double[2];
    String[] terms = term.split(",");
    if ( terms.length == 2 )
    {
      try
      {
        latlng[0] = Double.parseDouble(terms[0]);
        latlng[1] = Double.parseDouble(terms[1]);
        isLatLng = true;
      }
      catch (Exception e)
      {
        //could not parse as double, treat as location
        //just fall through
      }
    }
    List<SearchSuggestPojo> locations = null;
    if ( isLatLng )
    {
      //lookup location name via lat/lng
       locations = reverseGeoLookup(latlng[0], latlng[1]);
     
    }
    else
    {
      //lookup lat/lngs via location name
      rp.setResponse(new ResponseObject("Suggestions Geo", false, "Search term provided could not be parsed as lat, lng... geotag lookup by name not yet supported."));
      return rp;
    }
   
    rp.setData(locations, new SearchSuggestPojoApiMap());
    rp.setResponse(new ResponseObject("Suggestions Geo", true, term));
    return rp;
  }
View Full Code Here


      else if ( field.equals(AssociationFeaturePojo.verb_))
        searchTerm = verb;
      else
        searchTerm = ent2;

      rp.setResponse(new ResponseObject("Association Suggestions", true, searchTerm));
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
      rp.setResponse(new ResponseObject("Association Suggestions",false,"Response returned unsuccessfully: " + ex.getMessage()));
    }
    return rp;
 
View Full Code Here

    }
    else if (field.equalsIgnoreCase("gazateer_index") || field.equalsIgnoreCase(EntityPojo.index_)) { // (for bw compatibility from GUI)
      field = EntityFeaturePojo.index_;
    }
    else if (!field.equalsIgnoreCase(EntityFeaturePojo.index_)) {
      rp.setResponse(new ResponseObject("aliasSuggest",false, "Field " + field + " not recognized"));
      return rp;
    }

    try
    {        
      Collection<Set<String>> aliasSet = findAliases(null, field, Arrays.asList(term), userIdStr, communityIdStrList).values();
      Set<String> superSet = new HashSet<String>();
      for (Set<String> set : aliasSet )
      {
        superSet.addAll(set);
      }      
      rp.setData(superSet, (BasePojoApiMap<String>)null);
      rp.setResponse(new ResponseObject("aliasSuggest",true,"Successfully returned aliases"));

      if (nSysTime > (lastAliasLog + 5000)) {
        lastAliasLog = nSysTime;
        logMsg.setLength(0);
        logMsg.append("knowledge/aliasSuggest query=").append(term);
        logMsg.append(" found=").append(superSet.size());
        logMsg.append(" time=").append(System.currentTimeMillis() - nSysTime).append(" ms");
        logger.info(logMsg.toString());
      }         
    }
    catch (Exception e)
    {
      // If an exception occurs log the error
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("aliasSuggest",false,"Error returning aliases"));
    }
    return rp;
  }   
View Full Code Here

       {
         JSON.parse(json);
       }
       catch (Exception e)
       {
         rp.setResponse(new ResponseObject("Parsing JSON",false,"The value passed via the json parameter could not be" +
         " parsed as valid JSON."));
         isValidJson = false;
       }
     }
    
     if (isValidJson)
     {
       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 {
           // Every call needs communityid so check now
          
           boolean validCommunities = ((communityid == null) || communityid.startsWith("*")) ?
               true : // (in this case, we apply the regex to user communities, so don't need to validate)
                 SocialUtils.validateCommunityIds(cookieLookup, communityid);

           if ( validCommunities == false )
           {
             rp = new ResponsePojo();
             rp.setResponse(new ResponseObject("Verifying Communities",false,"Community IDs are not valid for this user"));
           }
           else
           {
             if ( action.equals("saveSource") )
             {
View Full Code Here

        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

        }
      }
      //TESTED (update case, normal case, and intermediate case where both update and original still exist)
     
      if (null == dbo) {
        rp.setResponse(new ResponseObject("Doc Info",true,"Document not found"));
        return rp;
      }
      DocumentPojo dp = DocumentPojo.fromDb(dbo, DocumentPojo.class);
      if (bReturnFullText)
      {
        if (null == dp.getFullText()) { // (Some things like database records might have this stored already)
          byte[] storageArray = new byte[200000];
          DBCollection contentDB = DbManager.getDocument().getContent();
          BasicDBObject contentQ = new BasicDBObject(CompressedFullTextPojo.url_, dp.getUrl());
          contentQ.put(CompressedFullTextPojo.sourceKey_, new BasicDBObject(MongoDbManager.in_, Arrays.asList(null, dp.getSourceKey())));
          BasicDBObject fields = new BasicDBObject(CompressedFullTextPojo.gzip_content_, 1);
          BasicDBObject dboContent = (BasicDBObject) contentDB.findOne(contentQ, fields);
          if (null != dboContent) {
            byte[] compressedData = ((byte[])dboContent.get(CompressedFullTextPojo.gzip_content_));       
            ByteArrayInputStream in = new ByteArrayInputStream(compressedData);
            GZIPInputStream gzip = new GZIPInputStream(in);       
            int nRead = 0;
            StringBuffer output = new StringBuffer();
            while (nRead >= 0) {
              nRead = gzip.read(storageArray, 0, 200000);
              if (nRead > 0) {
                String s = new String(storageArray, 0, nRead, "UTF-8");
                output.append(s);
              }
            }
            dp.setFullText(output.toString());
            dp.makeFullTextNonTransient();
          }
        }       
      }
      else if (!returnRawData) {
        dp.setFullText(null); // (obviously will normally contain full text anyway)
      }
      else // if ( returnRawData )
      {
        //check if the harvest type is file, return the file instead
        //if file is db return the json
        //get source
        SourcePojo source = getSourceFromKey(dp.getSourceKey());
        if ( source.getExtractType().equals( "File" ))
        {
          //get file from harvester
          String fileURL = dp.getUrl();
          if ( dp.getSourceUrl() != null )
            fileURL = dp.getSourceUrl();
          byte[] bytes = FileHarvester.getFile(fileURL, source);
          if ( bytes == null )
          {
            // Try returning JSON instead
            String json = ApiManager.mapToApi(dp, new DocumentPojoApiMap());
            DocumentFileInterface dfp = new DocumentFileInterface();
           
            dfp.bytes = json.getBytes();
            dfp.mediaType = "application/json";
           
            rp.setResponse(new ResponseObject("Doc Info",true,"Document bytes returned successfully"));
            rp.setData(dfp, null);
            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;
          }
        }
        else
        {       
          String json = ApiManager.mapToApi(dp, new DocumentPojoApiMap());
          DocumentFileInterface dfp = new DocumentFileInterface();
         
          dfp.bytes = json.getBytes();
          dfp.mediaType = "application/json";
         
          rp.setResponse(new ResponseObject("Doc Info",true,"Document bytes returned successfully"));
          rp.setData(dfp, null);
          return rp;
        }       
      }
      rp.setData(dp, new DocumentPojoApiMap());
      rp.setResponse(new ResponseObject("Doc Info",true,"Feed info returned successfully"));
    }//(end full text vs raw data)
    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;
  }
View Full Code Here

      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

     {
       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
View Full Code Here

              }//TESTED (post proc and no post proc)
              sort = new BasicDBObject(sortField, sortDir);
            }//TOTEST
           
            // Case 1: DB
            rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",true,"Map reduce job completed at: " + cmr.lastCompletionTime));
            if ((null == cmr.exportToHdfs) || !cmr.exportToHdfs) {
              DBCursor resultCursor = null;
              if (limit > 0) {
                resultCursor = DbManager.getCollection(cmr.getOutputDatabase(), cmr.outputCollection).find(queryDbo, fieldsDbo).sort(sort).limit(limit);
              }
              else {
                resultCursor = DbManager.getCollection(cmr.getOutputDatabase(), cmr.outputCollection).find(queryDbo, fieldsDbo).sort(sort);
              }
              CustomMapReduceResultPojo cmrr = new CustomMapReduceResultPojo();
              cmrr.lastCompletionTime = cmr.lastCompletionTime;
              cmrr.results = resultCursor.toArray();
              rp.setData(cmrr);
            }//TESTED
            else { // Case 2: HDFS
             
              if ((null != cmr.outputKey) && (null != cmr.outputValue) &&
                cmr.outputKey.equalsIgnoreCase("org.apache.hadoop.io.text") && cmr.outputValue.equalsIgnoreCase("org.apache.hadoop.io.text"))
              {
                // special case, text file
                try {
                  rp.setData(HadoopUtils.getBsonFromTextFiles(cmr, limit, fields), (BasePojoApiMap<BasicDBList>) null);
                }
                catch (Exception e) {
                  rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"Files don't appear to be in text file format, did you run the job before changing the output to Text/Text?"));
                }
              }//TESTED
              else { // sequence file
                try {
                  rp.setData(HadoopUtils.getBsonFromSequenceFile(cmr, limit, fields), (BasePojoApiMap<BasicDBList>) null);
                }
                catch (Exception e) {
                  rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"Files don't appear to be in sequence file format, did you run the job with Text/Text?"));
                }
              }//TESTED
            }//TESTED
          }
          else
          {
            rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"Map reduce job has not completed yet"));
          }
        }
        else
        {
          rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"User is not a member of communities with read permissions"));
        }
      }
      else
      {
        rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"Job does not exist"));
      }
    }
    catch (Exception e)
    {
      // If an exception occurs log the error
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Custom Map Reduce Job Results",false,"error retrieving job info"));
    }
    return rp;
  }
View Full Code Here

              cmr.jobDependencies = getJobDependencies(jobsToDependOn);
              cmr.waitingOn = cmr.jobDependencies;
            }
            catch (Exception ex)
            {
              rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"Error parsing the job dependencies, did a title or id get set incorrectly or did a job not exist?"));
              return rp;
            }
          }
         
          //make sure title hasn't been used before
          DBObject dbo = DbManager.getCustom().getLookup().findOne(new BasicDBObject("jobtitle",title));
          if ( dbo == null )
          {
            Date nextRunDate = new Date(nextRun);
            Date now = new Date();
            String nextRunString = nextRunDate.toString();
            boolean bRunNowIfPossible = false;
            if ( nextRunDate.getTime() < now.getTime() ) {
              nextRunString = "next available timeslot";
              bRunNowIfPossible = true;
            }
            rp.setResponse(new ResponseObject("Schedule MapReduce Job",true,"Job scheduled successfully, will run on: " + nextRunString));
            rp.setData(cmr._id.toString(), null);
                       
            if (bRunNowIfPossible) {
              runJobAndWaitForCompletion(cmr, bQuickRun);
            }//TESTED
            else {
              DbManager.getCustom().getLookup().save(cmr.toDb());             
            }
          }
          else
          {         
            rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"A job already matches that title, please choose another title"));
          }
        }
        catch (IllegalArgumentException e)
        {
          logger.error("Exception Message: " + e.getMessage(), e);
          rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"No enum matching scheduled frequency, try NONE, DAILY, WEEKLY, MONTHLY"));
        }
        catch (Exception e)
        {
          // If an exception occurs log the error
          logger.error("Exception Message: " + e.getMessage(), e);
          rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"error scheduling job"));
        }         
      }
      else
      {
        rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"You do not have permission to use the given input collection."));
      }
    }
    else
    {
      rp.setResponse(new ResponseObject("Schedule MapReduce Job",false,"You do not have permissions for all the communities given."));
    }
    return rp;
  }
View Full Code Here

TOP

Related Classes of com.ikanow.infinit.e.data_model.api.ResponsePojo.ResponseObject

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.