Исключение с использованием Maven - PullRequest
0 голосов
/ 01 ноября 2019

Я внедряю клиент синхронизации Google SpreadSheet и, выполняя mvn clean install, сталкиваюсь со следующим исключением.

private static final String APPLICATION_NAME = "Data Synchronization";
private static final JsonFactory JSON_FACTORY = JacksonFactory.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 = "/credentials.json";

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

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

List<List<Object>> fetchData(String spreadsheetId, String range) {
    System.out.println("Load data for " + spreadsheetId);
    final NetHttpTransport httpTransport;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Sheets service = new Sheets.Builder(httpTransport, JSON_FACTORY, getCredentials(httpTransport))
                .setApplicationName(APPLICATION_NAME)
                .build();
        ValueRange response = service.spreadsheets().values()
                .get(spreadsheetId, range)
                .execute();

        return response.getValues();

    } catch (GeneralSecurityException | IOException e) {
        throw new IllegalArgumentException("Error fetching data", e);
    }
}

Код прекрасно компилируется с IntelliJ IDEA, но я сталкиваюсь со следующим исключением:

org.junit.jupiter.api.extension.TestInstantiationException: TestInstanceFactory [io.quarkus.test.junit.QuarkusTestExtension] failed to instantiate test class [test.business.journal.control.JournalTest]
Caused by: java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Failed to start quarkus
Caused by: java.lang.VerifyError: 
Bad type on operand stack
Exception Details:
  Location:
    /data_sync/boundary/SpreadSheetClient.fetchData(Ljava/lang/String;Ljava/lang/String;)Ljava/util/List; @94: invokespecial
  Reason:
    Type 'java/lang/Object' (current frame, stack[3]) is not assignable to 'java/lang/Throwable'
  Current Frame:
    bci: @94
    flags: { }
    locals: { '/data_sync/boundary/SpreadSheetClient', 'java/lang/String', 'java/lang/String', 'com/google/api/client/http/javanet/NetHttpTransport', 'java/lang/Object' }
    stack: { uninitialized 86, uninitialized 86, 'java/lang/String', 'java/lang/Object' }
  Bytecode:
    0x0000000: b200 21bb 0022 59b7 0023 1224 b600 252b
    0x0000010: b600 25b6 0026 b600 2701 4eb8 0028 4ebb
    0x0000020: 0029 592d b200 092a 2db7 002a b700 2b12
    0x0000030: 2cb6 002d b600 2e3a 0419 04b6 002f b600
    0x0000040: 302b 2cb6 0031 b600 32c0 0033 3a05 1905
    0x0000050: b600 34b0 3a04 bb00 3759 1238 1904 b700
    0x0000060: 39bf                                   
  Exception Handler Table:
    bci [27, 83] => handler: 84
    bci [27, 83] => handler: 84
  Stackmap Table:
    full_frame(@84,{Object[#106],Object[#107],Object[#107],Object[#108]},{Object[#62]})

Этот код взят из официальных quickstarers из Google Sheets API: https://developers.google.com/sheets/api/quickstart/java

Я попробовал пример, и mvn clean install выдает мне ту же ошибку, что и мой адаптированный код.

Полагаю, это проблема зависимости от maven, но я не уверен в этом. Что именно вызывает проблему?

1 Ответ

0 голосов
/ 01 ноября 2019

Вы делаете это с maven , поэтому вы должны внести некоторые изменения в свой код, потому что в примере быстрого запуска предназначен для использования с gradle . Я дам вам код, который я использовал, и он работал для меня (также работает в IntelliJ IDEA).

Java-код

package com.quickstart;

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.jackson2.JacksonFactory;
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 = JacksonFactory.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 = "/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.
     */
    private static Credential getCredentials(NetHttpTransport HTTP_TRANSPORT) throws Exception {
        // Load client secrets.
        InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // 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");
    }

    public static void main(String[] args) throws Exception {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        final String spreadsheetId = "YOUR SHEET ID";
        // Choose any range you want to
        final String range = "A2:E2";
        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));
            }
        }
    }

}

Не забудьте указать здесь свой идентификатор листа final String spreadsheetId = "YOUR SHEET ID";и поместите файл credentials.json в папку resources .

Для файла maven используйте эти зависимости

maven

 <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-sheets -->
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-sheets</artifactId>
            <version>v4-rev1-1.21.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.gdata</groupId>
            <artifactId>core</artifactId>
            <version>1.47.1</version>
        </dependency>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...