Skip to content

Instantly share code, notes, and snippets.

@anadimisra
Created February 26, 2015 16:03
Show Gist options
  • Save anadimisra/cbee30f04bdebc6853ae to your computer and use it in GitHub Desktop.
Save anadimisra/cbee30f04bdebc6853ae to your computer and use it in GitHub Desktop.
drive uploader java code
@Service
public class GoogleDriveResumeUploader implements ResumeUploader {
/** Global Drive API client. */
private Drive drive;
@Resource
private Environment environment;
private static final Logger LOGGER = LoggerFactory.getLogger(GoogleDriveResumeUploader.class);
@Autowired
public void setDrive(Drive drive) {
this.drive = drive;
}
@Async
public void uploadResume(UploadData data, byte[] uploadFile) throws GeneralSecurityException, IOException {
LOGGER.info("Uploading file type {} of size {} to Drive",data.getContentType(),uploadFile.length);
File file = new File();
List<ParentReference> referneces = new ArrayList<ParentReference>();
referneces.add(buildParentReference(data.getApplication().getRole()));
file.setTitle(data.getFileName());
file.setParents(referneces);
file.setCopyable(true);
file.setEditable(true);
file.setWritersCanShare(true);
file.setTitle(data.getFileName());
ByteArrayInputStream inputBytes = new ByteArrayInputStream(uploadFile);
InputStreamContent fileUpload = new InputStreamContent(data.getContentType(), new BufferedInputStream(inputBytes));
fileUpload.setLength(uploadFile.length);
Drive.Files.Insert request = drive.files().insert(file, fileUpload);
request.getMediaHttpUploader().setProgressListener(getProgressListener());
request.execute();
}
private ParentReference buildParentReference(String role) {
ParentReference reference = new ParentReference();
reference.setId(environment.getProperty(role + ".id"));
reference.setKind("drive#parentReference");
reference.setIsRoot(false);
return reference;
}
private MediaHttpUploaderProgressListener getProgressListener() {
return new MediaHttpUploaderProgressListener() {
@Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation has started!");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation is complete!");
break;
case MEDIA_IN_PROGRESS:
System.out.println(uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload is complete!");
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment