Issue with Google Calendar: Unable to locate com.google.api.client.json.JsonFactory.fromInputStream

Currently, I'm developing a Spring-MVC application and I'm facing an issue while trying to integrate Calendar functionality. The problem seems to be related to authentication due to a json error. I have been using Googles sample code but it appears to be outdated, so I made some adjustments. Would appreciate if you could take a look at the modifications. Error log :

java.lang.NoSuchMethodError: com.google.api.client.json.JsonFactory.fromInputStream(Ljava/io/InputStream;Ljava/lang/Class;)Ljava/lang/Object;
    com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load(GoogleClientSecrets.java:167)
    com.journaldev.spring.utility.OAuth.authorize(OAuth.java:73)

The Oauth class is where I am implementing calendar functionality.

public class OAuth {

    private static final String APPLICATION_NAME = "appname";

    private static final java.io.File DATA_STORE_DIR =
            new java.io.File(System.getProperty("user.home"), "" +
                    "/Store/calendar_sample");

    private static FileDataStoreFactory dataStoreFactory;

    private static HttpTransport httpTransport;

    private static final com.google.api.client.json.JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    private static com.google.api.services.calendar.Calendar client;

    static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();

    public void authorizeAndTest(){

        try {
            httpTransport = new NetHttpTransport();
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
            Credential credential = authorize();

            client = new com.google.api.services.calendar.Calendar.Builder(httpTransport,JSON_FACTORY,credential).setApplicationName(APPLICATION_NAME).build();

            showCalenders();
            addCalendarsUsingBatch();
            Calendar calendar = addCalendar();
            updateCalendar(calendar);
            addEvent(calendar);
            showEvents(calendar);
            deleteCalendarInBatch();
            deleteCalendar(calendar);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Credential authorize() throws Exception{


        InputStream inputStream = new FileInputStream(new File("/home/akshay/c0cc3b4b7502.json"));


        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,inputStream);

// The error occurs on this line.

   if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                        + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
        return null;
    }

    AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,JSON_FACTORY,clientSecrets,
            Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory).build();

    return new AuthorizationCodeInstalledApp(flow,new LocalServerReceiver()).authorize("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc898f998ebc9b919d9590d29f9391">[email protected]</a>");
}

Pom.xml

<dependencies>
    <dependency>
        <groupId>com.google.api.client</groupId>
        <artifactId>google-api-client-json</artifactId>
        <version>1.2.3-alpha</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson2</artifactId>
        <version>1.19.0</version>
    </dependency>


    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-calendar</artifactId>
        <version>v3-rev35-1.13.2-beta</version>
    </dependency>

    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-java6</artifactId>
        <version>1.19.0</version>
    </dependency>

    <dependency>
        <groupId>com.google.gdata</groupId>
        <artifactId>core</artifactId>
        <version>1.47.1</version>
    </dependency>

    <dependency>
        <groupId>com.google.api.client</groupId>
        <artifactId>google-api-client-auth-oauth2</artifactId>
        <version>1.2.3-alpha</version>
    </dependency>

    <dependency>
        <groupId>com.google.api.client</groupId>
        <artifactId>google-api-client</artifactId>
        <version>1.4.1-beta</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson</artifactId>
        <version>1.19.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.0.3.RELEASE</version>
    </dependency>

Error log provided by David :

java.lang.IllegalArgumentException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:76)
    at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
    at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
    at com.journaldev.spring.utility.OAuth.authorize(OAuth.java:75)
    at com.journaldev.spring.utility.OAuth.authorizeAndTest(OAuth.java:53)
    at com.journaldev.spring.controller.PersonController.listCanvas(PersonController.java:586)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.ExpiresFilter.doFilter(ExpiresFilter.java:1179)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)

Answer №1

It is important to consider the following points:

  1. The dependency com.google.gdata.core is not needed for the Calendar API. If it is not required for another Google API, it can be removed.

  2. There are two implementations of the google-http-client: google-http-client-jackson and google-http-client-jackson2. One of them should be removed.

  3. Some dependencies such as

    google-api-client-auth-oauth2:1.2.3-alpha
    and google-api-client:1.4.1-beta are unnecessary and outdated.

  4. The versions of google-api-services-calendar and google-http-client-jackson2 do not match. Use

    google-api-services-calendar:v3-rev121-1.19.0
    with
    google-http-client-jackson2:1.19.0
    .

  5. Replace the google-oauth-client-java6 dependency with google-oauth-client-jetty if the LocalServerReceiver class is needed.

Below is an updated list of dependencies and a modified OAuth class:

    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-calendar</artifactId>
        <version>v3-rev121-1.19.0</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson</artifactId>
        <version>1.19.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.0.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.19.0</version>
    </dependency>

