plugins/tech/google/src/main/java/org/apache/hop/pipeline/transforms/googlesheets/GoogleSheetsOutput.java
@Override
  public boolean init() {
    JsonFactory JSON_FACTORY;
    NetHttpTransport HTTP_TRANSPORT;
    String scope;
    Boolean exists = false;

    if (super.init()) {

      // Check if file exists
      try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        JSON_FACTORY = JacksonFactory.getDefaultInstance();
        scope = "https://www.googleapis.com/auth/drive";
        Drive service =
            new Drive.Builder(
                    HTTP_TRANSPORT,
                    JSON_FACTORY,
                    GoogleSheetsCredentials.getCredentialsJson(
                        scope, resolve(meta.getJsonCredentialPath())))
                .setApplicationName(GoogleSheetsCredentials.APPLICATION_NAME)
                .build();
        String wsID = resolve(meta.getSpreadsheetKey());
        // "properties has { key='id' and value='"+wsID+"'}";
        String q = "mimeType='application/vnd.google-apps.spreadsheet'";
        FileList result =
            service
                .files()
                .list()
                .setSupportsAllDrives(true)
                .setIncludeItemsFromAllDrives(true)
                .setQ(q)
                .setPageSize(100)
                .setFields("nextPageToken, files(id, name)")
                .execute();
        List<File> spreadsheets = result.getFiles();

        for (File spreadsheet : spreadsheets) {
          // log.logBasic(wsID+" VS "+spreadsheet.getId());
          if (wsID.equals(spreadsheet.getId())) {
            exists = true; // file exists
            log.logBasic("Spreadsheet:" + wsID + " exists");
          }
        }
        // If it does not exist & create checkbox is checker create it.
        // log.logBasic("Create if Not exist is :"+meta.getCreate());
        if (!exists && meta.getCreate()) {
          if (!meta.getAppend()) { // si append + create alors erreur
            // Init Service
            scope = "https://www.googleapis.com/auth/spreadsheets";
            data.service =
                new Sheets.Builder(
                        HTTP_TRANSPORT,
                        JSON_FACTORY,
                        GoogleSheetsCredentials.getCredentialsJson(
                            scope, resolve(meta.getJsonCredentialPath())))
                    .setApplicationName(GoogleSheetsCredentials.APPLICATION_NAME)
                    .build();

            // If it does not exist create it.
            Spreadsheet spreadsheet =
                new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle(wsID));
            Sheets.Spreadsheets.Create request = data.service.spreadsheets().create(spreadsheet);
            Spreadsheet response = request.execute();
            String spreadsheetID = response.getSpreadsheetId();
            meta.setSpreadsheetKey(spreadsheetID); //
            // log.logBasic(response);
            // If it does not exist we use the Worksheet ID to rename 'Sheet ID'
            if (resolve(meta.getWorksheetId()) != "Sheet1") {

              SheetProperties title =
                  new SheetProperties().setSheetId(0).setTitle(resolve(meta.getWorksheetId()));
              // make a request with this properties
              UpdateSheetPropertiesRequest rename =
                  new UpdateSheetPropertiesRequest().setProperties(title);
              // set fields you want to update
              rename.setFields("title");
              log.logBasic("Changing worksheet title to:" + resolve(meta.getWorksheetId()));
              List<Request> requests = new ArrayList<>();
              Request request1 = new Request().setUpdateSheetProperties(rename);
              requests.add(request1);
              BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
              requestBody.setRequests(requests);
              // now you can execute batchUpdate with your sheetsService and SHEET_ID
              data.service.spreadsheets().batchUpdate(spreadsheetID, requestBody).execute();
              // now if share email is not null we share with R/W with the email given
              if ((resolve(meta.getShareEmail()) != null
                      && !resolve(meta.getShareEmail()).isEmpty())
                  || (resolve(meta.getShareDomain()) != null
                      && !resolve(meta.getShareDomain()).isEmpty())) {

                String fileId = spreadsheetID;
                JsonBatchCallback<Permission> callback =
                    new JsonBatchCallback<Permission>() {
                      @Override
                      public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                          throws IOException {
                        // Handle error
                        log.logError("Failed sharing file" + e.getMessage());
                      }

                      @Override
                      public void onSuccess(Permission permission, HttpHeaders responseHeaders)
                          throws IOException {
                        log.logBasic("Shared successfully : Permission ID: " + permission.getId());
                      }
                    };
                BatchRequest batch = service.batch();
                if (resolve(meta.getShareEmail()) != null
                    && !resolve(meta.getShareEmail()).isEmpty()) {
                  log.logBasic("Sharing sheet with:" + resolve(meta.getShareEmail()));
                  Permission userPermission =
                      new Permission()
                          .setType("user")
                          .setRole("writer")
                          .setEmailAddress(resolve(meta.getShareEmail()));
                  // Using Google drive service here not spreadsheet data.service
                  service
                      .permissions()
                      .create(fileId, userPermission)
                      .setFields("id")
                      .queue(batch, callback);
                }
                if (resolve(meta.getShareDomain()) != null
                    && !resolve(meta.getShareDomain()).isEmpty()) {
                  log.logBasic("Sharing sheet with domain:" + resolve(meta.getShareDomain()));
                  Permission domainPermission =
                      new Permission()
                          .setType("domain")
                          .setRole("reader")
                          .setDomain(resolve(meta.getShareDomain()));
                  service
                      .permissions()
                      .create(fileId, domainPermission)
                      .setFields("id")
                      .queue(batch, callback);
                }
                batch.execute();
              }
            }
          } else {
            log.logError("Append and Create options cannot be activated altogether");
            return false;
          }
        }

        if (!exists && !meta.getCreate()) {
          log.logError("File does not Exist");
          return false;
        }

      } catch (Exception e) {
        log.logError(
            "Error: for worksheet : "
                + resolve(meta.getWorksheetId())
                + " in spreadsheet :"
                + resolve(meta.getSpreadsheetKey())
                + e.getMessage(),
            e);
        return false;
      }

      return true;
    }
    return false;
  }
