2012-07-30 4 views
3

주말에 촬영되었습니다. 여기에 마지막으로 일요일 밤 도움을 청합니다.Google GData API를 사용하여 스프레드 시트를 일괄 수정 OAUTH/OPEN ID 도메인 계정을 사용하여

Google 마켓 플레이스 앱은 2 개의 OAUTH를 사용해야합니다. aproach는 Google 문서 스프레드 시트에 50,000 개의 레코드를 작성해야합니다. 스프레드 시트에 레코드를 작성, 크기 조정, 이름 변경 및 기록 할 수 있습니다. 개별적으로 100 개의 행을 작성하는 데 최대 1 분이 소요되므로 일괄 업데이트를 사용해야합니다. 일괄 업데이트를 가져올 수 없습니다. 아래의 코드는 최선의 시도입니다 - "Token invalid - Invalid token 401"이 계속 나타납니다. 모든 샘플 코드는 3 개의 다리가있는 oauth 용이지만 마켓 플레이스 앱이므로 사용자에게 앱 승인 메시지를 표시 할 수 없습니다.

openid 및 2LO를 사용하여 일괄 스프레드 시트 업데이트의 예를 찾는 것이 좋습니다.

 final String SCOPE = "https://spreadsheets.google.com/feeds/spreadsheets/private/full"; 
     SpreadsheetService spreadsheetService; 
     String consumerKey = getInitParameter("consumer_key"); 
     String consumerSecret = getInitParameter("consumer_secret"); 
     GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
     oauthParameters.setOAuthConsumerKey(consumerKey); 
     oauthParameters.setOAuthConsumerSecret(consumerSecret); 
     oauthParameters.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH); 
     oauthParameters.setScope(SCOPE); 
     OAuthSigner signer = new OAuthHmacSha1Signer(); 
     spreadsheetService = new SpreadsheetService("nimbits-com"); 
     String title = entity.getName().getValue(); 

     try { 

      spreadsheetService.setOAuthCredentials(oauthParameters, signer); 
      spreadsheetService.setProtocolVersion(SpreadsheetService.Versions.V3); 
      SpreadsheetQuery query = new SpreadsheetQuery(new URL(SCOPE)); 
      query.addCustomParameter(new Query.CustomParameter("xoauth_requestor_id", user.getEmail().getValue())); 
      query.setTitleQuery(title); 
      SpreadsheetFeed feed = spreadsheetService.query(query, SpreadsheetFeed.class); 


//works fine up to this point, I get the feed and spreadsheet. 

      if (feed != null && ! feed.getEntries().isEmpty()) { 

       com.google.gdata.data.spreadsheet.SpreadsheetEntry wsEntry = feed.getEntries().get(0); 
       WorksheetEntry sheet = wsEntry.getWorksheets().get(0); 
       CellFeed batchRequest = new CellFeed(); 
       String batchId = "R" + 2 + "C" + 1; 


       URL entryUrl = new URL(sheet.getCellFeedUrl().toString() + "/" + batchId); 

//Invalid TOKEN error here, trying to get the entry. 
CellEntry batchOperation = spreadsheetService.getEntry(entryUrl, CellEntry.class); 
       batchOperation.setService(spreadsheetService); 
       batchOperation.changeInputValueLocal("test"); 
       BatchUtils.setBatchId(batchOperation, batchId); 
       BatchUtils.setBatchOperationType(batchOperation, BatchOperationType.UPDATE); 
       batchRequest.getEntries().add(batchOperation); 


       CellFeed cellFeed = spreadsheetService.getFeed(sheet.getCellFeedUrl(), CellFeed.class); 
       Link batchLink = cellFeed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM); 
       URL batchUrl = new URL(batchLink.getHref()); 
       spreadsheetService.batch(batchUrl, batchRequest); 
      } 
     } catch (MalformedURLException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 

     } catch (ServiceException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } catch (IOException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } catch (OAuthException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } 

이 샘플은 레코드 하나를 일괄 적으로 작성하려고합니다. 스프레드 시트의 크기를 조정 했으므로 괜찮습니다. 토큰을 설정하는 방법이나 2LO로이 요청을 완료하는 방법을 볼 수 없습니다. URL에 xoauth_requestor_id를 추가하려고했습니다. 내가 현상금을 시작한 이후

편집 :

이 코드 조각이 완벽하게 작동하고 내가 가지고있는 2LO 인증을 기존 스프레드 시트에 1 개 행을 추가합니다. 50,000 개의 행을 신속하게 불러 오도록 수정해야합니다.

함께 넣어 다양한 소스에서 몇 가지 예제 코드를 빼서 : 스프레드 시트하지만 두 다리가 인증 덤프 -

