Hello, I'm to interact with the Google Calendar AP...
# getting-started
u
Hello, I'm to interact with the Google Calendar API. There is a Java piece of code that the IntelliJ IDE mostly managed to convert to Kotlin, but it doesn't know how to process the first line of
getCredentials
(where it's supposed to load credentials from a json file) . How can I fix this myself:
Copy code
val `in`: InputStream = CalendarQuickstart::class.java.getResourceAsStream(CREDENTIALS_FILE_PATH)
    ?: throw FileNotFoundException("Resource not found: $CREDENTIALS_FILE_PATH")
Concretely, the Java (
CalendarQuickstart
) class seems to be referring to itself... https://developers.google.com/calendar/api/quickstart/java
c
What leads you to believe that is incorrect? Aside from syntax differences it’s the same as the Java code.
u
@Chris Lee because the IDE is telling me so? It raises an error.
c
And that error is…?
u
@Chris Lee
Unresolved reference: CalendarQuickstart
Btw, here is the whole script:
Copy code
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.DateTime
import com.google.api.client.util.store.FileDataStoreFactory
import com.google.api.services.calendar.Calendar
import com.google.api.services.calendar.CalendarScopes
import com.google.api.services.calendar.model.Event
import com.google.api.services.calendar.model.Events
import java.io.*
import java.security.GeneralSecurityException


class CalendarQuickStart {

    /**
     * Application name.
     */
    private val APPLICATION_NAME = "Google Calendar API Java Quickstart"

    /**
     * Global instance of the JSON factory.
     */
    private val JSON_FACTORY: JsonFactory = GsonFactory.getDefaultInstance()

    /**
     * Directory to store authorization tokens for this application.
     */
    private val TOKENS_DIRECTORY_PATH = "tokens"

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private val SCOPES = listOf(CalendarScopes.CALENDAR_READONLY)
    private val CREDENTIALS_FILE_PATH = "/credentials.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.
     */
    @Throws(IOException::class)
    private fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): Credential {
        // Load client secrets.
        val `in`: InputStream = CalendarQuickstart::class.java.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource not found: $CREDENTIALS_FILE_PATH")
        val clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(`in`))

        // Build flow and trigger user authorization request.
        val flow =
            GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES
            )
                .setDataStoreFactory(
                    FileDataStoreFactory(
                        File(
                            TOKENS_DIRECTORY_PATH
                        )
                    )
                )
                .setAccessType("offline")
                .build()
        val receiver = LocalServerReceiver.Builder().setPort(8888).build()
        //returns an authorized Credential object.
        return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
    }

    @Throws(IOException::class, GeneralSecurityException::class)
    fun main() {
        // Build a new authorized API client service.
        val HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport()
        val service: Calendar = Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build()

        // List the next 10 events from the primary calendar.
        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()
        val items: List<Event> = events.getItems()
        if (items.isEmpty()) {
            println("No upcoming events found.")
        } else {
            println("Upcoming events")
            for (event in items) {
                var start: DateTime = event.getStart().getDateTime()
                if (start == null) {
                    start = event.getStart().getDate()
                }
                System.out.printf("%s (%s)\n", event.getSummary(), start)
            }
        }
    }

}
c
Thx; here’s the corrected version of
getCredentials
, note the use of `javaClass`:
Copy code
public class CalendarQuickStart {
    
    private val CREDENTIALS_FILE_PATH = "/credentials.json"

    private fun getCredentials() {
        // Load client secrets.
        val `in`: InputStream = javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource not found: $CREDENTIALS_FILE_PATH")
    }
}
1
👍 1
🙇 1
k
Yes, using
javaClass
is good here because you don't have to repeat the name of your class. But just to clarify, your error was caused by using
CalendarQuickstart::class
when your class was named
CalendarQuickStart
instead.
☝️ 1
🙇 1
122 Views