Read Google sheet API : ExceptionInInitializerError

With the above in mind, you should also check if any library you uploaded in your project conflicts with another version already present in Katalon (the one from Katalon have priority)
This is a common issue we saw before, discussed under various topics.

Thank @anon46315158 for all this precision !

For the moment, I don’t want to venture into Graddle because it’s still a POC with katalon.
I updated all the libraries this morning and it took me forever!

I updated many lib.
Removed all library “sources.jar”
and i have a new error now : java.lang.NoSuchMethodError: com.google.api.client.http.HttpRequest.setResponseReturnRawInputStream(Z)Lcom/google/api/client/http/HttpRequest;

2022-12-29 12:43:13.846 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2022-12-29 12:43:13.850 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/Draft/LireGoogleSheet2
Test Cases/Draft/LireGoogleSheet2
[:]
2022-12-29 12:43:14.325 INFO  c.k.k.c.keyword.builtin.CommentKeyword   - beforeTestCase: Test Cases/Draft/LireGoogleSheet2
déc. 29, 2022 12:43:15 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
AVERTISSEMENT: unable to change permissions for everybody: C:\Users\soukna\nefertiti_auto\tokens
déc. 29, 2022 12:43:15 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
AVERTISSEMENT: unable to change permissions for owner: C:\Users\soukna\nefertiti_auto\tokens
2022-12-29 12:43:15.645 ERROR k.k.c.m.CustomKeywordDelegatingMetaClass - ❌ java.lang.NoSuchMethodError: com.google.api.client.http.HttpRequest.setResponseReturnRawInputStream(Z)Lcom/google/api/client/http/HttpRequest;
2022-12-29 12:43:15.646 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/Draft/LireGoogleSheet2 FAILED.
Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.NoSuchMethodError: com.google.api.client.http.HttpRequest.setResponseReturnRawInputStream(Z)Lcom/google/api/client/http/HttpRequest;
	at technicalFunctions.SheetsQuickstart.invokeMethod(Google.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at LireGoogleSheet2.run(LireGoogleSheet2:1)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:448)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:439)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:418)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:410)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:285)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
	at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
	at TempTestCase1672314190536.run(TempTestCase1672314190536.groovy:25)
Caused by: java.lang.NoSuchMethodError: com.google.api.client.http.HttpRequest.setResponseReturnRawInputStream(Z)Lcom/google/api/client/http/HttpRequest;
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:418)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:514)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$execute.call(Unknown Source)
	at technicalFunctions.SheetsQuickstart.main(Google.groovy:73)
	... 14 more

2022-12-29 12:43:15.662 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/Draft/LireGoogleSheet2

the concerned line is :

ValueRange response = service.spreadsheets().values().get(spreadsheetId, range).execute();
		

the whole code :

package technicalFunctions
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.ValueRange;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class SheetsQuickstart {
	private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
	private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
	private static final String TOKENS_DIRECTORY_PATH = "tokens";

	/**
	 * Global instance of the scopes required by this quickstart.
	 * If modifying these scopes, delete your previously saved tokens/ folder.
	 */
	private static final List<String> SCOPES =
	Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
	private static final String CREDENTIALS_FILE_PATH = "C:/Users/soukna/nefertiti_auto/client_secret.json";

	/**
	 * Creates an authorized Credential object.
	 *
	 * @param HTTP_TRANSPORT The network HTTP Transport.
	 * @return An authorized Credential object.
	 * @throws IOException If the credentials.json file cannot be found.
	 */
	private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
	throws IOException {
		// Load client secrets.
		InputStream intr = new FileInputStream(CREDENTIALS_FILE_PATH);
		if (intr == null) {
			throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
		}
		GoogleClientSecrets clientSecrets =
				GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(intr));

		// Build flow and trigger user authorization request.
		GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
				HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
				.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
				.setAccessType("offline")
				.build();
		LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
		return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
	}

	/**
	 * Prints the names and majors of students in a sample spreadsheet:
	 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
	 */
	public static void main(String args) throws IOException, GeneralSecurityException {
		// Build a new authorized API client service.
		final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
		final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
		final String range = "Class Data!A2:E";
		Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();
		ValueRange response = service.spreadsheets().values().get(spreadsheetId, range).execute();
		List<List<Object>> values = response.getValues();
		if (values == null || values.isEmpty()) {
			System.out.println("No data found.");
		} else {
			System.out.println("Name, Major");
			for (List row : values) {
				// Print columns A and E, which correspond to indices 0 and 4.
				System.out.printf("%s, %s\n", row.get(0), row.get(4));
			}
		}
	}
}

Again i get the error : ExceptionInInitializer…

2022-12-29 14:06:48.255 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2022-12-29 14:06:48.258 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/Draft/LireGoogleSheet
Test Cases/Draft/LireGoogleSheet
[:]
2022-12-29 14:06:48.690 INFO  c.k.k.c.keyword.builtin.CommentKeyword   - beforeTestCase: Test Cases/Draft/LireGoogleSheet
iCi
déc. 29, 2022 2:06:49 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
AVERTISSEMENT: unable to change permissions for everybody: C:\Users\soukna\nefertiti_auto\tokens
déc. 29, 2022 2:06:49 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
AVERTISSEMENT: unable to change permissions for owner: C:\Users\soukna\nefertiti_auto\tokens
2022-12-29 14:06:49.535 ERROR k.k.c.m.CustomKeywordDelegatingMetaClass - ❌ java.lang.ExceptionInInitializerError
2022-12-29 14:06:49.538 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/Draft/LireGoogleSheet FAILED.
Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.ExceptionInInitializerError
	at technicalFunctions.ReadSpreadsheet.invokeMethod(ReadSpreadsheet.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at LireGoogleSheet.run(LireGoogleSheet:26)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:448)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:439)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:418)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:410)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:285)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
	at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
	at TempTestCase1672319204984.run(TempTestCase1672319204984.groovy:25)
