Read Google sheet API : ExceptionInInitializerError

your original problem is, you don’t understand how various java libraries depend on each other, and why central repositories are important (aside of using up-to-date libraries)
read a bit on this, please

Thank you Bionel !
if you have documentation, I’m interested.

I already showed enough information to you.

In the Stacktrace, you can find a message:

Caused by: java.lang.IllegalStateException: No match found
	at com.google.api.client.googleapis.GoogleUtils.<clinit>(GoogleUtils.java:66)

This is the immediate point where a ExceptionInInitializationError occured. So you should read the source of GoogleUtils.java. I showed you the URL already.

I am afraid you, @moustik, ignored this information that I provided. You did not read the source code of GoogleUtil.java at all. You should note that the truth about programs always lies in the source code; nowhere else.

At the line#66 of the GoogleUtils.java, you can find the following statement:

63: static {
64:     Matcher versionMatcher = VERSION_PATTERN.matcher(VERSION);
65:     versionMatcher.find();
66:     MAJOR_VERSION = Integer.parseInt(versionMatcher.group(1)); // HERE THE ERROR OCCURED

versionMatcher.group(1) failed and complaied "No match found". So you need to think why versionMatcher.group(1) failed. … It seems that the VERSION variable had an unexpected value.

Then how the VERSION variable is initialized? … By the following code snipet:

35:  /** Current release version. */
36:  public static final String VERSION = getVersion();

How is the getVersion() method implemented?

91: private static String getVersion() {
    // attempt to read the library's version from a properties file generated during the build
    // this value should be read and cached for later use
    String version = null;
    try (InputStream inputStream =
        GoogleUtils.class.getResourceAsStream("google-api-client.properties")) {
      if (inputStream != null) {
        Properties properties = new Properties();
        properties.load(inputStream);
        version = properties.getProperty("google-api-client.version");
      }
    } catch (IOException e) {
      // ignore
    }
    return version == null ? "unknown-version" : version;
  }

The getVersion() method tries to load a properties file named google-api-client.properties, which must be bundled in some jar file. Which jar file? I find no clue in the GoogleUtils.java source file.

I looked around the GitHub repository, and found a file named google-api-client.properties.

which contains a line:

google-api-client.version=${project.version}

The getVersion() method could possibly return a string which is either of

  1. a string like "2.1.2" which is generated during a build process
  2. something else; like "unknown-version".

You should note that, if the statement GoogleUtils.class.getResourceAsStream("google-api-client.properties")) failed for some reason, then the getVersion() will return a string unknown-version. When unknown-version is returned, then a "No match found" error will be raised.

That’s all I can trace for sure what could happen.

@moustik

I guess, you used the jar files which are incomplete somehow. But I do not know how and why. You should be able to look into the jar file and try to see if the “google-api-client.properties” is really contained in the jar. If contained, you should check how the file is coded. That’s the first thing you should check. I guess, you would find something interesting in the jar. If not, I have no more idea.

No, this problem does not reside in this line. This line is not immediately causing the “No match found” error. This line is just an entrance into a dark cave. The problem resides somewhere in the darkness.

@kazurayam This is my jars:
maybe there are jars that need to be removed or added ?

next :

next :

other way, i investigate on the net and i found one post :

I read all the post and i make some verification but always the same error : ExceptionInInitializerError :sob: :sob: :sob:

I have no more input. I will quite.

Looks like you have google-api-client 1.32.x which is quite old.
On Maven central, latest is 2.1.1

https://mvnrepository.com/artifact/com.google.api-client/google-api-client

So, I suggest, remove all of them, grab the latest from maven (using either maven or gradle) alongside all dependencies.

@kazurayam already provided some hints on how to do it, and if you search the forum you may find more tips and tricks on this matter.

e.g you can try the Grape trick:

Well, a quick view here:

The most important is:

One of the core features of Maven is its ability to handle Transitive Dependencies. That is, to find and download the dependencies of your dependencies, and their dependencies also , recursively, until they are all satisfied.

So, by using a certain dependency management tool (Maven, Gradle, Grape whatever) you are sure that all dependencies are satisfied properly.

Downloading manually from web, chances are high that you are missing something, or you can grab a wrong version for a certain library needed. Such is almost imposible to debug, you have to look into all of them code.

Another important thing is, use up to date libraries (as much as possible)
It has been already pointed that, the article you used as a source for your project is very old, it was written for java 1.7.
Katalon is not using the very latest java, but still, it is using openjdk8 which is newer.

Since that article was written, lot of libraries were updated.

Another thing to consider, Katalon is not a Maven project.
Maven it is not aware of whatever is installed.
So, by using Maven to grab everything needed, you may grab also duplicated libs, possible having a different version, thus conflicting with the libraries already present.

With this in mind, using the Gradle POC or the Grape trick, you have better chances to get propper versions (libraries already present in Katalon should be skipped)

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:

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