0

Google 워드 프로세서에 문제가 있습니다. OAuth 2.0을 사용하여 모든 파일을 검색하고 싶습니다. - (MediaSource의 MS = service.getMedia 여기Google docs api for Java (예외)

Exception in thread "main" java.lang.NullPointerException 
at GoogleBlack.readUrl(GoogleBlack.java:95) 
at GoogleBlack.getDocument(GoogleBlack.java:87) 
at GoogleBlack.go(GoogleBlack.java:187) 
at GoogleBlack.main(GoogleBlack.java:222) 

코드 내가

import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.BufferedReader; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.URL; 
import java.util.Arrays; 
import java.util.List; 

import com.google.api.client.auth.oauth2.Credential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.jackson.JacksonFactory; 
import com.google.gdata.client.GoogleService; 
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken; 
import com.google.gdata.client.docs.DocsService; 
import com.google.gdata.data.MediaContent; 
import com.google.gdata.data.docs.DocumentListEntry; 
import com.google.gdata.data.docs.DocumentListFeed; 
import com.google.gdata.data.media.MediaSource; 
import com.google.gdata.util.ServiceException; 

public class GoogleBlack { 

private static final String APPLICATION_NAME = "Homework"; 
public DocsService service; 
public GoogleService spreadsheetsService; 
static String CLIENT_ID = "***********"; 
static String CLIENT_SECRET = "**************"; 
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; 
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds"); 

public void getSpreadSheet(String id, String i, String ids, String type) throws Exception { 
    UserToken docsToken = (UserToken) service.getAuthTokenFactory() 
      .getAuthToken(); 
    UserToken spreadsheetsToken = (UserToken) spreadsheetsService 
      .getAuthTokenFactory().getAuthToken(); 
    service.setUserToken(spreadsheetsToken.getValue()); 

    URL url = null; 

    if(type.equals("doc")) 
    { 
     url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids); 
    } 

    else 
    { 
     url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0"); 
     i += ".xls"; 
    } 

    System.out.println("Spred = " + url.toString()); 

    readUrl1(url.toString(), i, type); 
    service.setUserToken(docsToken.getValue()); 
} 

public void readUrl1(String url, String i, String type) throws IOException, ServiceException 
{ 
    MediaContent mc = new MediaContent(); 
    mc.setUri(url); 
    MediaSource ms = service.getMedia(mc); 

    System.out.println("Name: "+i); 
    BufferedInputStream bin = new BufferedInputStream(ms.getInputStream()); 
    OutputStream out = new FileOutputStream(i); 
    BufferedOutputStream bout = new BufferedOutputStream(out); 

    while (true) { 
     int datum = bin.read(); 
     if (datum == -1) 
     break; 
     bout.write(datum); 
    } 
    bout.flush(); 
} 

public void getDocument(String id, String i) throws Exception { 
    URL url = new URL(id); 
    readUrl(url,i); 
} 

public void readUrl(URL url, String i) throws Exception { 
    MediaContent mc = new MediaContent(); 
    mc.setUri(url.toString()); 
    System.out.println("Url "+ url.toString()); 
    System.out.println("MC: " + mc.toString()); 
    MediaSource ms = service.getMedia(mc); 

    System.out.println("Name: "+i); 
    BufferedInputStream bin = new BufferedInputStream(ms.getInputStream()); 
    OutputStream out = new FileOutputStream(i); 
    BufferedOutputStream bout = new BufferedOutputStream(out); 

    while (true) { 
     int datum = bin.read(); 
     if (datum == -1) 
     break; 
     bout.write(datum); 
    } 
    bout.flush(); 






//  FileOutputStream fout = null; 
//  fout = new FileOutputStream(i); 
//  fout.write(cbuf.); 
//  fout.close(); 

} 

static Credential getCredentials() { 
    HttpTransport transport = new NetHttpTransport(); 
    JacksonFactory jsonFactory = new JacksonFactory(); 

    // Step 1: Authorize --> 
    String authorizationUrl = 
     new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build(); 

    // Point or redirect your user to the authorizationUrl. 
    System.out.println("Go to the following link in your browser:"); 
    System.out.println(authorizationUrl); 

    // Read the authorization code from the standard input stream. 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("What is the authorization code?"); 
    String code = null; 
    try { 
     code = in.readLine(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    // End of Step 1 <-- 

    // Step 2: Exchange --> 
    GoogleTokenResponse response = null; 
    try { 
     response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, 
      code, REDIRECT_URI).execute(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    // End of Step 2 <-- 

    // Build a new GoogleCredential instance and return it. 
    return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET) 
     .setJsonFactory(jsonFactory).setTransport(transport).build() 
     .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken()); 
    } 

public void go() throws Exception { 


    DocsService service = new DocsService(APPLICATION_NAME); 
    service.setOAuth2Credentials(getCredentials()); 

    URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/"); 

    DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class); 

    System.out.println("Feed " + feed.getEntries().size()); 

    for(int i = 0; i < feed.getEntries().size(); i++) 
    { 

      DocumentListEntry entry = feed.getEntries().get(i); 
      if(entry.getType().equals("file")) 
      { 
       MediaContent mc1 = (MediaContent) entry.getContent(); 
       String UrlForDownload = mc1.getUri(); 
       System.out.println("Type is: " + entry.getType()); 
       System.out.println("File Name is: " + entry.getTitle().getPlainText()); 
       System.out.println("URL "+ UrlForDownload); 

       getDocument(UrlForDownload, entry.getFilename()); 
      } 

      else 
      { 
       MediaContent mc1 = (MediaContent) entry.getContent(); 
       String UrlForDownload = mc1.getUri(); 
       System.out.println("URL "+ UrlForDownload); 
       System.out.println("Type is: " + entry.getType()); 
       System.out.println("File Name is: " + entry.getTitle().getPlainText()); 

       if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали")) 
       { 
        continue; 
       } 

       if(entry.getType().equals("spreadsheet")) 
       { 
        String name = entry.getTitle().getPlainText().replaceAll(" ", ""); 
        System.out.println("name: " + name); 
        getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls"); 
       } 
       else 
       { 
        String name = entry.getTitle().getPlainText().replaceAll(" ", ""); 
        System.out.println("name: " + name); 
        getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc"); 
       } 
      } 
    } 

} 

public static void main(String[] args) throws Exception { 

    new GoogleBlack().go(); 

} 

} 

95 행을 사용할 수있다 : 문제는 당신이하고, 파일을 다운로드하려고 승인이 날이 오류를 제공 한 번이다 mc);

87 행 - readUrl (url, i);

187 행 - getDocument (UrlForDownload, entry.getFilename());

222 행 - 새로운 GoogleBlack(). go();

잘 설명하지 않으면 사과드립니다.

답변

1

"공용 DocsService 서비스;"를 초기화하지 않았습니다. 귀하의 GoogleBlack 클래스의 멤버이므로 "service.getMedia (mc);"를 호출하면 NullPointerException이 발생합니다.

+0

답변 해 주셔서 감사합니다. 나는 그것을 발견하고 쓰려고했으나 감사합니다. – Krasimir