/** * * @return * @throws IOException */ private JsonObject getPublicKeysJson() throws IOException { // get public keys URI uri = URI.create(pubKeyUrl); GenericUrl url = new GenericUrl(uri); HttpTransport http = new NetHttpTransport(); HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute(); // store json from request String json = response.parseAsString(); // disconnect response.disconnect(); // parse json to object JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); return jsonObject; }
public BigQueryExporter(BigQueryExporterConfiguration config) { this.config = config; this.checkedSchemas = new HashSet<String>(); this.existingSchemaMap = new HashMap<String, com.google.api.services.bigquery.model.TableSchema>(); HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential; try { credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); } catch (IOException e) { throw new RuntimeException(e); } if (credential.createScopedRequired()) { credential = credential.createScoped(BigqueryScopes.all()); } this.bq = new Bigquery.Builder(transport, jsonFactory, credential) .setApplicationName(this.config.applicationName).build(); }
public GoogleAuthenticator( final String clientId, final UserRepository userRepo, @Nullable final String hostedDomain ) { this.userRepo = userRepo; tokenVerifier = new GoogleIdTokenVerifier.Builder( new NetHttpTransport(), JacksonFactory.getDefaultInstance()) .setAudience(Collections.singleton(clientId)) .setIssuer(ISSUER) .build(); this.hostedDomain = hostedDomain; }
private synchronized YouTube getTubeService() { if( tubeService == null ) { tubeService = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { // Nothing? } }).setApplicationName(EQUELLA).build(); } return tubeService; }
private YouTubeSingleton() { credential = GoogleAccountCredential.usingOAuth2( YTApplication.getAppContext(), Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()); youTube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { } }).setApplicationName(YTApplication.getAppContext().getString(R.string.app_name)) .build(); youTubeWithCredentials = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), credential) .setApplicationName(YTApplication.getAppContext().getString(R.string.app_name)) .build(); }
private void init() { NetHttpTransport.Builder netBuilder = new NetHttpTransport.Builder(); Proxy proxy = ProxyManager.getProxyIf(); if (proxy != null) { netBuilder.setProxy(proxy); } this.customsearch = new Customsearch(netBuilder.build(), new JacksonFactory(), httpRequest -> { }); }
private YouTubeSingleton(Context context) { String appName = context.getString(R.string.app_name); credential = GoogleAccountCredential .usingOAuth2(context, Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()); youTube = new YouTube.Builder( new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException {} } ).setApplicationName(appName).build(); youTubeWithCredentials = new YouTube.Builder( new NetHttpTransport(), new JacksonFactory(), credential ).setApplicationName(appName).build(); }
public YoutubeSearcher(String apiKey) { youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), (HttpRequest request) -> { }).setApplicationName(SpConst.BOTNAME).build(); Search.List tmp = null; try { tmp = youtube.search().list("id,snippet"); } catch (IOException ex) { SimpleLog.getLog("Youtube").fatal("Failed to initialize search: "+ex.toString()); } search = tmp; if(search!=null) { search.setKey(apiKey); search.setType("video"); search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); } }
public String get(String url) { try { HttpRequest request = new NetHttpTransport() .createRequestFactory() .buildGetRequest(new GenericUrl(url)); HttpResponse response = request.execute(); InputStream is = response.getContent(); StringBuilder sb = new StringBuilder(); int ch; while ((ch = is.read()) != -1) { sb.append((char) ch); } response.disconnect(); return sb.toString(); } catch (Exception e) { throw new RuntimeException(); } }
/** * Interface for requesting new connections to the {@link DeploymentManager} service. * * @param credentials The credentials to use to authenticate with the service * @return a new instance of the {@link DeploymentManager} service for issuing requests * @throws CloudManagementException if a service connection cannot be established. */ public DeploymentManager newManager(GoogleRobotCredentials credentials) throws CloudManagementException { try { DeploymentManager.Builder builder = new DeploymentManager.Builder(new NetHttpTransport(), new JacksonFactory(), requireNonNull(credentials).getGoogleCredential(getRequirement())); // The descriptor surfaces global overrides for the API being used // for cloud management. AbstractCloudDeploymentDescriptor descriptor = getDescriptor(); return builder.setApplicationName(Messages.CloudDeploymentModule_AppName()) .setRootUrl(descriptor.getRootUrl()).setServicePath(descriptor.getServicePath()).build(); } catch (GeneralSecurityException e) { throw new CloudManagementException(Messages.CloudDeploymentModule_ConnectionError(), e); } }
public GoogleCredential generateCredentials(){ GoogleCredential credential = null; try { File p12 = new File(this.getClass().getResource("/" + p12FilePath).getFile()); if (!p12.exists()) { p12 = new File(p12FilePath); } credential = new GoogleCredential.Builder() .setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setServiceAccountId(serviceAccountId) .setServiceAccountScopes(asList(scopes.split(";"))) .setServiceAccountPrivateKeyFromP12File(p12) .build(); } catch (GeneralSecurityException | IOException e) { String message = "Cannot generate google credentials for connection."; logger.error(message, e); } return credential; }
private static void createGoogleCredential() throws GeneralSecurityException, IOException { if (SERVICE_ACCOUNT_EMAIL == null) { SERVICE_ACCOUNT_EMAIL = PropertiesUtils.getProperties("google.service_account_email"); } if (SERVICE_ACCOUNT_PKCS12_FILE == null) { openFile(); } if (CREDENTIAL == null) { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); String[] SCOPESArray = {"https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/gmail.compose"}; CREDENTIAL = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(getScopes()) .setServiceAccountPrivateKeyFromP12File(SERVICE_ACCOUNT_PKCS12_FILE) .build(); } else { refreshToken(); } }
public Optional<Credential> load() { Properties properties = new Properties(); try { File file = getAuthenticationFile(options); if(!file.exists() || !file.canRead()) { LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials."); return Optional.empty(); } properties.load(new FileReader(file)); HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory) .setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build(); credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN)); credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN)); return Optional.of(credential); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e); } }
@Test public void testBrokenPipe_NetHttpTransport() throws Failure { HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(); TestService.Iface client = new TestService.Client(new HttpClientHandler( this::endpoint, factory, provider)); try { // The request must be larger than the socket read buffer, to force it to fail the write to socket. client.test(new Request(Strings.times("request ", 1024 * 1024))); fail("No exception"); } catch (HttpResponseException e) { fail("When did this become a HttpResponseException?"); } catch (IOException ex) { // TODO: This should be a HttpResponseException assertThat(ex.getMessage(), is("Error writing request body to server")); } }
/** * Retrieve OAuth 2.0 credentials. * * @return OAuth 2.0 Credential instance. * @throws IOException */ private Credential getCredentials() throws IOException { String code = tokenField.getText(); HttpTransport transport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY"; // Step 2: Exchange --> GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest( transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI).execute(); // End of Step 2 <-- // Build a new GoogleCredential instance and return it. return new GoogleCredential.Builder() .setClientSecrets(CLIENT_ID, CLIENT_SECRET) .setJsonFactory(jsonFactory).setTransport(transport).build() .setAccessToken(response.getAccessToken()) .setRefreshToken(response.getRefreshToken()); }
protected OAuthAuthenticator( String clientId, String requestTokenUri, String accessTokenUri, String authorizeTokenUri, String redirectUri, @Nullable String clientSecret, @Nullable String privateKey) { this.clientId = clientId; this.clientSecret = clientSecret; this.privateKey = privateKey; this.requestTokenUri = requestTokenUri; this.accessTokenUri = accessTokenUri; this.authorizeTokenUri = authorizeTokenUri; this.redirectUri = redirectUri; this.httpTransport = new NetHttpTransport(); this.credentialsStore = new HashMap<>(); this.credentialsStoreLock = new ReentrantLock(); this.sharedTokenSecrets = new HashMap<>(); }
/** * Creates an authorized CloudKMS client service using Application Default Credentials. * * @return an authorized CloudKMS client * @throws IOException if there's an error getting the default credentials. */ public static CloudKMS createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); // Authorize the client using Application Default Credentials // @see https://g.co/dv/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return new CloudKMS.Builder(transport, jsonFactory, credential) .setApplicationName("CloudKMS CryptFile") .build(); }
/** * Creates an authorized CloudKMS client service using Application Default Credentials. * * @return an authorized CloudKMS client * @throws IOException if there's an error getting the default credentials. */ public static CloudKMS createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); // Authorize the client using Application Default Credentials // @see https://g.co/dv/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return new CloudKMS.Builder(transport, jsonFactory, credential) .setApplicationName("CloudKMS snippets") .build(); }
/** * Creates an authorized CloudTasks client service using Application Default Credentials. * * @return an authorized CloudTasks client * @throws IOException if there's an error getting the default credentials. */ private static CloudTasks createAuthorizedClient() throws IOException { // Create the credential HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); // Authorize the client using Application Default Credentials // @see https://g.co/dv/identity/protocols/application-default-credentials GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); // Depending on the environment that provides the default credentials (e.g. Compute Engine, App // Engine), the credentials may require us to specify the scopes we need explicitly. // Check for this case, and inject the scope if required. if (credential.createScopedRequired()) { credential = credential.createScoped(CloudTasksScopes.all()); } return new CloudTasks.Builder(transport, jsonFactory, credential) .setApplicationName("Cloud Tasks Snippets") .build(); }
public YoutubeConnector(Context context) { youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest hr) throws IOException {} }).setApplicationName(context.getString(R.string.app_name)).build(); try{ // Setting search query query = youtube.search().list("id,snippet"); query.setKey(KEY); query.setType("video"); query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)"); }catch(IOException e){ query = null; } }
private Credential getCredential(NetHttpTransport httpTransport) throws IOException, GeneralSecurityException { GoogleDriveConnectionProperties conn = getConnectionProperties(); /* get rid of warning on windows until fixed... https://github.com/google/google-http-java-client/issues/315 */ final java.util.logging.Logger dsLogger = java.util.logging.Logger.getLogger(FileDataStoreFactory.class.getName()); dsLogger.setLevel(java.util.logging.Level.SEVERE); File dataStore; switch (conn.oAuthMethod.getValue()) { case AccessToken: return GoogleDriveCredentialWithAccessToken.builder().accessToken(conn.accessToken.getValue()).build(); case InstalledApplicationWithIdAndSecret: dataStore = new File(conn.datastorePath.getValue()); return GoogleDriveCredentialWithInstalledApplication.builderWithIdAndSecret(httpTransport, dataStore) .clientId(conn.clientId.getValue()).clientSecret(conn.clientSecret.getValue()).build(); case InstalledApplicationWithJSON: dataStore = new File(conn.datastorePath.getValue()); return GoogleDriveCredentialWithInstalledApplication.builderWithJSON(httpTransport, dataStore) .clientSecretFile(new File(conn.clientSecretFile.getValue())).build(); case ServiceAccount: return GoogleDriveCredentialWithServiceAccount.builder() .serviceAccountJSONFile(new File(conn.serviceAccountFile.getValue())).build(); } throw new IllegalArgumentException(messages.getMessage("error.credential.oaut.method")); }
public Storage getStorageService(GoogleRobotCredentials credentials, String version) throws IOException { try { String appName = Messages.UploadModule_AppName(); if (version.length() > 0) { version = version.split(" ")[0]; appName = appName.concat("/").concat(version); } return new Storage.Builder(new NetHttpTransport(), new JacksonFactory(), credentials.getGoogleCredential(getRequirement())) .setApplicationName(appName) .build(); } catch (GeneralSecurityException e) { throw new IOException( Messages.UploadModule_ExceptionStorageService(), e); } }
/** * Send a request to the UserInfo API to retrieve the user's * information. * * @param credentials OAuth 2.0 credentials to authorize the request. * @return User's information. * @throws NoUserIdException An error occurred. */ static Userinfo getUserInfo(Credential credentials) throws NoUserIdException { Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials).build(); Userinfo userInfo = null; try { userInfo = userInfoService.userinfo().get().execute(); } catch (IOException e) { System.err.println("An error occurred: " + e); } if (userInfo != null && userInfo.getId() != null) { return userInfo; } else { throw new NoUserIdException(); } }
@Override public void configure(Binder binder) { // binder.bind(HttpTransport.class).toInstance(new UrlFetchTransport()); binder.bind(HttpTransport.class).toInstance(new NetHttpTransport()); /* * TODO HH? */ binder.bind(DateFormat.class).toInstance( new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'")); binder.bind(JsonFactory.class).toInstance( JacksonFactory.getDefaultInstance()); /* * Global instance of the {@link DataStoreFactory}. The best practice is * to make it a single globally shared instance across your application. */ binder.bind(DataStoreFactory.class).toInstance( AppEngineDataStoreFactory.getDefaultInstance()); binder.bind(AppEngineDataStoreFactory.class).in(Singleton.class); }
/** * On update, retrieves a line status update, and populates an ExtensionData object * ready for publication. The data object my be empty if there are no updates, or may * be populated with some error details if we can't get the status for some reason. */ @Override protected void onUpdateData(int reason) { ExtensionData data = new ExtensionData(); if (shouldGetUpdates()) { try { GenericUrl url = new GenericUrl(getString(R.string.line_status_api_url)); HttpTransport transport = new NetHttpTransport(); HttpRequest req = transport.createRequestFactory().buildGetRequest(url); HttpResponse rsp = req.execute(); data = processResponse(rsp); rsp.disconnect(); } catch (IOException ioe) { // Some kind of connection issue data = populateExtensionData(R.string.error_status, R.string.error_status, getString(R.string.error_request_expanded_body), null); } } publishUpdate(data); }
public void initService(Handler handler) throws CloudsyncException { if (service != null) return; final HttpTransport httpTransport = new NetHttpTransport(); final JsonFactory jsonFactory = new JacksonFactory(); service = new Drive.Builder(httpTransport, jsonFactory, null) .setApplicationName("Backup") .setHttpRequestInitializer(credential) .build(); if (StringUtils.isEmpty(credential.getServiceAccountId())) { credential.setExpiresInSeconds(MIN_TOKEN_REFRESH_TIMEOUT); } try { refreshCredential(); } catch (IOException e) { throw new CloudsyncException("couldn't refresh google drive token"); } handler.getRootItem().setRemoteIdentifier(_getBackupFolder().getId()); }
private static List<Place> performSearch( String kind, String type, double lat, double lng ) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory hrf = httpTransport.createRequestFactory(); String paramsf = "%s?location=%f,%f&rankby=distance&keyword=%s&type=%s&sensor=true&key=%s"; String params = String.format(paramsf, SearchData.BASE_URL, lat, lng, type, kind, AuthUtils.API_KEY); GenericUrl url = new GenericUrl(params); HttpRequest hreq = hrf.buildGetRequest(url); HttpResponse hres = hreq.execute(); InputStream content = hres.getContent(); JsonParser p = new JacksonFactory().createJsonParser(content); SearchData searchData = p.parse(SearchData.class, null); return searchData.buildPlaces(); }
private static Place populateDetails( Place place ) throws IOException { // grab more restaurant details HttpTransport httpTransport = new NetHttpTransport(); HttpRequestFactory hrf = httpTransport.createRequestFactory(); String paramsf = "%s?reference=%s&sensor=true&key=%s"; String params = String.format(paramsf, DetailsData.BASE_URL, place.getReference(), AuthUtils.API_KEY); GenericUrl url = new GenericUrl(params); HttpRequest hreq = hrf.buildGetRequest(url); HttpResponse hres = hreq.execute(); // ByteArrayOutputStream os = new ByteArrayOutputStream(); // IOUtils.copy(hres.getContent(), os, false); // System.out.println( os.toString() ); InputStream content2 = hres.getContent(); JsonParser p = new JacksonFactory().createJsonParser(content2); DetailsData details = p.parse(DetailsData.class, null); details.populatePlace( place ); return place; }
public static Drive getDrive() throws IOException, Docx4JException { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, getClientSecrets(jsonFactory), Arrays.asList(DriveScopes.DRIVE)) .setAccessType("online") .setApprovalPrompt("auto").build(); String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build(); System.out.println("Please open the following URL in your browser then type the authorization code:"); System.out.println(" " + url); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String code = br.readLine(); GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute(); GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response); //Create a new authorized API client return new Drive.Builder(httpTransport, jsonFactory, credential).build(); }
/** * Creates and returns a new {@link AuthorizationCodeFlow} for this app. */ public static AuthorizationCodeFlow newAuthorizationCodeFlow() throws IOException { URL resource = AuthUtil.class.getResource("/oauth.properties"); File propertiesFile = new File("./src/main/resources/oauth.properties"); try { propertiesFile = new File(resource.toURI()); //LOG.info("Able to find oauth properties from file."); } catch (URISyntaxException e) { LOG.info(e.toString()); LOG.info("Using default source path."); } FileInputStream authPropertiesStream = new FileInputStream(propertiesFile); Properties authProperties = new Properties(); authProperties.load(authPropertiesStream); String clientId = authProperties.getProperty("client_id"); String clientSecret = authProperties.getProperty("client_secret"); return new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(), clientId, clientSecret, Collections.singleton(GLASS_SCOPE)).setAccessType("offline") .setCredentialStore(store).build(); }
@Test public void testDescribeRequestAndResponseForApiClient() throws Exception { HttpRequestInitializer initializer = mock(HttpRequestInitializer.class); NetHttpTransport transport = new NetHttpTransport(); Storage storage = new Storage.Builder(transport, new JacksonFactory(), initializer) .setApplicationName("bla").build(); HttpRequest request = storage.objects().delete("bucket", "object").buildHttpRequest(); request.getHeaders().clear(); request.getHeaders().put("k1", "v1"); request.getHeaders().put("k2", "v2"); HttpResponseException exception = null; try { request.execute(); } catch (HttpResponseException ex) { exception = ex; } String expected = "Request: DELETE " + Storage.DEFAULT_BASE_URL + "b/bucket/o/object\n" + "k1: v1\nk2: v2\n\nno content\n\nResponse: 40"; String result = URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), exception); assertTrue(expected + "\nis not a prefix of:\n" + result, result.startsWith(expected)); }
private GoogleCredential openCredential() throws java.security.GeneralSecurityException, java.io.IOException { NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = new JacksonFactory(); GoogleCredential cred = new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(conf.get("google_api_account")) .setServiceAccountScopes(DatastoreOptions.SCOPES) .setServiceAccountPrivateKeyFromP12File(new File(conf.get("google_api_keyfile"))) .build(); return cred; }
protected GoogleAuthorizationCodeFlow getFlow() throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); InputStream is = GoogleOAuth.class.getResourceAsStream( _CLIENT_SECRETS_LOCATION); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( jsonFactory, new InputStreamReader(is)); GoogleAuthorizationCodeFlow.Builder builder = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, clientSecrets, _SCOPES); builder.setAccessType("online"); builder.setApprovalPrompt("force"); return builder.build(); }