Caused by: java.lang.ExceptionInInitializerError
	at com.google.api.services.sheets.v4.Sheets$Builder.build(Sheets.java:2958)
	at com.google.api.services.sheets.v4.Sheets$Builder$build$0.call(Unknown Source)
	at technicalFunctions.ReadSpreadsheet.getSpreadSheetRecords(ReadSpreadsheet.groovy:103)
	at technicalFunctions.ReadSpreadsheet.invokeMethod(ReadSpreadsheet.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at Script1672065789436.run(Script1672065789436.groovy:26)
	... 11 more
Caused by: java.lang.IllegalStateException: You are currently running with version 2.1.1 of google-api-client. You need at least version 1.15 of google-api-client to run version 1.25.0 of the Google Sheets API library.
	at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:200)
	at com.google.api.client.util.Preconditions.checkState(Preconditions.java:115)
	at com.google.api.services.sheets.v4.Sheets.<clinit>(Sheets.java:48)
	at com.google.api.services.sheets.v4.Sheets$Builder.build(Sheets.java:2958)
	at com.google.api.services.sheets.v4.Sheets$Builder$build$0.call(Unknown Source)
	at technicalFunctions.ReadSpreadsheet.getSpreadSheetRecords(ReadSpreadsheet.groovy:103)
	at technicalFunctions.ReadSpreadsheet.invokeMethod(ReadSpreadsheet.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at LireGoogleSheet.run(LireGoogleSheet:26)
	... 11 more

2022-12-29 14:06:49.553 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/Draft/LireGoogleSheet

Thank you for sharing the screenshot of your “External Library Management” dialog. This enabled us to understand your situation better.

You have problems in dependecy management. You have downloaded a lot of (around 70?) jars from somewhere. The erros you got proves that the versions of jars are inconsistent.

What is dependency management? Quoting from
https://docs.gradle.org/current/userguide/core_dependency_management.html#what_is_dependency_management

Software projects rarely work in isolation. In most cases, a project relies on reusable functionality in the form of libraries or is broken up into individual components to compose a modularized system. Dependency management is a technique for declaring, resolving and using dependencies required by the project in an automated fashion.

But you wrote:

You are a brave man!

Nobody would be able to overcome the difficulties without Gradle or Maven. Gradle is a MUST to use any API (including Google Sheet API) which requires a lot of transitive dependencies.

You should look at this at least:

If you surely do not like to venture into Gradle, you should abandon this POC.

@moustik

If you want to use Google Sheet API, you should follow the Google’s official tutorial:

Just do as this document tells you to, and learn how to use Gradle. You should use the plain old Java development tools like vi/emacs editor + Gradle, Eclipse or IntelliJ IDEA, VSCode. But you shouldn’t use Katalon Studio.

If you want to do a POC for Katalon Studio, you shouldn’t try Google Sheet API. You should choose other easier theme to perform a POC for Katalon Studio.


Why shouldn’t you use Katalon Studio here? Because Katalon Studio requires you to select all of appropriate version of external jars and locate them into the project’s Drivers folder. This design is very unique. No other IDEs (like Eclipse, IntelliJ IDEA) does this way. This requirement makes it impossible to apply the dependencies management mechanizm of Gradle and Maven to your projects.

In my humble opinion, this is a fatal design mistake of Katalon Studio. Your POC happened to reveal this issue. Your case demonstrated well how difficult it is to use external jars that are not bundled in the Katalon’s distribution zip. Thank you for your informative report.

If you want to use Google API in Katalon Studio, you need to learn how to use Gradle to resolve external dependencies. And not only that, you have to select and locate the appropriate version of jars out of the downloaded set of jars into the Drivers folder. That is what the katalon-gradle-plugin is supposed to do for you.

Anyway, as long as you do not like to venture into Gradle to resolve external dependecies required by Google API, I think you would never be successful. You had better abandon your POC.

1 Like

It’s my aim.
I have to read a Google Sheet with Katalon Studio.
No choice
This is the way!

It was interesting to see my paragraph was translated from English to French beautifully.

So I tried to translate the paragraph:

into my native tongue Japanse by Google Traslate:

Katalon StudioでGoogle APIを使用する場合は、Gradleを使用して外部依存関係を解決する方法を学ぶ必要があります。それだけでなく、ダウンロードしたjarファイルのセットから適切なバージョンのjarファイルを選択して、Driverフォルダーに配置する必要があります。それがkatalon-gradle-pluginがあなたのためにすることになっていることです。

Good enough translation. Well-done! Google. Just impressive.

Google can traslate it into more languages…

auf Deutsche

Wenn Sie die Google API in Katalon Studio verwenden möchten, müssen Sie lernen, wie Sie Gradle verwenden, um externe Abhängigkeiten aufzulösen. Und nicht nur das, Sie müssen die entsprechende Version von JARs aus dem heruntergeladenen Satz von Jars auswählen und im Ordner Treiber finden. Das ist es, was das katalon-gradle-plugin für Sie tun soll.

по Русские

Если вы хотите использовать Google API в Katalon Studio, вам нужно узнать, как использовать Gradle для разрешения внешних зависимостей. И не только это, вы должны выбрать и найти соответствующую версию jar-файлов из загруженного набора JAR-файлов в папку Drivers. Это то, что katalon-gradle-plugin должен сделать для вас.

In Vietnamese

Nếu bạn muốn sử dụng Google API trong Katalon Studio, bạn cần tìm hiểu cách sử dụng Gradle để giải quyết các phụ thuộc bên ngoài. Và không chỉ vậy, bạn phải chọn và định vị phiên bản lọ thích hợp trong bộ lọ đã tải xuống vào thư mục Trình điều khiển. Đó là những gì katalon-gradle-plugin phải làm cho bạn.

en español

Si quieres usar la API de Google en Katalon Studio, debes aprender a usar Gradle para resolver dependencias externas. Y no solo eso, debe seleccionar y ubicar la versión adecuada de jars del conjunto descargado de jars en la carpeta Controladores. Eso es lo que se supone que el katalon-gradle-plugin debe hacer por ti.

1 Like

Thank you Kazuyaram but i have difficulties to implement gradle with Katalon.
It’s not simple in my company laptop…

I have : “gradle isn’t a recognize command…” in my windows command line.

Besides, I feel like that some person had difficulties to use gradle with Katalon : Dependencies Management with Native Gradle Support (P.o.C) - #8 by kazurayam

I wrote a new post:

http://forum.katalon.com/t/automated-visual-inspection/81966

in there I wrote the procedure to install Gradle into Windows10.

I am not surprised to here you got problems in Windows’ CMD.exe. CMD.exe is rarely supposed to be used for open-source software. You have to find a way to solve your problem in CMD.exe for yourself; I don’t know it and I do not need to find it.

I use Git Bash as a command line interface on Windows OS instead of CMD.exe.

I use SDKMAN! to install Java and Gradle in the command line in Git Bash.

also use a service account. I can support building this. It is really easy implemented this for an old customer with a katalon extension

1 Like

“Integrating Google Sheets API with Katalon Studio Using a Service Account” I have revamped an old article and described exactly how to do this. you can read this in my blog post Integrating Google Sheets API with Katalon Studio Using a Service Account