@Override 
public void addSpreadsheetHeader(Entity entity) throws NimbitsException { 
    final User user = UserServiceFactory.getServerInstance().getHttpRequestUser(
      this.getThreadLocalRequest()); 


    SpreadsheetService spreadsheetService; 
    String consumerKey = getInitParameter("consumer_key"); 
    String consumerSecret = getInitParameter("consumer_secret"); 
    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
    oauthParameters.setOAuthConsumerKey(consumerKey); 
    oauthParameters.setOAuthConsumerSecret(consumerSecret); 
    spreadsheetService = new SpreadsheetService("nimbits-com"); 


    // SpreadsheetEntry entry = new SpreadsheetEntry(); 
    String title = entity.getName().getValue(); 
    // entry.setTitle(TextConstruct.plainText(title)); 



    try { 
     spreadsheetService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); 
     SpreadsheetQuery query = new SpreadsheetQuery(new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full")); 
     query.addCustomParameter(new Query.CustomParameter("xoauth_requestor_id", user.getEmail().getValue())); 

     query.setTitleQuery(title); 
     SpreadsheetFeed feed = spreadsheetService.query(query, SpreadsheetFeed.class); 
     if (feed != null && ! feed.getEntries().isEmpty()) { 
      com.google.gdata.data.spreadsheet.SpreadsheetEntry wsEntry = feed.getEntries().get(0); 
      WorksheetEntry sheet = wsEntry.getWorksheets().get(0); 
      URL cellFeedUrl= sheet.getCellFeedUrl(); 
      CellFeed cellFeed= spreadsheetService.getFeed (cellFeedUrl, CellFeed.class); 
      CellEntry cellEntry; 

      cellEntry= new CellEntry (1, 1, "Timestamp"); 
      cellFeed.insert (cellEntry); 

      cellEntry= new CellEntry (1, 2, "Value"); 
      cellFeed.insert (cellEntry); 

      cellEntry= new CellEntry (1, 3, "Latitude"); 
      cellFeed.insert (cellEntry); 

      cellEntry= new CellEntry (1, 4, "Longitude"); 
      cellFeed.insert (cellEntry); 

      cellEntry= new CellEntry (1, 5, "Annotation"); 
      cellFeed.insert (cellEntry); 

      cellEntry= new CellEntry (1, 6, "Data"); 
      cellFeed.insert (cellEntry); 

     } 



    } catch (MalformedURLException e) { 
     LogHelper.logException(this.getClass(), e); 
     throw new NimbitsException(e); 

    } catch (ServiceException e) { 
     LogHelper.logException(this.getClass(), e); 
     throw new NimbitsException(e); 
    } catch (IOException e) { 
     LogHelper.logException(this.getClass(), e); 
     throw new NimbitsException(e); 
    } catch (OAuthException e) { 
     LogHelper.logException(this.getClass(), e); 
     throw new NimbitsException(e); 
    } 


} 

답변

5

는 여기가 문서화되지 않은 작은 것들의 많은입니다. 문서 키는 새 문서 .getId를 작성할 때 리턴 된 오브젝트에서옵니다.

@Override 
    public void dumpValues(final Entity entity, int count) throws NimbitsException { 
     String[][] values = { {"1", "2", "3", "4", "5"}, 
       {"a", "b", "c", "d", "e"}, 
       {"dummy", "foo", "bar", "x", "y"}}; 


     final User user = //where you store your user 


     SpreadsheetService spreadsheetService; 
     String consumerKey = getInitParameter("consumer_key"); 
     String consumerSecret = getInitParameter("consumer_secret"); 
     GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
     oauthParameters.setOAuthConsumerKey(consumerKey); 
     oauthParameters.setOAuthConsumerSecret(consumerSecret); 
     spreadsheetService = new SpreadsheetService("nimbits-com"); 
     spreadsheetService.setProtocolVersion(SpreadsheetService.Versions.V1); 


     try { 
      spreadsheetService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); 
      String key = String.valueOf(this.getThreadLocalRequest().getSession().getAttribute("docId")); 
      FeedURLFactory urlFactory = FeedURLFactory.getDefault(); 
      URL cellFeedUrl = urlFactory.getCellFeedUrl(key, "od6", "private", "full"); 


      CellQuery q = new CellQuery(cellFeedUrl); 
      //CellQuery q = new CellQuery(worksheet.getCellFeedUrl()); 
      q.setMinimumRow(1); 
      q.setMaximumRow(1 + values.length); 
      q.setMinimumCol(1); 
      q.setMaximumCol(values[0].length); 
      q.setReturnEmpty(true); 
      q.addCustomParameter(new Query.CustomParameter("xoauth_requestor_id", user.getEmail().getValue())); 
      CellFeed cellFeed = spreadsheetService.query(q, CellFeed.class); 

      CellFeed batchRequestFeed = new CellFeed(); 

      // set values for each cell 
      int currentCellEntry=0; 
      for (int i=0; i < values.length; i++) { 
       for (int j=0; j < values[i].length; j++) { 

        CellEntry entry = new CellEntry(cellFeed.getEntries().get(currentCellEntry)); 
        entry.changeInputValueLocal(values[i][j]); 
        BatchUtils.setBatchId(entry, (new Integer(currentCellEntry)).toString()); 
        BatchUtils.setBatchOperationType(entry, BatchOperationType.UPDATE); 
        batchRequestFeed.getEntries().add(entry); 
        currentCellEntry++; 
       } 
      } 

      // upload cells 
      Link batchLink = cellFeed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM); 
      spreadsheetService.setHeader("If-Match", "*"); 

      CellFeed batchResponse = spreadsheetService.batch(new URL(batchLink.getHref()), batchRequestFeed); 
      spreadsheetService.setHeader("If-Match", null); 
      for (CellEntry entry : batchResponse.getEntries()) { 
       if (!BatchUtils.isSuccess(entry)) { 

        BatchStatus status = BatchUtils.getBatchStatus(entry); 
        throw new NimbitsException(BatchUtils.getBatchId(entry) + " " + status.getReason() + " " + status.getContent()); 
       } 
      } 
     } catch (IOException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } catch (ServiceException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } catch (OAuthException e) { 
      LogHelper.logException(this.getClass(), e); 
      throw new NimbitsException(e); 
     } 
+0

나를 위해 좋은 작품! –