/** Initialize and do work where other transforms need to wait for... */
Initialize and do work where other transforms need to wait for
Initialize and do work where other transforms need to wait for
@Override
  public boolean init() {
    JsonFactory JSON_FACTORY;
    NetHttpTransport HTTP_TRANSPORT;
    String scope;
    Boolean exists = false;
    if (super.init()) {
      try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        JSON_FACTORY = JacksonFactory.getDefaultInstance();
        scope = "https:www.googleapis.com/auth/drive";
        Drive service =
            new Drive.Builder(
                    HTTP_TRANSPORT,
                    JSON_FACTORY,
                    GoogleSheetsCredentials.getCredentialsJson(
                        scope, resolve(meta.getJsonCredentialPath())))
                .setApplicationName(GoogleSheetsCredentials.APPLICATION_NAME)
                .build();
        String wsID = resolve(meta.getSpreadsheetKey());
        String q = "mimeType='application/vnd.google-apps.spreadsheet'";
        FileList result =
            service
                .files()
                .list()
                .setSupportsAllDrives(true)
                .setIncludeItemsFromAllDrives(true)
                .setQ(q)
                .setPageSize(100)
                .setFields("nextPageToken, files(id, name)")
                .execute();
        List<File> spreadsheets = result.getFiles();
        for (File spreadsheet : spreadsheets) {
          if (wsID.equals(spreadsheet.getId())) {
            exists = true; 
            log.logBasic("Spreadsheet:" + wsID + " exists");
          }
        }
        if (!exists && meta.getCreate()) {
          if (!meta.getAppend()) { 
            scope = "https:www.googleapis.com/auth/spreadsheets";
            data.service =
                new Sheets.Builder(
                        HTTP_TRANSPORT,
                        JSON_FACTORY,
                        GoogleSheetsCredentials.getCredentialsJson(
                            scope, resolve(meta.getJsonCredentialPath())))
                    .setApplicationName(GoogleSheetsCredentials.APPLICATION_NAME)
                    .build();
            Spreadsheet spreadsheet =
                new Spreadsheet().setProperties(new SpreadsheetProperties().setTitle(wsID));
            Sheets.Spreadsheets.Create request = data.service.spreadsheets().create(spreadsheet);
            Spreadsheet response = request.execute();
            String spreadsheetID = response.getSpreadsheetId();
            meta.setSpreadsheetKey(spreadsheetID); 
             log.logBasic(response);
             If it does not exist we use the Worksheet ID to rename 'Sheet ID'
            if (resolve(meta.getWorksheetId()) != "Sheet1") {
              SheetProperties title =
                  new SheetProperties().setSheetId(0).setTitle(resolve(meta.getWorksheetId()));
               make a request with this properties
              UpdateSheetPropertiesRequest rename =
                  new UpdateSheetPropertiesRequest().setProperties(title);
               set fields you want to update
              rename.setFields("title");
              log.logBasic("Changing worksheet title to:" + resolve(meta.getWorksheetId()));
              List<Request> requests = new ArrayList<>();
              Request request1 = new Request().setUpdateSheetProperties(rename);
              requests.add(request1);
              BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
              requestBody.setRequests(requests);
               now you can execute batchUpdate with your sheetsService and SHEET_ID
              data.service.spreadsheets().batchUpdate(spreadsheetID, requestBody).execute();
               now if share email is not null we share with R/W with the email given
              if ((resolve(meta.getShareEmail()) != null
                      && !resolve(meta.getShareEmail()).isEmpty())
                  || (resolve(meta.getShareDomain()) != null
                      && !resolve(meta.getShareDomain()).isEmpty())) {
                String fileId = spreadsheetID;
                JsonBatchCallback<Permission> callback =
                    new JsonBatchCallback<Permission>() {
                      @Override
                      public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                          throws IOException {
                         Handle error
                        log.logError("Failed sharing file" + e.getMessage());
                      }
                      @Override
                      public void onSuccess(Permission permission, HttpHeaders responseHeaders)
                          throws IOException {
                        log.logBasic("Shared successfully : Permission ID: " + permission.getId());
                      }
                    };
                BatchRequest batch = service.batch();
                if (resolve(meta.getShareEmail()) != null
                    && !resolve(meta.getShareEmail()).isEmpty()) {
                  log.logBasic("Sharing sheet with:" + resolve(meta.getShareEmail()));
                  Permission userPermission =
                      new Permission()
                          .setType("user")
                          .setRole("writer")
                          .setEmailAddress(resolve(meta.getShareEmail()));
                   Using Google drive service here not spreadsheet data.service
                  service
                      .permissions()
                      .create(fileId, userPermission)
                      .setFields("id")
                      .queue(batch, callback);
                }
                if (resolve(meta.getShareDomain()) != null
                    && !resolve(meta.getShareDomain()).isEmpty()) {
                  log.logBasic("Sharing sheet with domain:" + resolve(meta.getShareDomain()));
                  Permission domainPermission =
                      new Permission()
                          .setType("domain")
                          .setRole("reader")
                          .setDomain(resolve(meta.getShareDomain()));
                  service
                      .permissions()
                      .create(fileId, domainPermission)
                      .setFields("id")
                      .queue(batch, callback);
                }
                batch.execute();
              }
            }
          } else {
            log.logError("Append and Create options cannot be activated altogether");
            return false;
          }
        }
        if (!exists && !meta.getCreate()) {
          log.logError("File does not Exist");
          return false;
        }
      } catch (Exception e) {
        log.logError(
            "Error: for worksheet : "
                + resolve(meta.getWorksheetId())
                + " in spreadsheet :"
                + resolve(meta.getSpreadsheetKey())
                + e.getMessage(),
            e);
        return false;
      }
      return true;
    }
    return false;
  }