Please note that the path to the json file needs to be updated in the OAuth class:

public class OAuth {

    private static final String APPLICATION_NAME = "APPNAME";

    private static final java.io.File DATA_STORE_DIR =
            new java.io.File(System.getProperty("user.home"), "" +
                    "/Store/calendar_sample");

    private static FileDataStoreFactory dataStoreFactory;

    private static HttpTransport httpTransport;

    private static final com.google.api.client.json.JsonFactory JSON_FACTORY = new JacksonFactory();

    private static com.google.api.services.calendar.Calendar client;


    public void authorizeAndTest() {

        try {
            httpTransport = new NetHttpTransport();
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
            Credential credential = authorize();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Credential authorize() throws Exception {


        FileReader credentialsReader = new FileReader(new File("client_secret_47576556653-go0fkf4c56dohm6m16s2400qed5ps410.apps.googleusercontent.com.json"));

// It gives me an error for line below.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, credentialsReader);
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                    "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                            + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
            return null;
        }

        AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
                Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory).build();

        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("example@example.com");
    }

Answer №2

To resolve the issue, simply comment out the dependency from your Pom.xml file and give it a try:

    <!--dependency>
        <groupId>com.google.api.client</groupId>
        <artifactId>google-api-client-auth-oauth2</artifactId>
        <version>1.2.3-alpha</version>
    </dependency-->

Instead of this:

<dependency>
    <groupId>com.google.api.client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.4.1-beta</version>
</dependency>

We hope this solution works for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while trying to retrieve the response

Currently, I am in the process of developing a script that utilizes node.js, fbgraph API, and the express framework. My task involves sending the user's access_token from an index.html page to the nodejs server via a POST request. I have successfully ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

Executing several API endpoint requests using an array in Node.js

Having difficulty utilizing values from an array to make API calls to endpoints. The array contains necessary data to retrieve the information needed from the endpoint. However, when attempting to parse the JSON text received from the API call and extract ...

Is there a method to automatically replace the latest or asterisk (*) symbol in package.json with a specific version number?

When managing my project library using npm's Node Packaged Modules, I encountered issues with the unconditional latest update version causing unmet dependencies errors. I attempted to change all latest versions to my current local version, utilizing ...

JSON response detailing the status of GPIO ports on a Raspberry Pi server

Lately, I've been facing some difficulties for a couple of days. My question is pretty straightforward - is there a way to create a server on Raspberry Pi that can provide the current status of GPIO ports in JSON format? For instance: Http://192.168 ...

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...

Why does Request-Body(req.body) display a value while Request-QueryParams(req.queryParams) returns null?

Using vuejs-axios, I successfully transferred client-side data to the server-side using Java with SparkJAVA Framework to manage the request-response cycle. The following code snippets demonstrate how Form-Data is posted from vuejs to java. const formData ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

The compatibility between Node.js and Git seems to be lacking

I'm attempting to set up automatic deployment with GitHub. I have created a JavaScript file to act as a "server" to receive the hook from GitHub, and that part is working flawlessly. However, I'm struggling with getting my hook.sh script to execu ...

Tips on excluding null or empty values when writing to JSON with NodeJS

When saving the following content to a JSON file, I want to exclude any fields with a value of null or blank. Specifically, I do not want to include productPrice and productRating fields in the JSON file. Since I am not very familiar with NodeJS, can someo ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

Displaying JSON data from the API on a webpage within a NodeJS weather application

Currently, I am in the process of developing a weather application using NodeJS. I have successfully retrieved JSON formatted data from the weather site's API. Nonetheless, I am perplexed about how to transmit this data to the application. Below is a ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

Steps to retrieve the JSON response using newman

After successfully testing the endpoint on Postman, I exported it as a collection and now running it using Newman on Jenkins CI. Command: newman run <POSTMAN_COLLECTION>.json -r json,cli The response.json file is generated in the current direct ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

You have reached the maximum limit for the quota group 'AnalyticsDefaultGroup' with the restriction 'Requests per user per 100 seconds'

I'm attempting to retrieve data from Google Analytics using the Googleapis npm package. let res= await analyticsreporting.reports.batchGet({ requestBody: { reportRequests: [ { viewId: defaultPro ...

Does the compression ratio for GZip change depending on the library used, such as Zlib in NodeJS and SharpZipLib in .Net?

Context: I am currently conducting tests on the compression ratio of our device. The data from the device is transmitted in the form of Json payloads, specifically in JArray format. I will be measuring the size of this data in Bytes before it undergoes com ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...