IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Java Discussion :

Google Sheets API : écriture impossible depuis une application Java


Sujet :

API standards et tierces Java

  1. #1
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2017
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Transports

    Informations forums :
    Inscription : Octobre 2017
    Messages : 7
    Points : 3
    Points
    3
    Par défaut Google Sheets API : écriture impossible depuis une application Java
    Bonjour,

    Je tente en vain depuis plusieurs jours de modifier des cellules d'une Google Sheet depuis une application Java.

    J'utilise les trois classes suivantes pour cela (que j'ai trouvé sur Internet).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
    import java.util.List;
     
    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.json.jackson2.JacksonFactory;
    import com.google.api.client.util.store.MemoryDataStoreFactory;
    import com.google.api.services.sheets.v4.SheetsScopes;
     
    public class GoogleAuthorizeUtil {
     
        public static Credential authorize() throws IOException, GeneralSecurityException {
            InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/client_secret.json");
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
     
            List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
     
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            		GoogleNetHttpTransport.newTrustedTransport(),
            		JacksonFactory.getDefaultInstance(), clientSecrets, scopes)
            		.setDataStoreFactory(new MemoryDataStoreFactory())
                    .setAccessType("offline")
                    .build();
            Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
     
            return credential;
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import java.io.IOException;
    import java.security.GeneralSecurityException;
     
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.sheets.v4.Sheets;
     
    public class SheetsServiceUtil {
     
        private static final String APPLICATION_NAME = "Google Sheets Example";
     
        public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
            Credential credential = GoogleAuthorizeUtil.authorize();
            return new Sheets.Builder(
            		GoogleNetHttpTransport.newTrustedTransport(),
            		JacksonFactory.getDefaultInstance(), credential)
            		.setApplicationName(APPLICATION_NAME)
            		.build();
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
     
    import org.junit.BeforeClass;
    import org.junit.jupiter.api.Test;
     
    import com.google.api.services.sheets.v4.Sheets;
    import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
    import com.google.api.services.sheets.v4.model.ValueRange;
     
    public class GoogleSheetsIntegrationTest {
     
        private static Sheets sheetsService;
        private static String SPREADSHEET_ID = "1sILuxZUnyl_7-MlNThjt765oWshN3Xs-PPLfqYe4DhI";
     
        @BeforeClass
        public static void setup() throws GeneralSecurityException, IOException {
            sheetsService = SheetsServiceUtil.getSheetsService();
        }
     
       @Test
        public void whenWriteSheet_thenReadSheetOk() throws IOException {
            ValueRange body = new ValueRange()
            		.setValues(Arrays.asList(
            		        Arrays.asList("Expenses January"),
            		        Arrays.asList("books", "30"),
            		        Arrays.asList("pens", "10"),
            		        Arrays.asList("Expenses February"),
            		        Arrays.asList("clothes", "20"),
            		        Arrays.asList("shoes", "15")));
            UpdateValuesResponse result = sheetsService.spreadsheets().values()
            		.update(SPREADSHEET_ID, "A1", body)
            		.setValueInputOption("RAW")
            		.execute();
            System.out.println(result);
        }
     
    }
    J'obtiens ce message d'erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    java.lang.NullPointerException
    	at GoogleSheetsIntegrationTest.whenWriteSheet_thenReadSheetOk(GoogleSheetsIntegrationTest.java:34)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:389)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:167)
    	at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:163)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:110)
    	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:57)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:83)
    	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    	at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
    	at java.util.Iterator.forEachRemaining(Unknown Source)
    	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    	at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    	at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    	at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    	at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
    	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    	at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
    	at java.util.Iterator.forEachRemaining(Unknown Source)
    	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    	at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    	at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    	at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    	at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
    	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:51)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    	at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
    	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
    Pourriez-vous me dire ce qui ne va pas, s'il vous plaît ? Merci.

    Bonne journée.

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Le soucis ne vient pas de l'API mais de ton test, le code suivant n'est jamais exécuté et donc sheetService est null ce qui provoque l'exception dans le test suivant.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     @BeforeClass
        public static void setup() throws GeneralSecurityException, IOException {
            sheetsService = SheetsServiceUtil.getSheetsService();
        }
    L’annotation @BeforeClass provient de JUnit 4 mais tu sembles utiliser JUnit 5 donc a remplacer par :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     @BeforeAll
        public static void setup() throws GeneralSecurityException, IOException {
            sheetsService = SheetsServiceUtil.getSheetsService();
        }
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  3. #3
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2017
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Transports

    Informations forums :
    Inscription : Octobre 2017
    Messages : 7
    Points : 3
    Points
    3
    Par défaut
    Bonjour et merci pour votre réponse.

    J'ai procédé à la rectification et j'obtiens ce message :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    java.lang.NullPointerException
    	at java.io.Reader.<init>(Unknown Source)
    	at java.io.InputStreamReader.<init>(Unknown Source)
    	at com.gofret.sheets.GoogleAuthorizeUtil.authorize(GoogleAuthorizeUtil.java:24)
    	at com.gofret.sheets.SheetsServiceUtil.getSheetsService(SheetsServiceUtil.java:16)
    	at com.gofret.sheets.GoogleSheetsIntegrationTest.setup(GoogleSheetsIntegrationTest.java:21)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:389)
    	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    	at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeBeforeAllMethods$5(ClassTestDescriptor.java:228)
    	at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    	at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeBeforeAllMethods(ClassTestDescriptor.java:227)
    	at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.before(ClassTestDescriptor.java:151)
    	at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.before(ClassTestDescriptor.java:61)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:80)
    	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    	at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
    	at java.util.Iterator.forEachRemaining(Unknown Source)
    	at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    	at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    	at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    	at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    	at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    	at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
    	at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:51)
    	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    	at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
    	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
    J'ai l'impression que le fichier JSON contenant les identifiants n'est pas lu et que la connexion n'est donc pas possible... Le fichier est présentement à l'adresse c:/workspace/Projet/src/main/resources

    Auriez-vous une idée, s'il vous plaît ? Merci.

  4. #4
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Cela dépend ou tu l'as mis par rapport a ta classe/ton package/ton IDE. Avec "/client_secret.json" il faut qu'il soit a la racine du CLASSPATH. Mais effectivement, s'il n'est pas trouvé cela devrait engendrer une erreur de ce genre.
    Pour moi j'ai pu passer cette étape et après j'avais le navigateur qui s'ouvrait pour demander la permission d'utiliser l'application sur mon compte.
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  5. #5
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Octobre 2017
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Transports

    Informations forums :
    Inscription : Octobre 2017
    Messages : 7
    Points : 3
    Points
    3
    Par défaut
    Même si je mets le chemin d'accès complet (c:/Projet/src/main/resources/client_secret.json), j'ai la même erreur en retour...


Discussions similaires

  1. Lancer une video depuis une application java
    Par toma03 dans le forum Débuter avec Java
    Réponses: 5
    Dernier message: 21/03/2008, 00h22
  2. Créer un paquet depuis une application Java
    Par mac88 dans le forum KDE
    Réponses: 2
    Dernier message: 23/02/2008, 19h36
  3. Accéder à la Javadoc depuis une application Java
    Par leelo dans le forum Langage
    Réponses: 4
    Dernier message: 04/10/2007, 18h08
  4. Lancer un .bat depuis une application Java
    Par shindara dans le forum Langage
    Réponses: 1
    Dernier message: 01/05/2007, 10h57

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo