3

How to resolve the error given below?

java.lang.NullPointerException: Cannot invoke "com.app.gdrivetest.service.FileManager.listEverything()" because "this.fileManager" is null
at com.app.gdrivetest.controller.MainController.listEverything(MainController.java:34) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:an]

GoogleDriveManager.java

In the following, we have created a GoogleDriveManager class, which has one method called getInstance() which returns the instance of Drive. We will use this class in all functions in the FileManager.java class to get the drive connection.

@Service

public class GoogleDriveManager {

    private static final String APPLICATION_NAME = "Technicalsand.com - Google Drive API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
  
        public Drive getInstance() throws GeneralSecurityException, IOException {
         // Build a new authorized API client service.
            final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
               .setApplicationName(APPLICATION_NAME)
               .build();
         return service;
      }
      /**
       * Creates an authorized Credential object.
       *
       * @param HTTP_TRANSPORT The network HTTP Transport.
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
        
       
      private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
         // Load client secrets.
         InputStream in = GoogleDriveManager.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
         if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
         }
         GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
         // Build flow and trigger user authorization request.
         GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
               HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
               .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
               .setAccessType("offline")
               .build();
         LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8080).build();
         return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
      }
    }

MainController.Java

@RestController
public class MainController {

@Autowired
private FileManager fileManager;
  
  @GetMapping({"/"})
  public ResponseEntity<List<File>> listEverything() throws IOException, GeneralSecurityException {
    List<File> files = fileManager.listEverything();
    return ResponseEntity.ok(files);
}

@GetMapping({"/list/{parentId}"})
public ResponseEntity<List<File>> list(@PathVariable(required = false) String parentId) throws IOException, GeneralSecurityException {
    List<File> files = fileManager.listFolderContent(parentId);
    return ResponseEntity.ok(files);
}

@GetMapping("/download/{id}")
public void download(@PathVariable String id, HttpServletResponse response) throws IOException, GeneralSecurityException {
    fileManager.downloadFile(id, response.getOutputStream());
}

@GetMapping("/directory/create")
public ResponseEntity<String> createDirecory(@RequestParam String path) throws Exception {
    String parentId = fileManager.getFolderId(path);
    return ResponseEntity.ok("parentId: "+parentId);
}

@PostMapping(value = "/upload",
        consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE} )
public ResponseEntity<String> uploadSingleFileExample4(@RequestBody MultipartFile file) {
    String fileId = fileManager.uploadFile(file);
    if(fileId == null){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    return ResponseEntity.ok("Success, FileId: "+ fileId);
}
@GetMapping("/delete/{id}")
public void delete(@PathVariable String id) throws Exception {
    fileManager.deleteFile(id);
}
}

FileManager.Java

The following class has functions to list files, download, delete from the drive and upload files to the drive.

@Service
public class FileManager {

@Autowired
private GoogleDriveManager googleDriveManager;

public List<File> listEverything() throws IOException, GeneralSecurityException {
      // Print the names and IDs for up to 10 files.
      FileList result = googleDriveManager.getInstance().files().list()
            .setPageSize(10)
            .setFields("nextPageToken, files(id, name)")
            .execute();
      return result.getFiles();
    }

 

public List<File> listFolderContent(String parentId) throws IOException, GeneralSecurityException {
    if (parentId == null) {
        parentId = "root";
    }
    String query = "'" + parentId + "' in parents";
    FileList result = googleDriveManager.getInstance().files().list()
            .setQ(query)
            .setPageSize(10)
            .setFields("nextPageToken, files(id, name)")
            .execute();
     List<File> files = result.getFiles();
     if (files == null || files.isEmpty()) {
            System.out.println("No files found.");
        } else {
            System.out.println("Files:");
            for (File file : files) {
                System.out.printf("%s (%s)\n", file.getName(), file.getId());
            }
        }
    return result.getFiles();
    
}

public void downloadFile(String id, OutputStream outputStream) throws IOException, GeneralSecurityException {
    if (id != null) {
        String fileId = id;
        googleDriveManager.getInstance().files().get(fileId).executeMediaAndDownloadTo(outputStream);
    }
}

public void deleteFile(String fileId) throws Exception {
    googleDriveManager.getInstance().files().delete(fileId).execute();
}

public String uploadFile(MultipartFile file, String filePath) {
    try {
        //String folderId = getFolderId(filePath);
        if (file != null) {
            File fileMetadata = new File();
            //fileMetadata.setParents(Collections.singletonList(folderId));
            fileMetadata.setName(file.getOriginalFilename());
            File uploadFile = googleDriveManager.getInstance()
                    .files()
                    .create(fileMetadata, new InputStreamContent(
                            file.getContentType(),
                            new ByteArrayInputStream(file.getBytes()))
                    )
                    .setFields("id").execute();
            return uploadFile.getId();
        }
    } catch (Exception e) {
        System.out.print("Error: "+e);
    }
    return null;
}

public String getFolderId(String path) throws Exception {
    String parentId = null;
    String[] folderNames = path.split("/");

    Drive driveInstance = googleDriveManager.getInstance();
    for (String name : folderNames) {
        parentId = findOrCreateFolder(parentId, name, driveInstance);
    }
    return parentId;
}

private String findOrCreateFolder(String parentId, String folderName, Drive driveInstance) throws Exception {
    String folderId = searchFolderId(parentId, folderName, driveInstance);
    // Folder already exists, so return id
    if (folderId != null) {
        return folderId;
    }
    //Folder dont exists, create it and return folderId
    File fileMetadata = new File();
    fileMetadata.setMimeType("application/vnd.google-apps.folder");
    fileMetadata.setName(folderName);

    if (parentId != null) {
        fileMetadata.setParents(Collections.singletonList(parentId));
    }
    return driveInstance.files().create(fileMetadata)
            .setFields("id")
            .execute()
            .getId();
}

private String searchFolderId(String parentId, String folderName, Drive service) throws Exception {
    String folderId = null;
    String pageToken = null;
    FileList result = null;

    File fileMetadata = new File();
    fileMetadata.setMimeType("application/vnd.google-apps.folder");
    fileMetadata.setName(folderName);

    do {
        String query = " mimeType = 'application/vnd.google-apps.folder' ";
        if (parentId == null) {
            query = query + " and 'root' in parents";
        } else {
            query = query + " and '" + parentId + "' in parents";
        }
        result = service.files().list().setQ(query)
                .setSpaces("drive")
                 
                .setFields("nextPageToken, files(id, name)")
                .setPageToken(pageToken)
                .execute();

        for (File file : result.getFiles()) {
            if (file.getName().equalsIgnoreCase(folderName)) {
                folderId = file.getId();
            }
        }
        pageToken = result.getNextPageToken();
    } while (pageToken != null && folderId == null);

    return folderId;
}

}

Project Structure

Linet M Shaji
  • 69
  • 1
  • 7

0 Answers0