Upload document on google drive in a folder - java

I want to upload my document on google drive but in a folder. can you please suggest how i insert this into the folder. I have uploaded but this is not in folder. Code is -
#RequestMapping(value = "/uploadDDFile", method = RequestMethod.POST)
public ModelAndView uploadDDFile(#RequestParam(value = "ddid", required = true) Integer ddid,
#RequestParam(value = "catageryId", required = true) Integer catageryId,
#RequestParam(value = "document", required = true) GMultipartFile document[], HttpServletRequest request) {
System.out.println("-------------------------");
String name = "";
DdeDriveDocuments ddeDriveDocuments = new DdeDriveDocuments();
if (ServletFileUpload.isMultipartContent(request) && document != null) {
for (GMultipartFile gdocument : document) {
try {
boolean user = true;
List<DdeDriveDocuments> dds = ddeDriveDocumentsService.fatchData(ddid, catageryId);
for (DdeDriveDocuments file : dds) {
System.out.println(file.getDocument_name());
if (file.getDocument_name().equals(gdocument.getOriginalFilename())) {
user = false;
}
}
if (user == true) {
Client client = sessionService.getClient();
System.out.println(gdocument.getOriginalFilename());
ddeDriveDocuments
.setDocument_name((gdocument.getName() != null ? gdocument.getOriginalFilename() : ""));
ddeDriveDocuments.setDocument_uploadby(client.getEmail());
ddeDriveDocuments.setDocument_created(new Date());
ddeDriveDocuments.setCatagery_id(catageryId);
ddeDriveDocuments.setDd_id(ddid);
ddeDriveDocuments.setDd_uuid(GeneralUtil.getUUID());
ddeDriveDocuments.setClientID(client.getClientID());
Lawyer googleAuthToken = lawyerService
.getAuthorisedUserToken(Configurator.getInstance().getDriveAccountEmail());
if (googleAuthToken != null) {
// upload file in drive
if (ServletFileUpload.isMultipartContent(request) && document != null) {
// It's value either we need to get from form.
String description = "Testing";
File file = DriveService.uploadDocumentToDrive(googleAuthToken, gdocument,
ddeDriveDocuments.getDocument_name(), description);
File thumFile = DriveService.getFileById(googleAuthToken, file.getId());
System.out.println("thumFile ====" + thumFile);
System.out.println("thab url" + thumFile.getIconLink());
if (file != null) {
ddeDriveDocuments.setDocument_drive_id(file.getId());
ddeDriveDocuments.setImageurl(thumFile.getIconLink());
ddeDriveDocuments = ddeDriveDocumentsService.create(ddeDriveDocuments);
}
}
} else {
System.out.println("Autorised token not available for configured drive account.");
}
} else {
System.out.println("wroung Input");
System.out.println("wroung Input");
name = name.concat(gdocument.getOriginalFilename() + " , ");
System.out.println("This is ::::::::::::: " + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(name !=""){
sessionService.setUnupload_files_name(name);
}
return new ModelAndView("redirect:/al/client/ddeclientportal/" + ddid + "/" + catageryId);
}
public static File uploadDocumentToDrive(Lawyer googleAuthToken,
GMultipartFile file, String fileName, String description) {
File driveFile = null;
try {
InputStream fileStream = file.getInputStream();
String mimeType = DocumentListEntry.MediaType.fromFileName(
file.getOriginalFilename()).getMimeType();
GoogleCredential googleCrednetial = getGoogleCredential(googleAuthToken);
Drive drive = buildService(googleCrednetial);
String file_name = fileName.contains(FilenameUtils.getExtension(file.getOriginalFilename())) ? fileName : fileName + "." + FilenameUtils.getExtension(file.getOriginalFilename());
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
} catch (Exception e) {
e.printStackTrace();
}
return driveFile;
}
Please help i want insert my document in folder.

By Using
File body1 = new File();
body1.setTitle("cloudbox");
body1.setMimeType("application/vnd.google-apps.folder");
driveFile = drive.files().insert(body1).execute();
File body = new File();
body.setTitle(file_name);
body.setDescription(description);
body.setMimeType(mimeType);
body.setParents(Arrays.asList(new ParentReference().setId(driveFile.getId())));
driveFile = drive.files()
.insert(body, new InputStreamContent(mimeType, fileStream))
.execute();
Now can you please suggest how i can generate subfoler.

Related

createNewFile() not working and image not being stored

I am trying to save the images in my local machine and its information in the database. But no data is being inserted into the database. The file is being created but their is no content (is of 0 bytes).
I am using hibernate and spring mvc REST API. I am receiving data from an angular 7 app. The program is running on live server but not on my local machine.
On the local server I get this error and response
POST
http://localhost:8080/com_bmis_app_war_exploded/api/product/save/19
500 core.js:15724 ERROR TypeError: Cannot read property 'length' of
undefined
at AppService.push../src/app/app.service.ts.AppService.errorObjToMap
(app.service.ts:56)
at SafeSubscriber._error (edit-product.component.ts:240)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:192)...........
This is the response error:
HTTP Status 500 – Internal Server Error
Root
Causejava.lang.UnsupportedOperationException
java.base/sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:193)
java.base/java.nio.file.Files.readAttributes(Files.java:1763)
com.bmis.app.controller.ProductController.saveProduct(ProductController.java:329)
com.bmis.app.controller.ProductController.addProduct(ProductController.java:443)......................
This is my code:
private ResponseEntity saveProduct(Integer id, #Valid #RequestBody Product product, MultipartFile[] images, BindingResult bindingResult, HttpServletRequest request) throws IOException {
HashMap response = new HashMap();
boolean success = false;
List errors = new ArrayList();
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
String message = "";
Map data = new HashMap();
Slugify slg = new Slugify();
String directory = "C:/Users/dellm4700/Documents/images";
Set<ProductImage> productImages = new HashSet<>();
for (MultipartFile multipartFile : images) {
ProductImage productImage = new ProductImage();
productImage.setSize(multipartFile.getSize());
productImage.setExtension(multipartFile.getContentType());
productImage.setActualImageName(new Date().getTime() + multipartFile.getOriginalFilename());
productImage.setStandardImageName(multipartFile.getOriginalFilename());
productImage.setNameAtFilestore(slg.slugify(productImage.getActualImageName()));
productImage.setThumbnailImageName("thumb_"+ new Date().getTime() + multipartFile.getOriginalFilename());
productImage.setProduct(product);
productImages.add(productImage);
File imageFile = new File(directory + "/" + productImage.getActualImageName());
imageFile.setReadable(true, false);
imageFile.createNewFile();
Set<PosixFilePermission> perms = Files.readAttributes(imageFile.toPath(), PosixFileAttributes.class).permissions();
try {
multipartFile.transferTo(imageFile);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(imageFile.toPath(), perms);
} catch (IOException e) {
e.printStackTrace();
}
File thumbFile = new File(directory + "/" + productImage.getThumbnailImageName());
thumbFile.setReadable(true, false);
thumbFile.createNewFile();
Set<PosixFilePermission> thumbperms = Files.readAttributes(thumbFile.toPath(), PosixFileAttributes.class).permissions();
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(thumbFile.toPath(), perms);
try {
Thumbnails.of(directory + "/" + productImage.getActualImageName())
.size(200, 200).keepAspectRatio(false)
.toFile(thumbFile);
} catch (IOException e) {
e.printStackTrace();
}
}
productImages.addAll(product.getProductImages());
product.setProductImages(productImages);
for (CustomAttribute customAttribute : product.getCustomAttributes()) {
customAttribute.setProduct(product);
}
Claims claims = (Claims) request.getAttribute("claims");
User user = userService.findById((Integer) claims.get("id"));
productValidator.validate(product, bindingResult);
if (id != null) {
Product sourceProduct = productService.findById(id);
// sourceProduct.getPrices().clear();
if (!(StringUtility.compare(sourceProduct.getName(), product.getName())) && (productService.findByName(product.getName()) != null)) {
bindingResult.rejectValue("name", null, "Product with same name already exists");
message = "Fill the form properly";
} else if (!(StringUtility.compare(sourceProduct.getBarcode(), product.getBarcode())) && (productService.findByBarCode(product.getBarcode()) != null)) {
message = "Fill the form properly";
bindingResult.rejectValue("barcode", null, "Product with same barcode already exists");
}
// DaoUtility.copyNonNullProperties(product, sourceProduct);
// product = sourceProduct;
} else {
if (productService.findByName(product.getName()) != null) {
message = "Fill the form properly";
bindingResult.rejectValue("name", null, "Product with same name already exists");
} else if (productService.findByBarCode(product.getBarcode()) != null) {
message = "Fill the form properly";
bindingResult.rejectValue("barcode", null, "Product with same barcode already exists");
}
}
try {
if (!bindingResult.hasErrors()) {
for (Price price : product.getPrices()) {
price.setProduct(product);
}
if (id == null) {
productService.save(product);
} else {
productService.update(product);
}
data.put("products", product);
success = true;
message = "Product Successfully added";
httpStatus = HttpStatus.OK;
} else {
for (FieldError error : bindingResult.getFieldErrors()) {
message = "Fill the form properly";
errors.add(new ErrorMessage(error.getField(), error.getDefaultMessage()));
}
}
} catch (Exception e) {
errors.add(new ErrorMessage("error", e.getMessage()));
}
response.put("success", success);
response.put("errors", errors);
response.put("message", message);
response.put("data", data);
return new ResponseEntity(response, httpStatus);
}
The problem actually was with PosixFilePermission class as this class only works with Linux based operating systems.
When used readAttributes() method it gave error as Linux has its own methods to get file attributes and windows has its own.

Unable to upload a file through multipart form data from java as well as postman

I have been trying to upload a file from java as well as postman. But I am unable to upload. The server is giving back the response as 200 Ok. But, the file is not being uploaded.
API Details:
I have an API for uploading file as "FileExplorerController". This API has a method "upload()" to upload the files. Url to access this method is"/fileupload". The API is working fine if I upload a file through HTML UI.
But I am trying to upload using Java. I have tried using Postman as well.
I have passed the multipart form data in several ways. But unable to resolve the issue. The code is as follows.
API - Upload - Function
public Result upload() {
String fileName="";
String folderPath="";
String fileDescription="";
String userName = "";
StopWatch stopWatch = null;
List<FileUploadStatusVo> fileStatus = new ArrayList<>();
try {
stopWatch = LoggerUtil.startTime("FileExplorerController -->
upload() : File Upload");
StringBuilder exceptionBuilder = new StringBuilder();
Http.MultipartFormData body =
play.mvc.Controller.request().body().asMultipartFormData();
Http.Context ctx = Http.Context.current();
userName = ctx.session().get(SessionUtil.USER_NAME);
String password = "";
if(StringUtils.isBlank(userName)) {
Map<String, String[]> formValues = play.mvc.Controller.
request().body().asMultipartFormData().asFormUrlEncoded();
if(formValues != null) {
if(formValues.get("userName") != null &&
formValues.get("userName").length > 0) {
userName = formValues.get("userName")[0];
}
if(formValues.get("password") != null &&
formValues.get("password").length > 0) {
password = formValues.get("password")[0];
}
}
if(StringUtils.isBlank(userName) ||
StringUtils.isBlank(password)) {
return Envelope.ok();
}
UserVo userVo = userService.findUserByEmail(userName);
boolean success = BCrypt.checkpw(password, userVo.password);
if(!success) {
return badRequest("Password doesn't match for the given user
name: "+userName);
}
if(userVo == null) {
return Envelope.ok();
}
}
boolean override = false;
String fileTags="";
boolean isPublicView = false;
boolean isPublicDownload = false;
boolean isPublicDelete = false;
boolean isEmailNotification = false;
boolean isEmailWithS3Link = false;
List<String> viewerGroupNames = new ArrayList<>();
List<String> downloaderGroupNames = new ArrayList<>();
List<String> deleterGroupNames = new ArrayList<>();
List<String> viewerUserNames = new ArrayList<>();
List<String> downloaderUserNames = new ArrayList<>();
List<String> deleterUserNames = new ArrayList<>();
List<String> emailIds = new ArrayList<>();
Map<String, String[]> formValues =
play.mvc.Controller.request().body().
asMultipartFormData().asFormUrlEncoded();
JSONObject obj = new JSONObject(formValues.get("model")[0]);
Set<String> groupNames = new HashSet<>();
Set<String> userNames = new HashSet<>();
if(obj != null) {
if(obj.get("override") != null) {
override = Boolean.valueOf(obj.get("override").toString());
}
if(obj.get("description") != null) {
fileDescription = obj.get("description").toString();
}
if(obj.get("tags") != null) {
fileTags = obj.get("tags").toString();
}
if(obj.get("folderPath") != null){
folderPath = obj.get("folderPath").toString();
} else {
folderPath =
ctx.session().get(SessionUtil.LOCAL_STORAGE_PATH);
}
if(obj.get("isPublicView") != null) {
isPublicView =
Boolean.parseBoolean(obj.get("isPublicView").toString());
}
if(obj.get("isPublicDownload") != null) {
isPublicDownload =
Boolean.parseBoolean(obj.get("isPublicDownload").toString());
}
if(obj.get("isPublicDelete") != null) {
isPublicDelete = Boolean.parseBoolean(
obj.get("isPublicDelete").toString());
}
if(obj.get("emailNotification") != null) {
isEmailNotification =
Boolean.parseBoolean(obj.get("emailNotification").toString());
}
if(obj.get("emailWithFileAttachement") != null) {
isEmailWithS3Link =
Boolean.parseBoolean(obj.get(
"emailWithFileAttachement").toString());
}
if(obj.get("viewerGroupNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerGroupNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("downloaderGroupNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("deleteGroupNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("viewerUserNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerUserNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("downloaderUserNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("deleteUserNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("emailIds") != null) {
if(isEmailWithS3Link) {
String[] emailIdsArr =
(obj.get("emailIds").toString()).split(",");
for(String emailId:emailIdsArr){
if(StringUtils.isNotEmpty(emailId)){
emailIds.add(emailId);
}
}
}
}
}
if(groupNames.size() == 0 && userNames.size() == 0){
isEmailNotification = false;
}
List<Http.MultipartFormData.FilePart> files = body.getFiles();
boolean multiUpload = false;
if(files != null && files.size() > 1) {
multiUpload = true;
}
Logger.info("Total Number of files is to be uploaded:"+ files.size()
+" by user: " + userName);
int uploadCount = 0;
List<String> fileNames = new ArrayList<>();
List<String> fileMasters = new ArrayList<>();
FileMasterVo fileMasterVo = null;
UserVo userVo = userService.findUserByEmail(userName);
for(Http.MultipartFormData.FilePart uploadedFile: files) {
if (uploadedFile == null) {
return badRequest("File upload error for file " +
uploadedFile + " for file path: " + fileName);
}
uploadCount++;
String contentType = uploadedFile.getContentType();
String name = uploadedFile.getFile().getName();
Logger.info("Content Type: " + contentType);
Logger.info("File Name: " + fileName);
Logger.info("Name: " + name);
Logger.info("Files Processed : "+uploadCount+"/"+files.size()+"
for user: "+userName);
try {
String extension =
FileUtil.getExtension(uploadedFile.getFilename()).toLowerCase();
File renamedUploadFile =
FileUtil.moveTemporaryFile(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "_" +
uploadedFile.getFilename(), uploadedFile.getFile());
FileInputStream fis = new
FileInputStream(renamedUploadFile);
String errorMsg = "";
fileName = folderPath + uploadedFile.getFilename();
fileNames.add(uploadedFile.getFilename());
if(multiUpload) {
Logger.info("Attempting to upload file " + folderPath +
"/" + uploadedFile.getFilename());
fileMasterVo = fileService.upload(folderPath,fileName,
fileDescription, new Date(), fis, fis.available(),
extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else if(fileName != null) {
Logger.info("Attempting to upload file " + fileName);
int index = fileName.lastIndexOf("/");
if (index > 1) {
fileMasterVo =
fileService.upload(folderPath,fileName, fileDescription,
new Date(), fis, fis.available(), extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else {
errorMsg = "Root Folder MUST exist to upload any
file";
return badRequest(errorMsg);
}
} else {
errorMsg = "File Name is incorrect";
return badRequest(errorMsg);
}
createFileActivityLog(
fileMasterVo,userVo,ViewConstants.UPLOADED);
if (fileMasterVo != null && fileMasterVo.getId() != null) {
fileMasters.add(fileMasterVo.getId().toString());
}
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
exceptionBuilder.append("Exception occured in uploading
file: ");
exceptionBuilder.append(name);
exceptionBuilder.append(" are as follows ");
exceptionBuilder.append(ExceptionUtils.getStackTrace(inEx));
}
fileStatus.add(new
FileUploadStatusVo(uploadedFile.getFilename(),
fileMasterVo.getStatus()));
}
if(isEmailNotification){
fileService.sendNotificationForFile(folderPath,fileNames,
userName, groupNames,
userNames, ViewConstants.UPLOADED);
}
if (isEmailWithS3Link) {
//fileService.sendFileS3Link(folderPath, emailIds, fileMasters);
// Replacing sending S3 link with sending cdi specific link
fileService.sendFilesLink(emailIds, fileMasters);
}
String exceptions = exceptionBuilder.toString();
LoggerUtil.endTime(stopWatch);
if(!StringUtils.isBlank(exceptions)) {
Logger.error("Exception occured while uploading file: " +
fileName + " are as follows " + exceptions);
}
return Envelope.ok(fileStatus);
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
return badRequest("There is a system error please contact
support/administrator" );
} }
Client
**Client - Program**
multipart.addFormField("fileName",file.getAbsolutePath());
multipart.addFormField("folderPath","D/");
multipart.addFormField("fileDescription","Desc");
multipart.addFormField("userName","superadmin");
multipart.addFormField("password","admin");
multipart.addFormField("override","false");
multipart.addFormField("fileTags","tag");
multipart.addFormField("isPublicView","true");
multipart.addFormField("isPublicDownload","true");
multipart.addFormField("isPublicDelete","false");
multipart.addFormField("isEmailNotification","false");
multipart.addFormField("isEmailWithS3Link","true");*/
multipart.addFormField("file", input);
System.out.print("SERVER REPLIED: ");
for (String line : response)
{
System.out.print(line);
}
// synchronize(clientFolder, uploadFolder, true);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I am able to upload using the following code snippet.
Here "model" is a json object which contain all parameters.
DefaultHttpClient client = new DefaultHttpClient();
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", userName)
.addTextBody("password", passWord)
.addBinaryBody("upload_file", new File(sourceFolder + "/" + fileName), ContentType.create("application/octet-stream"), fileName)
.addTextBody("model", object.toString())
.build();
HttpPost post = new HttpPost(uploadURL);
post.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
logger.info("File " + file.getName() + " Successfully Uploaded At: " + destination);
} else {
logger.info("File Upload Unsuccessful");
}
logger.info("Response from server:" + response.getStatusLine());
} catch (ClientProtocolException e) {
logger.error("Client Protocol Exception");
logger.error(e.getMessage());

Google API v3 checking exist folder by passing folder name

I'm using google API v3 for check exist folder. If folder does not exist, then create the new folder. This is my code for creating folder
private void createFolderInDrive() throws IOException {
boolean existed = checkExistedFolder("MyFolder");
if (existed = false) {
File fileMetadata = new File();
fileMetadata.setName("MyFolder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(), "Folder Created with ID:" + file.getId());
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Folder is existed already", Toast.LENGTH_SHORT).show();
}
}
and here is the code for checking exist file
private boolean checkExistedFolder(String folderName) {
//File file = null;
boolean existedFolder = true;
// check if the folder exists already
try {
//String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and title='" + "Evacuation Kit" + "'";
String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='Evacuation Kit'";
// add parent param to the query if needed
//if (parentId != null) {
//query = query + " and '" + parentId + "' in parents";
// }
Drive.Files.List request = mService.files().list().setQ(query);
FileList fileList = request.execute();
if (fileList.getFiles().size() == 0 ) {
// file = fileList.getFiles().get(0);
existedFolder = false;
}
} catch (IOException e) {
e.printStackTrace();
}
return existedFolder;
fileList.getFiles().size() keep returning 3, even there is no folder on g drive. Can you guys tell me where am I doing wrong?
In the code you show, checkExistedFolder is always looking for the name "Evacuation Kit" and not using the argument folderName. Maybe this is the main reason you're always getting 3 from fileList.getFiles().size().
Also there's an assignment in if (existed = false), you should use if ( false == existed ) -using the static value in the left side of the comparison helps avoiding such mistakes-, or if (!existed). Note that it's important to check the nextPageToken when calling Files:list to check if there is more pages to look for the file. See more here https://developers.google.com/drive/api/v3/reference/files/list and Create folder if it does not exist in the Google Drive
This code will check if folder exist on drive. if exists, it will return id else create folder and returns id.
private DriveFile file;
GoogleApiClient mGoogleApiClient;
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.e(TAG, "connected");
new Thread(new Runnable() {
#Override
public void run() {
DriveId Id = getFolder(Drive.DriveApi.getRootFolder(mGoogleApiClient).getDriveId(), "FOLDER_NAME");
Log.e(TAG, "run: " + Id);
}
}).start();
}
DriveId getFolder(DriveId parentId, String titl) {
DriveId dId = null;
if (parentId != null && titl != null) try {
ArrayList<Filter> fltrs = new ArrayList<>();
fltrs.add(Filters.in(SearchableField.PARENTS, parentId));
fltrs.add(Filters.eq(SearchableField.TITLE, titl));
fltrs.add(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE));
Query qry = new Query.Builder().addFilter(Filters.and(fltrs)).build();
MetadataBuffer mdb = null;
DriveApi.MetadataBufferResult rslt = Drive.DriveApi.query(mGoogleApiClient, qry).await();
if (rslt.getStatus().isSuccess()) try {
mdb = rslt.getMetadataBuffer();
if (mdb.getCount() > 0)
dId = mdb.get(0).getDriveId();
} catch (Exception ignore) {
} finally {
if (mdb != null) mdb.close();
}
if (dId == null) {
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(DriveFolder.MIME_TYPE).build();
DriveFolder.DriveFolderResult r1 = parentId.asDriveFolder().createFolder(mGoogleApiClient, meta).await();
DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
if (dFld != null) {
DriveResource.MetadataResult r2 = dFld.getMetadata(mGoogleApiClient).await();
if ((r2 != null) && r2.getStatus().isSuccess()) {
dId = r2.getMetadata().getDriveId();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dId;
}
The code working for me with updated API on Kotlin:
override fun createFolder(name: String): Task<GoogleDriveFileHolder> {
check(googleDriveService != null) { "You have to init Google Drive Service first!" }
check(search(name, FOLDER_MIME_TYPE).not()){"folder already exist"}
return Tasks.call<GoogleDriveFileHolder>(
mExecutor,
Callable<GoogleDriveFileHolder> {
val metadata = File()
.setMimeType(FOLDER_MIME_TYPE)
.setName(name)
GoogleDriveFileHolder(
googleDriveService!!.files()
.create(metadata)
.setFields("id")
.execute() ?: throw IOException("Null result when requesting file creation.")
)
})
}
private fun search(name: String, mimeType:String): Boolean {
var pageToken: String? = null
do {
val result: FileList =
googleDriveService!!
.files()
.list()
.setQ("mimeType='$FOLDER_MIME_TYPE'")
.setSpaces("drive")
.setFields("nextPageToken, files(id, name)")
.setPageToken(pageToken)
.execute()
for (file in result.files) {
Log.d(TAG_UPLOAD_FILE , "Found file: %s (%s)\n ${file.name}, ${file.id} ")
if (name == file.name) return true
}
pageToken = result.nextPageToken
} while (pageToken != null)
return false
}
private const val FOLDER_MIME_TYPE= "application/vnd.google-apps.folder"

video streaming is very slow in java spring MVC

#RequestMapping(value = "/video/{clientID}/{fileName}", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getClientVideo(#PathVariable(value = "clientID") Integer clientID, #PathVariable(value = "fileName") final String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String absolutePath = new File(".").getAbsolutePath();
File file = new File(Paths.get(absolutePath).getParent() + "/" + clientID);
if (null != file) {
FilenameFilter beginswithm = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.contains("ClientVideo_"+fileName);
}
};
File[] files = file.listFiles(beginswithm);
if (null != files && files.length > 0) {
Resource resource = null;
for (final File f : files) {
headers.set("Content-Disposition", "inline; filename=" + f.getName());
StreamingResponseBody responseBody = new StreamingResponseBody() {
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(Files.readAllBytes(f.toPath()));
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody); //(responseBody, headers, HttpStatus.OK);
}
}
}
RecruiterResponseBean resBean = new RecruiterResponseBean();
resBean.setStatusMessage("Video is not present : " + Constants.FAILED);
resBean.setStatusCode(Constants.FAILED_CODE);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
video streaming is working but it is very slow. how to increase the efficiency?
There is no problem with internet it is 10mbps. i am using tomcat 7 and Spring MVC[4.2.4]. should I change the tomcat capacity or how it can be solve? i am not getting in google.

Export/Download presentations and SpreadSheet impersonate other domain users with using administrative access

I need to export/download all files of the other domain users. I used the client login with administer account to see the all files of domain users. however,only document can be export/download,others are fail.
so what is the download url format of the others(For File,pdf,presentation and spreadsheet)??
my document download url is
https://docs.google.com/feeds/download/documents/Export?xoauth_requestor=admin#domain.com&docId=<id>&exportFormat=doc
my program is as following:
public class AuthExample {
private static DocsService docService = new DocsService("Auth Example");
public static void main(String[] args)
throws Exception
{
String adminUser = admin;
String adminPassword = adminpasswd;
String impersonatedUser = "user#domain.com";
docService.setUserCredentials(adminUser, adminPassword);
URL url = new URL( "https://docs.google.com/feeds/" + impersonatedUser + "/private/full");
DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);
for (DocumentListEntry entry : feed.getEntries()) {
String title = entry.getTitle().getPlainText();
System.out.println( title );
String type = entry.getType();
if ( type.equals("document") )
{
String encodedAdminUser = URLEncoder.encode(adminUser);
String resourceId = entry.getResourceId();
String resourceIdNoPrefix = resourceId.substring( resourceId.indexOf(':')+1 );
String downloadUrl =
"https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedAdminUser +
"&docId=" + resourceIdNoPrefix +
"&exportFormat=doc";
downloadFile( downloadUrl, title + ".doc" );
}
}
}
// Method pasted directly from Google documentation
public static void downloadFile(String exportUrl, String filepath)
throws IOException, MalformedURLException, ServiceException
{
System.out.println("Exporting document from: " + exportUrl);
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
MediaSource ms = docService.getMedia(mc);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(filepath);
int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
}
Don't build the download link manually, instead use the entry's content link as explained in the docs:
https://developers.google.com/google-apps/documents-list/#downloading_documents_and_files

Categories