Google API v3 checking exist folder by passing folder name - java

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"

Related

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());

Realm findfirst() is returning null

realm newbie here and facing a problem in my project. So what I want to achieve is that, in my app when I click a photo I am saving a realm object inside my database as well as caching the image locally to be used later. Here is the code for both:
#Override
public void onPhotoSelected(PXImage photo) {
PXComposition composition = null;
PXPhoto photoParent = null;
for (PXComposition pxComposition : mSession.getCompositions()) {
if (pxComposition.getItems() == null || pxComposition.getItems().size() < 1)
continue;
for (PXPhoto item : pxComposition.getItems()) {
if (item.getImage().getOriginalPath().equals(photo.getOriginalPath())) {
composition = pxComposition;
photoParent = item;
break;
}
}
}
if (composition == null && photo.isSelected()) {
mRealm.beginTransaction();
String uuid = mSession.addPhoto(photo).getUuid();
mRealm.commitTransaction(); // IMPORTANT to commit transaction. ContentDownloadTask requires PXImage to be written in Realm.
ThreadUtils.getDefaultExecutorService().submit(new ContentDownloadTask(this, photo.getOriginalPath(), uuid));
} else if (composition != null && !photo.isSelected()) {
mRealm.beginTransaction();
if (photoParent.getImage().isDownloaded()) // FIXME What if not copied yet ???
FileUtils.deleteFile(photoParent.getImage().getApplicationPath());
mSession.removePhoto(photoParent);
mRealm.commitTransaction();
}
onCheckChanged(photo);
App.log().v("SESSION", mSession.toString());
}
This is where click events on the photo are handled. After the selection click I am calling ThreadUtils.getDefaultExecutorService().submit(new ContentDownloadTask(this, photo.getOriginalPath(), uuid)); to cache the image locally. Here is the code for the ContentDownloadTask:
public class ContentDownloadTask implements Callable<Void> {
private String id;
private String path;
private Context context;
private Realm mRealm;
public static final String TAG = "ContentDownloadTask";
private static final String DIR_EXTERNAL_NAME = "Local";
private static final String FILE_EXTENSION = ".jpg";
public ContentDownloadTask(Context context, String path, String id) {
this.path = path;
this.id = id;
this.context = context;
}
#Override
public Void call() throws Exception {
try {
Log.d(TAG, "Copying From " + path);
//create output directory if it doesn't exist
final File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file == null) {
throw new IllegalStateException("Failed to get external storage files directory");
} else if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() +
" already exists and is not a directory");
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " +
file.getAbsolutePath());
}
}
File to = new File(file, DIR_EXTERNAL_NAME);
if (to.exists()) {
if (!to.isDirectory()) {
throw new IllegalStateException(file.getAbsolutePath() +
" already exists and is not a directory");
}
} else if (!to.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " +
file.getAbsolutePath());
}
to = new File(to, fileName(this.id));
if (!to.exists())
to.createNewFile();
InputStream in = null;
if (PackageUtils.isContentUri(path)) {
Uri uri = PackageUtils.toUri(path);
in = context.getContentResolver().openInputStream(uri);
} else {
File from = new File(this.path);
in = new FileInputStream(from);
}
OutputStream out = new FileOutputStream(to);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
mRealm = Realm.getDefaultInstance();
PXImage image = mRealm.where(PXImage.class).equalTo("uuid", this.id).findFirst();
if (image == null) {
to.delete();
throw new Exception("Photo Not Found ID: " + this.id);
}
mRealm.beginTransaction();
image.setApplicationPath(to.getPath());
mRealm.commitTransaction();
mRealm.close();
Log.d(TAG, "Complete Copied From " + path + " To " + to.getAbsolutePath());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return null;
}
Now the null is returned at this statement: PXImage image = mRealm.where(PXImage.class).equalTo("uuid", this.id).findFirst();. Basically here I need to save the application path of the image that I cached locally inside the realm object. But it's returning null. Also this not happening every time I click the photos. This only happens sometimes and the error is not reproducible. Any kind of help will be appreciated. I have already checked the following duplicate questions:
first
second
third
fourth
public PXPhoto addPhoto(PXImage image) {
PXComposition composition = null;
PXPhoto photo = null;
boolean isLandscape = false;
int photosPerItem = getProduct().getSelectedPhotosPerItem();
switch (getProduct().getRootShortCode()) {
case Product.CategoryType.SQUARES:
case Product.CategoryType.CLASSIC:
case Product.CategoryType.WALLOGRAPHS:
case Product.CategoryType.SIGNATURES:
case Product.CategoryType.MOSAIC:
setLayoutType(image.isLandscape() ? C.LayoutType.LANDSCAPE.ordinal() : C.LayoutType.PORTRAIT.ordinal());
composition = PXComposition.initializeNewComposition(this);
photo = PXPhoto.initializePhoto(image);
break;
case Product.CategoryType.PANORAMA:
composition = PXComposition.initializeNewComposition(this);
photo = PXPhoto.initializePhoto(image);
break;
case Product.CategoryType.STRIPS:
case Product.CategoryType.POSTERS:
if (getCompositions() == null || getCompositions().size() == 0
|| (getProduct().getRootShortCode().equals(Product.CategoryType.STRIPS) &&
getCompositions().last().getItems().size() % photosPerItem == 0))
composition = PXComposition.initializeNewComposition(this);
else
composition = getCompositions().last();
photo = PXPhoto.initializePhoto(image);
break;
}
composition.addItem(photo);
composition.updateComposition();
if (!composition.isManaged()) {
Realm realm = Realm.getDefaultInstance();
composition = realm.copyToRealmOrUpdate(composition);
realm.close();
photo.setComposition(composition);
addComposition(composition);
} else
photo.setComposition(composition);
return photo;
}
EDIT:
uuid generation:
public PXPhoto() {
this.uuid = UUID.randomUUID().toString();
this.autoEnhance = false;
this.zoom = 1;
}

