List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport
public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException
From source file:nl.dukesolutions.picasa.fxml.OAuth2.java
License:Apache License
public UserInfo login() { try {/*from w ww . jav a 2s . c o m*/ httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization Credential credential = authorize(); // set up global Oauth2 instance oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); // run commands String email = tokenInfo(credential.getAccessToken()); // success! return new UserInfo(email, credential.getAccessToken()); } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:no.dusken.momus.controller.DevController.java
License:Apache License
@RequestMapping("/gdoc") public @ResponseBody String gdocTest() { JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = null;/*from w w w . j av a 2 s . c om*/ try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException | IOException e) { e.printStackTrace(); } try { if (credential == null) { String email = "68986569027-ecn9md3ej7krhquhvamf7phfovro8aru@developer.gserviceaccount.com"; ClassPathResource classPathResource = new ClassPathResource("googlekey.p12"); File file = classPathResource.getFile(); Collection<String> scopes = new ArrayList<>(); scopes.add("https://www.googleapis.com/auth/drive"); logger.info("making credentials"); credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory) .setServiceAccountId(email) // .setServiceAccountPrivateKey .setServiceAccountPrivateKeyFromP12File(file).setServiceAccountScopes(scopes).build(); logger.info("made credentials"); } if (drive == null) { drive = new Drive.Builder(httpTransport, jsonFactory, credential) .setApplicationName("momustest-molten-aurora-752").build(); logger.info("made drive"); } long start = System.currentTimeMillis(); // list all files Drive.Files.List request = drive.files().list(); FileList fileList = request.execute(); List<com.google.api.services.drive.model.File> items = fileList.getItems(); for (com.google.api.services.drive.model.File item : items) { logger.info("file: {}", item); // Map<String, String> exportLinks = item.getExportLinks();//.get("text/html"); // String s = exportLinks.get("text/plain"); // will crash for stuff not having this // logger.debug("test"); } About execute = drive.about().get().execute(); // insert file // com.google.api.services.drive.model.File insertFile = new com.google.api.services.drive.model.File(); // insertFile.setTitle("mats2.odt"); // insertFile.setMimeType("application/vnd.google-apps.document"); // com.google.api.services.drive.model.File uploaded = drive.files().insert(insertFile).execute(); // logger.info("uploaded file id({}): {}", uploaded.getId(), uploaded); // // Permission permission = new Permission(); // permission.setRole("writer"); // permission.setType("anyone"); // permission.setValue("default"); // permission.setWithLink(true); // // drive.permissions().insert(uploaded.getId(), permission).execute(); long end = System.currentTimeMillis(); long timeUsed = end - start; logger.debug("Time spent: {}ms", timeUsed); } catch (GeneralSecurityException | IOException e) { logger.debug("Ex: ", e); } return "gdoc ok"; }
From source file:no.dusken.momus.service.drive.GoogleDriveService.java
License:Apache License
@PostConstruct private void setup() { if (!enabled) { logger.info("Not setting up Google Drive"); return;//from w ww .jav a 2 s .c o m } logger.info("Setting up Google Drive"); GoogleCredential credentials; HttpTransport httpTransport; java.io.File keyFile; JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); List<String> scopes = Arrays.asList("https://www.googleapis.com/auth/drive"); // We want full access try { keyFile = new ClassPathResource("googlekey.p12").getFile(); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); credentials = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory) .setServiceAccountId(email).setServiceAccountPrivateKeyFromP12File(keyFile) .setServiceAccountScopes(scopes).build(); } catch (GeneralSecurityException | IOException e) { logger.warn("Couldn't create Google Drive credentials: ", e); return; } drive = new Drive.Builder(httpTransport, jsonFactory, credentials).setApplicationName(appName).build(); logger.info("Successfully set up Google Drive"); }
From source file:nu.t4.beans.APLManager.java
public GoogleIdToken.Payload googleAuth(String idTokenString) { //Varibler fr verifiering HttpTransport httpTransport;// ww w . j ava 2 s . co m JsonFactory jsonFactory; GoogleIdTokenVerifier verifier; try { jsonFactory = JacksonFactory.getDefaultInstance(); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); verifier = new GoogleIdTokenVerifier.Builder(httpTransport, jsonFactory) .setAudience(Arrays.asList(CLIENT_ID)).build(); } catch (Exception e) { return null; } GoogleIdToken idToken; try { idToken = verifier.verify(idTokenString); } catch (Exception ex) { return null; } //idToken blir null ifall den r felaktig if (idToken != null) { //Ta ut datan vi behver frn det verifierade idTokenet return idToken.getPayload(); //if (payload.getHostedDomain().equals(APPS_DOMAIN_NAME)) { /* } else { return Response.status(Response.Status.FORBIDDEN).build(); }*/ } else { return null; } }
From source file:nurseconsole1cserver.Notifications.ServerEvents.java
public ServerEvents() { try {//from w ww . j a v a 2s . co m // initialize the transport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // initialize the data store factory 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(); Calendar calendar = addCalendar(); addEvent(calendar); } catch (IOException e) { System.err.println(e.getMessage()); } catch (Throwable t) { System.err.println(t.getMessage()); } }
From source file:org.ado.minesync.translation.drive.DriveClientFactory.java
License:Open Source License
/** * @return @{Drive}/*ww w . j a v a 2 s. co m*/ * @throws RuntimeException if any error occurred during the creation of Drive client */ public static Drive createDrive() { try { // initialize the transport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // initialize the data store factory dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization Credential credential = authorize(); // set up global Drive instance final Drive client = new Drive.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); return client; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.beam.sdk.util.Credentials.java
License:Apache License
/** * Loads OAuth2 credential from client secrets, which may require an * interactive authorization prompt./* w w w .j a v a 2s . c o m*/ */ private static Credential getCredentialFromClientSecrets(GcpOptions options, Collection<String> scopes) throws IOException, GeneralSecurityException { String clientSecretsFile = options.getSecretsFile(); checkArgument(clientSecretsFile != null); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); GoogleClientSecrets clientSecrets; try { clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(clientSecretsFile)); } catch (IOException e) { throw new RuntimeException("Could not read the client secrets from file: " + clientSecretsFile, e); } FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory( new java.io.File(options.getCredentialDir())); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory) .setTokenServerUrl(new GenericUrl(options.getTokenServerUrl())) .setAuthorizationServerEncodedUrl(options.getAuthorizationServerEncodedUrl()).build(); // The credentialId identifies the credential if we're using a persistent // credential store. Credential credential = new AuthorizationCodeInstalledApp(flow, new PromptReceiver()) .authorize(options.getCredentialId()); LOG.info("Got credential from client secret"); return credential; }
From source file:org.apache.druid.common.gcp.GcpModule.java
License:Apache License
@Provides @LazySingleton public HttpTransport getHttpTransport() throws GeneralSecurityException, IOException { return GoogleNetHttpTransport.newTrustedTransport(); }
From source file:org.apache.ignite.spi.discovery.tcp.ipfinder.gce.TcpDiscoveryGoogleStorageIpFinder.java
License:Apache License
/** * Google Cloud Storage initialization./*from w w w. j a v a 2 s . co m*/ * * @throws IgniteSpiException In case of error. */ private void init() throws IgniteSpiException { if (initGuard.compareAndSet(false, true)) { if (srvcAccountId == null || srvcAccountP12FilePath == null || projectName == null || bucketName == null) { throw new IgniteSpiException("One or more of the required parameters is not set [serviceAccountId=" + srvcAccountId + ", serviceAccountP12FilePath=" + srvcAccountP12FilePath + ", projectName=" + projectName + ", bucketName=" + bucketName + "]"); } try { NetHttpTransport httpTransport; try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException | IOException e) { throw new IgniteSpiException(e); } GoogleCredential cred; try { cred = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JacksonFactory.getDefaultInstance()).setServiceAccountId(srvcAccountId) .setServiceAccountPrivateKeyFromP12File(new File(srvcAccountP12FilePath)) .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)) .build(); } catch (Exception e) { throw new IgniteSpiException("Failed to authenticate on Google Cloud Platform", e); } try { storage = new Storage.Builder(httpTransport, JacksonFactory.getDefaultInstance(), cred) .setApplicationName(projectName).build(); } catch (Exception e) { throw new IgniteSpiException("Failed to open a storage for given project name: " + projectName, e); } boolean createBucket = false; try { Storage.Buckets.Get getBucket = storage.buckets().get(bucketName); getBucket.setProjection("full"); getBucket.execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { U.warn(log, "Bucket doesn't exist, will create it [bucketName=" + bucketName + "]"); createBucket = true; } else throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e); } catch (Exception e) { throw new IgniteSpiException("Failed to open the bucket: " + bucketName, e); } if (createBucket) { Bucket newBucket = new Bucket(); newBucket.setName(bucketName); try { Storage.Buckets.Insert insertBucket = storage.buckets().insert(projectName, newBucket); insertBucket.setProjection("full"); insertBucket.setPredefinedDefaultObjectAcl("projectPrivate"); insertBucket.execute(); } catch (Exception e) { throw new IgniteSpiException("Failed to create the bucket: " + bucketName, e); } } } finally { initLatch.countDown(); } } else { try { U.await(initLatch); } catch (IgniteInterruptedCheckedException e) { throw new IgniteSpiException("Thread has been interrupted.", e); } if (storage == null) throw new IgniteSpiException("IpFinder has not been initialized properly"); } }
From source file:org.apache.manifoldcf.crawler.connectors.googledrive.GoogleDriveSession.java
License:Apache License
/** Constructor. Create a session. *//* w ww . j a v a2 s . c o m*/ public GoogleDriveSession(String clientId, String clientSecret, String refreshToken) throws IOException, GeneralSecurityException { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credentials = new GoogleCredential.Builder().setClientSecrets(clientId, clientSecret) .setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).build().setRefreshToken(refreshToken); drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials).setApplicationName(APPNAME).build(); }