Search in sources :

Example 11 with File

use of com.google.api.services.drive.model.File in project OpenRefine by OpenRefine.

the class UploadCommand method uploadSpreadsheet.

private static String uploadSpreadsheet(final Project project, final Engine engine, final Properties params, String token, String name, List<Exception> exceptions) {
    Drive driveService = GDataExtension.getDriveService(token);
    final SpreadsheetService spreadsheetService = GDataExtension.getSpreadsheetService(token);
    try {
        File body = new File();
        body.setTitle(name);
        body.setDescription("Spreadsheet uploaded from OpenRefine project: " + name);
        body.setMimeType("application/vnd.google-apps.spreadsheet");
        File file = driveService.files().insert(body).execute();
        String fileID = file.getId();
        // Iterate through all spreadsheets to find one with our ID
        SpreadsheetEntry spreadsheetEntry2 = null;
        SpreadsheetFeed feed = spreadsheetService.getFeed(new URL(SPREADSHEET_FEED), SpreadsheetFeed.class);
        List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries();
        for (com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet : spreadsheets) {
            if (spreadsheet.getId().endsWith(fileID)) {
                spreadsheetEntry2 = spreadsheet;
            }
        }
        // Bail if we didn't find our spreadsheet (shouldn't happen)
        if (spreadsheetEntry2 == null) {
            logger.error("Failed to find match for ID: " + fileID);
            return null;
        }
        int[] size = CustomizableTabularExporterUtilities.countColumnsRows(project, engine, params);
        URL worksheetFeedUrl = spreadsheetEntry2.getWorksheetFeedUrl();
        WorksheetEntry worksheetEntry = new WorksheetEntry(size[1], size[0]);
        worksheetEntry.setTitle(new PlainTextConstruct("Uploaded Data"));
        final WorksheetEntry worksheetEntry2 = spreadsheetService.insert(worksheetFeedUrl, worksheetEntry);
        spreadsheetEntry2.getDefaultWorksheet().delete();
        final SpreadsheetEntry spreadsheetEntry3 = spreadsheetEntry2;
        new Thread() {

            @Override
            public void run() {
                spreadsheetService.setProtocolVersion(SpreadsheetService.Versions.V3);
                try {
                    uploadToCellFeed(project, engine, params, spreadsheetService, spreadsheetEntry3, worksheetEntry2);
                } catch (Exception e) {
                    logger.error("Error uploading data to Google Spreadsheets", e);
                }
            }
        }.start();
        return spreadsheetEntry2.getSpreadsheetLink().getHref();
    } catch (IOException | ServiceException e) {
        exceptions.add(e);
    }
    return null;
}
Also used : SpreadsheetService(com.google.gdata.client.spreadsheet.SpreadsheetService) SpreadsheetEntry(com.google.gdata.data.spreadsheet.SpreadsheetEntry) IOException(java.io.IOException) URL(java.net.URL) WorksheetEntry(com.google.gdata.data.spreadsheet.WorksheetEntry) PlainTextConstruct(com.google.gdata.data.PlainTextConstruct) ServletException(javax.servlet.ServletException) ServiceException(com.google.gdata.util.ServiceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SpreadsheetEntry(com.google.gdata.data.spreadsheet.SpreadsheetEntry) ServiceException(com.google.gdata.util.ServiceException) SpreadsheetFeed(com.google.gdata.data.spreadsheet.SpreadsheetFeed) Drive(com.google.api.services.drive.Drive) File(com.google.api.services.drive.model.File)

Example 12 with File

use of com.google.api.services.drive.model.File in project Aegis by Decad3nce.

the class BackupGoogleAccountsActivity method saveFileToDrive.

private void saveFileToDrive() {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                if (!isAegisFolderAvailable()) {
                    createAegisFolder();
                }
                FileContent mediaContent = null;
                File body = new File();
                File file = null;
                if (callLogs) {
                    Log.i(TAG, "Generating new file to upload: " + callLogFileUri);
                    java.io.File callFileContent = new java.io.File(callLogFileUri.getPath());
                    mediaContent = new FileContent("text/plain", callFileContent);
                    body.setTitle(callFileContent.getName());
                    body.setParents(Arrays.asList(new ParentReference().setId(getAegisFolder())));
                    body.setMimeType("text/plain");
                    file = service.files().insert(body, mediaContent).execute();
                    if (file != null) {
                        Log.i(TAG, "File uploaded successfully: " + file.getTitle());
                        Utils.sendSMS(context, address, context.getResources().getString(R.string.util_sendsms_data_recovery_pass) + " " + file.getTitle() + " to Google Drive");
                        deleteFile(file.getTitle());
                        finish();
                    }
                }
                if (smsLogs) {
                    Log.i(TAG, "Generating new file to upload: " + smsLogFileUri);
                    java.io.File smsFileContent = new java.io.File(smsLogFileUri.getPath());
                    mediaContent = new FileContent("text/plain", smsFileContent);
                    body.setTitle(smsFileContent.getName());
                    body.setParents(Arrays.asList(new ParentReference().setId(getAegisFolder())));
                    body.setMimeType("text/plain");
                    file = service.files().insert(body, mediaContent).execute();
                    if (file != null) {
                        Log.i(TAG, "File uploaded successfully: " + file.getTitle());
                        Utils.sendSMS(context, address, context.getResources().getString(R.string.util_sendsms_data_recovery_pass) + " " + file.getTitle() + " to Google Drive");
                        deleteFile(file.getTitle());
                        finish();
                    }
                }
            } catch (UserRecoverableAuthIOException e) {
                Log.i(TAG, "Exception: " + e.toString());
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
            } catch (IOException e) {
                Log.i(TAG, "Exception: " + e.toString());
                e.printStackTrace();
                Utils.sendSMS(context, address, context.getResources().getString(R.string.util_sendsms_data_recovery_fail));
            }
        }
    });
    t.start();
}
Also used : FileContent(com.google.api.client.http.FileContent) ParentReference(com.google.api.services.drive.model.ParentReference) UserRecoverableAuthIOException(com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException) UserRecoverableAuthIOException(com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException) IOException(java.io.IOException) File(com.google.api.services.drive.model.File)