@ Override public boolean init ( ) { JsonFactory JSON_FACTORY ; NetHttpTransport HTTP_TRANSPORT ; String scope ; Boolean exists = false ; if ( super . init ( ) ) { try { HTTP_TRANSPORT = GoogleNetHttpTransport . newTrustedTransport ( ) ; JSON_FACTORY = JacksonFactory . getDefaultInstance ( ) ; scope = "https://www.googleapis.com/auth/drive" ; Drive service = new Drive . Builder ( HTTP_TRANSPORT , JSON_FACTORY , GoogleSheetsCredentials . getCredentialsJson ( scope , resolve ( meta . getJsonCredentialPath ( ) ) ) ) . setApplicationName ( GoogleSheetsCredentials . APPLICATION_NAME ) . build ( ) ; String wsID = resolve ( meta . getSpreadsheetKey ( ) ) ; String q = "mimeType='application/vnd.google-apps.spreadsheet'" ; FileList result = service . files ( ) . list ( ) . setSupportsAllDrives ( true ) . setIncludeItemsFromAllDrives ( true ) . setQ ( q ) . setPageSize ( 100 ) . setFields ( "nextPageToken, files(id, name)" ) . execute ( ) ; List < File > spreadsheets = result . getFiles ( ) ; for ( File spreadsheet : spreadsheets ) { if ( wsID . equals ( spreadsheet . getId ( ) ) ) { exists = true ; log . logBasic ( "Spreadsheet:" + wsID + " exists" ) ; } } if ( ! exists && meta . getCreate ( ) ) { if ( ! meta . getAppend ( ) ) { scope = "https://www.googleapis.com/auth/spreadsheets" ; data . service = new Sheets . Builder ( HTTP_TRANSPORT , JSON_FACTORY , GoogleSheetsCredentials . getCredentialsJson ( scope , resolve ( meta . getJsonCredentialPath ( ) ) ) ) . setApplicationName ( GoogleSheetsCredentials . APPLICATION_NAME ) . build ( ) ; Spreadsheet spreadsheet = new Spreadsheet ( ) . setProperties ( new SpreadsheetProperties ( ) . setTitle ( wsID ) ) ; Sheets . Spreadsheets . Create request = data . service . spreadsheets ( ) . create ( spreadsheet ) ; Spreadsheet response = request . execute ( ) ; String spreadsheetID = response . getSpreadsheetId ( ) ; meta . setSpreadsheetKey ( spreadsheetID ) ; if ( resolve ( meta . getWorksheetId ( ) ) != "Sheet1" ) { SheetProperties title = new SheetProperties ( ) . setSheetId ( 0 ) . setTitle ( resolve ( meta . getWorksheetId ( ) ) ) ; UpdateSheetPropertiesRequest rename = new UpdateSheetPropertiesRequest ( ) . setProperties ( title ) ; rename . setFields ( "title" ) ; log . logBasic ( "Changing worksheet title to:" + resolve ( meta . getWorksheetId ( ) ) ) ; List < Request > requests = new ArrayList < > ( ) ; Request request1 = new Request ( ) . setUpdateSheetProperties ( rename ) ; requests . add ( request1 ) ; BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest ( ) ; requestBody . setRequests ( requests ) ; data . service . spreadsheets ( ) . batchUpdate ( spreadsheetID , requestBody ) . execute ( ) ; if ( ( resolve ( meta . getShareEmail ( ) ) != null && ! resolve ( meta . getShareEmail ( ) ) . isEmpty ( ) ) || ( resolve ( meta . getShareDomain ( ) ) != null && ! resolve ( meta . getShareDomain ( ) ) . isEmpty ( ) ) ) { String fileId = spreadsheetID ; JsonBatchCallback < Permission > callback = new JsonBatchCallback < Permission > ( ) { @ Override public void onFailure ( GoogleJsonError e , HttpHeaders responseHeaders ) throws IOException { log . logError ( "Failed sharing file" + e . getMessage ( ) ) ; } @ Override public void onSuccess ( Permission permission , HttpHeaders responseHeaders ) throws IOException { log . logBasic ( "Shared successfully : Permission ID: " + permission . getId ( ) ) ; } } ; BatchRequest batch = service . batch ( ) ; if ( resolve ( meta . getShareEmail ( ) ) != null && ! resolve ( meta . getShareEmail ( ) ) . isEmpty ( ) ) { log . logBasic ( "Sharing sheet with:" + resolve ( meta . getShareEmail ( ) ) ) ; Permission userPermission = new Permission ( ) . setType ( "user" ) . setRole ( "writer" ) . setEmailAddress ( resolve ( meta . getShareEmail ( ) ) ) ; service . permissions ( ) . create ( fileId , userPermission ) . setFields ( "id" ) . queue ( batch , callback ) ; } if ( resolve ( meta . getShareDomain ( ) ) != null && ! resolve ( meta . getShareDomain ( ) ) . isEmpty ( ) ) { log . logBasic ( "Sharing sheet with domain:" + resolve ( meta . getShareDomain ( ) ) ) ; Permission domainPermission = new Permission ( ) . setType ( "domain" ) . setRole ( "reader" ) . setDomain ( resolve ( meta . getShareDomain ( ) ) ) ; service . permissions ( ) . create ( fileId , domainPermission ) . setFields ( "id" ) . queue ( batch , callback ) ; } batch . execute ( ) ; } } } else { log . logError ( "Append and Create options cannot be activated altogether" ) ; return false ; } } if ( ! exists && ! meta . getCreate ( ) ) { log . logError ( "File does not Exist" ) ; return false ; } } catch ( Exception e ) { log . logError ( "Error: for worksheet : " + resolve ( meta . getWorksheetId ( ) ) + " in spreadsheet :" + resolve ( meta . getSpreadsheetKey ( ) ) + e . getMessage ( ) , e ) ; return false ; } return true ; } return false ; }
Initialize and do work where other transforms need to wait for...
Initialize and do work where other transforms need to wait for ...
// Check if file exists // "properties has { key='id' and value='"+wsID+"'}"; // log.logBasic(wsID+" VS "+spreadsheet.getId()); // file exists // If it does not exist & create checkbox is checker create it. // log.logBasic("Create if Not exist is :"+meta.getCreate()); // si append + create alors erreur // Init Service // If it does not exist create it. // // log.logBasic(response); // If it does not exist we use the Worksheet ID to rename 'Sheet ID' // make a request with this properties // set fields you want to update // now you can execute batchUpdate with your sheetsService and SHEET_ID // now if share email is not null we share with R/W with the email given // Handle error // Using Google drive service here not spreadsheet data.service