Upload document on google drive in a folder

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.

Upload file to existing Google Drive Folder - Android

I want to upload a file to an existing Google Drive folder.
I am using this how to upload an image from my android app to a specific folder on google drive to get the folder name but not sure how to implement it (smokybob's answer)
//Search by name and type folder
String qStr = "mimeType = 'application/vnd.google-apps.folder' and title = 'myFolder'";
//Get the list of Folders
FileList fList=service.files().list().setQ(qStr).execute();
//Check that the result is one folder
File folder;
if (fList.getItems().lenght==0){
folder=fList.getItems()[0];
}
//Create the insert request is as in the sample
File file = service.files().insert(body, mediaContent);
//set the parent
file.setParents(Arrays.asList(newParentReference().setId(folder.getFolderId())));
//execute the request
file.execute();
I am getting cannot resolve symbol errors for FileList, body, mediacontent.
I am getting cannot resolve method for .files, getitems(), setparents, newparentsreference, and execute.
Class:GetFile.java https://github.com/googledrive/android-demos/blob/master/src/com/google/android/gms/drive/sample/demo/CreateFileActivity.java
public class GetFile extends UploadDrive {
private static final String TAG = "CreateFileActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient())
.setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write(MainActivity.driveText); //what is the problem?
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("text/plain")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
}
};
}
When a folder is created under GDAA, it produces a DriveId.
/**************************************************************************
* create file/folder in GOODrive
* #param prnId parent's ID, (null or "root") for root
* #param titl file name
* #param mime file mime type
* #param file file (with content) to create (optional, if null, create folder)
* #return file id / null on fail
*/
static String create(String prnId, String titl, String mime, java.io.File file) {
DriveId dId = null;
if (mGAC != null && mGAC.isConnected() && titl != null) try {
DriveFolder pFldr = (prnId == null || prnId.equalsIgnoreCase("root")) ?
Drive.DriveApi.getRootFolder(mGAC):
Drive.DriveApi.getFolder(mGAC, DriveId.decodeFromString(prnId));
if (pFldr == null) return null; //----------------->>>
MetadataChangeSet meta;
if (file != null) { // create file
if (mime != null) { // file must have mime
DriveContentsResult r1 = Drive.DriveApi.newDriveContents(mGAC).await();
if (r1 == null || !r1.getStatus().isSuccess()) return null; //-------->>>
meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(mime).build();
DriveFileResult r2 = pFldr.createFile(mGAC, meta, r1.getDriveContents()).await();
DriveFile dFil = r2 != null && r2.getStatus().isSuccess() ? r2.getDriveFile() : null;
if (dFil == null) return null; //---------->>>
r1 = dFil.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
if ((r1 != null) && (r1.getStatus().isSuccess())) try {
Status stts = file2Cont(r1.getDriveContents(), file).commit(mGAC, meta).await();
if ((stts != null) && stts.isSuccess()) {
MetadataResult r3 = dFil.getMetadata(mGAC).await();
if (r3 != null && r3.getStatus().isSuccess()) {
dId = r3.getMetadata().getDriveId();
}
}
} catch (Exception e) {
UT.le(e);
}
}
} else {
meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(UT.MIME_FLDR).build();
DriveFolderResult r1 = pFldr.createFolder(mGAC, meta).await();
DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
if (dFld != null) {
MetadataResult r2 = dFld.getMetadata(mGAC).await();
if ((r2 != null) && r2.getStatus().isSuccess()) {
dId = r2.getMetadata().getDriveId();
}
}
}
} catch (Exception e) { UT.le(e); }
return dId == null ? null : dId.encodeToString();
}
(must be run on non-UI thread)
This ID is used in subsequent calls as a "parent ID". If you have questions about unresolved methods, please refer to this GitHub project. BTW (as I mentioned before), it does everything you're trying to accomplish (creates folders, creates text files, reads contents back, deletes files/folders, ...)
Good Luck

android-market retrieve empty results

I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.
session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});

Categories