Example 13 with File

use of com.google.api.services.drive.model.File in project local-data-aragopedia by aragonopendata.

the class GoogleDriveAPI method createSpreadsheetFromFile.

/**
	 * Method to create a google spreadsheet from a file
	 * 
	 * @param idParentFolder
	 *            String to identify the parent folder
	 * @param emailUserOwner
	 *            String to identify email user owner
	 * @param extensionFile
	 *            String with extension file
	 * @param nameFile
	 *            String with name google spreadsheet
	 * @param fileOrigin
	 *            File with content file origin
	 * @param mimeType
	 *            String with mime type file origin
	 * 
	 * @return True if create is ok, False otherwise
	 */
public boolean createSpreadsheetFromFile(String idParentFolder, String emailUserOwner, String extensionFile, String nameFile, java.io.File fileOrigin, String mimeType) {
    boolean result = true;
    Permission newPermission = createPermission();
    File body = new File();
    body.setTitle(nameFile);
    body.setMimeType("application/vnd.google-apps.spreadsheet");
    body.setEditable(true);
    body.setShared(true);
    body.setPermissions(Arrays.asList(newPermission));
    body.setUserPermission(newPermission);
    body.setWritersCanShare(true);
    body.setFileExtension(extensionFile);
    User user = new User();
    user.setEmailAddress(emailUserOwner);
    user.setIsAuthenticatedUser(true);
    List<User> list = new ArrayList<User>();
    list.add(user);
    body.setOwners(list);
    body.setParents(Arrays.asList(new ParentReference().setId(idParentFolder)));
    FileContent mediaContent = new FileContent(mimeType, fileOrigin);
    String fileId = "";
    try {
        File file = drive.files().insert(body, mediaContent).execute();
        fileId = file.getId();
        insertPermission(newPermission, fileId);
    } catch (Exception e) {
        log.error("Error create spreadsheet from file ", e);
        result = false;
    }
    log.info("create Spreadsheet in google Drive from " + nameFile);
    return result;
}
Also used : FileContent(com.google.api.client.http.FileContent) ParentReference(com.google.api.services.drive.model.ParentReference) User(com.google.api.services.drive.model.User) Permission(com.google.api.services.drive.model.Permission) ArrayList(java.util.ArrayList) File(com.google.api.services.drive.model.File) GeneralSecurityException(java.security.GeneralSecurityException) ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 14 with File

use of com.google.api.services.drive.model.File in project local-data-aragopedia by aragonopendata.

the class GoogleDriveAPI method listOwnerFilesAfterDate.

/**
	 * Method to list files and folders of id account after date of parameter
	 */
public List<File> listOwnerFilesAfterDate(String stringDateLastChange) {
    SimpleDateFormat formatFullDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date dateLastChange = null;
    try {
        dateLastChange = formatFullDate.parse(stringDateLastChange);
    } catch (ParseException e1) {
        log.error("Error parse date in list", e1);
    }
    FileList result;
    List<File> files = null;
    try {
        result = drive.files().list().setMaxResults(1000).execute();
        files = result.getItems();
    } catch (Exception e) {
        log.error("Error list files", e);
    }
    if (files == null || files.size() == 0) {
        log.error("No files found");
    } else {
        for (File file : files) {
            if (file.getShared()) {
                DateTime dateTime = file.getModifiedDate();
                Date dateModifyFile = new Date(dateTime.getValue());
                if (dateModifyFile.after(dateLastChange))
                    log.info("Title " + file.getTitle() + " id " + file.getId() + " DateTime " + formatFullDate.format(dateModifyFile));
            }
        }
    }
    return files;
}
Also used : FileList(com.google.api.services.drive.model.FileList) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) File(com.google.api.services.drive.model.File) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) ParseException(java.text.ParseException) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime)

Example 15 with File

use of com.google.api.services.drive.model.File in project local-data-aragopedia by aragonopendata.

the class GoogleDriveAPI method downloadAllFiles.

/**
	 * Download all owner files
	 * 
	 * @param path
	 *            Path where download files
	 */
public void downloadAllFiles(String path) throws IOException {
    log.debug("init downloadAllFiles()");
    List<File> files = listOwnerFiles();
    FileUtils.deleteDirectory(new java.io.File(path));
    for (File file : files) {
        download(path, file);
    }
    log.debug("end downloadAllFiles()");
}
Also used : File(com.google.api.services.drive.model.File)

Aggregations

File (com.google.api.services.drive.model.File)41 Test (org.junit.Test)19 IOException (java.io.IOException)17 HashMap (java.util.HashMap)9 FileList (com.google.api.services.drive.model.FileList)7 ParseException (java.text.ParseException)7 ArrayList (java.util.ArrayList)7 FileContent (com.google.api.client.http.FileContent)6 GeneralSecurityException (java.security.GeneralSecurityException)6 GenericUrl (com.google.api.client.http.GenericUrl)4 HttpResponse (com.google.api.client.http.HttpResponse)4 Permission (com.google.api.services.drive.model.Permission)4 User (com.google.api.services.drive.model.User)4 InputStream (java.io.InputStream)4 UserRecoverableAuthIOException (com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException)3 DateTime (com.google.api.client.util.DateTime)3 ParentReference (com.google.api.services.drive.model.ParentReference)3 Comment (com.google.api.services.drive.model.Comment)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2