Java Code Examples for com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()

The following examples show how to use com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection.
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
  if (serviceAccountsApiStub == null) {
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      Collection<String> scopes = IamScopes.all();
      credential = credential.createScoped(scopes);
    }
    serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
        .build()
        .projects()
        .serviceAccounts();
  }
  return serviceAccountsApiStub;
}
 
Example 2
Source File: StorageFactory.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();

  // Depending on the environment that provides the default credentials (for
  // example: Compute Engine, App Engine), the credentials may require us to
  // specify the scopes we need explicitly.  Check for this case, and inject
  // the Cloud Storage scope if required.
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, new HttpCredentialsAdapter(credential))
      .setApplicationName("GCS Samples")
      .build();
}
 
Example 3
Source File: GCPProject.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Projects api object used for accessing the Cloud Resource Manager Projects API.
 * @return Projects api object used for accessing the Cloud Resource Manager Projects API
 * @throws GeneralSecurityException Thrown if there's a permissions error.
 * @throws IOException Thrown if there's an IO error initializing the API object.
 */
public static synchronized Projects getProjectsApiStub()
    throws GeneralSecurityException, IOException {
  if (projectApiStub != null) {
    return projectApiStub;
  }
  HttpTransport transport;
  GoogleCredential credential;
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  transport = GoogleNetHttpTransport.newTrustedTransport();
  credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = CloudResourceManagerScopes.all();
    credential = credential.createScoped(scopes);
  }
  projectApiStub = new CloudResourceManager
      .Builder(transport, jsonFactory, credential)
      .build()
      .projects();
  return projectApiStub;
}
 
Example 4
Source File: SearchHelper.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Factory method for {@code SearchHelper} objects.
 *
 * @param searchAuthInfo object containing the info to authenticate the impersonated user
 * @param searchApplicationId ID of the serving application linked to the data sourced containing
 *  the items to serving (this is can be obtained from the Admin console)
 * @param rootUrl URL of the Indexing API
 */
public static SearchHelper createSearchHelper(
    SearchAuthInfo searchAuthInfo, String searchApplicationId, Optional<String> rootUrl)
    throws GeneralSecurityException, IOException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  Credential credential = createCredentials(transport, searchAuthInfo);

  CloudSearch.Builder builder =
      new CloudSearch.Builder(
              transport,
              JSON_FACTORY,
              createChainedHttpRequestInitializer(credential, RETRY_REQUEST_INITIALIZER))
          .setApplicationName(SEARCH_APPLICATION_NAME);
  rootUrl.ifPresent(r -> builder.setRootUrl(r));
  return new SearchHelper(builder.build(), searchApplicationId);
}
 
Example 5
Source File: MlEngineModel.java    From zoltar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Google Cloud ML Engine backed model.
 *
 * @param id {@link Model.Id} needs to be created with the following format:
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}"</pre>
 *     or
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}/versions/{MODEL_VERSION}"</pre>
 */
public static MlEngineModel create(final Model.Id id)
    throws IOException, GeneralSecurityException {
  final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  final GoogleCredential credential =
      GoogleCredential.getApplicationDefault()
          .createScoped(CloudMachineLearningEngineScopes.all());

  final CloudMachineLearningEngine mlEngine =
      new CloudMachineLearningEngine.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName(APPLICATION_NAME)
          .build();

  return new AutoValue_MlEngineModel(id, mlEngine, httpTransport);
}
 
Example 6
Source File: GoogleCredentials.java    From halyard with Apache License 2.0 5 votes vote down vote up
public static HttpTransport buildHttpTransport() {
  try {
    return GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException("Failed to build trusted transport", e);
  }
}
 
Example 7
Source File: GoogleSheetsService.java    From q with Apache License 2.0 5 votes vote down vote up
private void initSpreadsheetService() throws Throwable, IOException
{
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    spreadsheetService = new SpreadsheetService(Properties.googleAppName.get());
    GoogleCredential googleCredential = buildGoogleCredential();
    spreadsheetService.setOAuth2Credentials(googleCredential);
    spreadsheetsFeedUrl = FEED_URL_FACTORY.getSpreadsheetsFeedUrl();
}
 
Example 8
Source File: GoogleCalendarAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public com.google.api.services.calendar.Calendar getAuthorizedCalendar(String appName,
                                                                       String clientSecretJSON) {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = authorize(clientSecretJSON);
        return new com.google.api.services.calendar.Calendar.Builder(
                HTTP_TRANSPORT,
                JSON_FACTORY,
                credential).setApplicationName(appName).build();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 9
Source File: GoogleTasksAuth.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public Tasks getTasksService(String appName,
                             String clientSecretJSON) {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = authorize(clientSecretJSON);
        return new Tasks.Builder(HTTP_TRANSPORT,
                                 JSON_FACTORY,
                                 credential)
                .setApplicationName(appName)
                .build();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 10
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
	log.debug("GoogleDriveServiceImpl init");
	OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	clientId = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_ID, null);
	clientSecret = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_SECRET, null);
	redirectUri = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_REDIRECT_URI, "http://localhost:8080/sakai-googledrive-tool");

	try {
		JsonNode rootNode = OBJECT_MAPPER.createObjectNode();
		JsonNode webInfo = OBJECT_MAPPER.createObjectNode();
		((ObjectNode) webInfo).put("client_id", clientId);
		//((ObjectNode) webInfo).put("project_id", "algebraic-creek-243007");
		((ObjectNode) webInfo).put("auth_uri", ENDPOINT_AUTH);
		((ObjectNode) webInfo).put("token_uri", ENDPOINT_TOKEN);
		((ObjectNode) webInfo).put("auth_provider_x509_cert_url", ENDPOINT_CERTS);
		((ObjectNode) webInfo).put("client_secret", clientSecret);
		((ObjectNode) rootNode).set("web", webInfo);
		InputStream isJson = IOUtils.toInputStream(rootNode.toString());
		isJson.close();//?

		httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		jsonFactory = JacksonFactory.getDefaultInstance();
		clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(isJson));

		DataStoreFactory dataStore = new JPADataStoreFactory(googledriveRepo);			
		flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Collections.singleton(DriveScopes.DRIVE))
				.setDataStoreFactory(dataStore)
				.setApprovalPrompt("force")
				.setAccessType("offline")
				.build();
	} catch(Exception e) {
		log.error("Error while trying to init Google Drive configuration");
	}

	driveRootItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveRootItemsCache");
	driveChildrenItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveChildrenItemsCache");
	googledriveUserCache = memoryService.<String, Drive>getCache("org.sakaiproject.googledrive.service.googledriveUserCache");
	driveItemsCache = memoryService.<String, GoogleDriveItem>getCache("org.sakaiproject.googledrive.service.driveItemsCache");
}
 
Example 11
Source File: ServiceAccountConfiguration.java    From play-work with Apache License 2.0 5 votes vote down vote up
public static Pubsub createPubsubClient(String serviceAccountEmail, String privateKeyFilePath)
    throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(transport)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountScopes(PubsubScopes.all())

      // Obtain this from the "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      // (and put the e-mail address into your system property obviously)
      .setServiceAccountId(serviceAccountEmail)

      // Download this file from "APIs & auth" -> "Credentials"
      // section in the Google Developers Console:
      // https://console.developers.google.com/
      .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFilePath))
      .build();


  // Please use custom HttpRequestInitializer for automatic
  // retry upon failures.  We provide a simple reference
  // implementation in the "Retry Handling" section.
  HttpRequestInitializer initializer =
      new RetryHttpInitializerWrapper(credential);
  return new Pubsub.Builder(transport, JSON_FACTORY, initializer)
      .setApplicationName("PubSub Example")
      .build();
}
 
Example 12
Source File: LifecycleIT.java    From spydra with Apache License 2.0 5 votes vote down vote up
private boolean isClusterCollected(SpydraArgument arguments)
    throws IOException, GeneralSecurityException {
  GoogleCredential credential = new GcpUtils().getCredential();
  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(
            Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  Dataproc dataprocService =
      new Dataproc.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName("Google Cloud Platform Sample")
          .build();

  Dataproc.Projects.Regions.Clusters.List request =
      dataprocService.projects().regions().clusters().list(
          arguments.getCluster().getOptions().get(SpydraArgument.OPTION_PROJECT),
          arguments.getRegion());
  ListClustersResponse response;
  do {
    response = request.execute();
    if (response.getClusters() == null) continue;

    String clusterName = arguments.getCluster().getName();
    for (Cluster cluster : response.getClusters()) {
      if (cluster.getClusterName().equals(clusterName)) {
        String status = cluster.getStatus().getState();
        LOGGER.info("Cluster state is" + status);
        return status.equals("DELETING");
      }
    }

    request.setPageToken(response.getNextPageToken());
  } while (response.getNextPageToken() != null);
  return true;
}
 
Example 13
Source File: GoogleStorageCacheManager.java    From simpleci with MIT License 5 votes vote down vote up
private Storage createClient() throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential.fromStream(
            new ByteArrayInputStream(settings.serviceAccount.getBytes(StandardCharsets.UTF_8)))
                                                  .createScoped(Collections.singleton(StorageScopes.CLOUD_PLATFORM));

    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Storage.Builder(
            httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                                              .setHttpRequestInitializer(credential).build();
}
 
Example 14
Source File: StorageFactory.java    From dlp-dataflow-deidentification with Apache License 2.0 5 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS")
      .build();
}
 
Example 15
Source File: GceApi.java    From simpleci with MIT License 5 votes vote down vote up
private Compute createApi(GoogleComputeProvider provider) throws IOException, GeneralSecurityException {
    GoogleCredential credential = GoogleCredential
            .fromStream(new ByteArrayInputStream(provider.gcAccount.serviceAccount.getBytes(StandardCharsets.UTF_8)))
            .createScoped(Collections.singleton(ComputeScopes.COMPUTE));

    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    return new Compute.Builder(
            httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                                              .setHttpRequestInitializer(credential).build();
}
 
Example 16
Source File: gdoc2adoc.java    From gdoc2adoc with Apache License 2.0 5 votes vote down vote up
@Override
public Integer call() throws Exception { // your business logic goes here...
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Docs docsService =
            new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                    .setApplicationName(APPLICATION_NAME)
                    .build();


    documentid =  documentid.replaceAll("^.*/document/d/([a-zA-Z0-9-_]+)/?.*$",
            "$1");

    try {
        Document doc = docsService.documents().get(documentid).execute();

        var v = new GDocVisitor();

        if(dump) {

            ObjectMapper mapper = new ObjectMapper(new com.fasterxml.jackson.core.JsonFactory());
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc));

        } else {
           System.out.println(v.visit(doc));
        }

        //Gson gson = new GsonBuilder().setPrettyPrinting().create();


        //System.out.println(gson.toJson(response));
    } catch(GoogleJsonResponseException e) {
        throw new IllegalStateException("Error fetching document id " + documentid, e);
    }
    return 0;
}
 
Example 17
Source File: CloudSearchService.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
private static CloudSearch getCloudSearchService(String keyFile, Optional<String> rootUrl)
    throws IOException, GeneralSecurityException {
  InputStream in = Files.newInputStream(Paths.get(keyFile));
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  Credential credential = GoogleCredential
      .fromStream(in, httpTransport, JSON_FACTORY)
      .createScoped(API_SCOPES);
  Builder builder = new CloudSearch.Builder(
      httpTransport,
      JSON_FACTORY,
      createChainedHttpRequestInitializer(credential, RETRY_REQUEST_INITIALIZER))
      .setApplicationName(APPLICATION_NAME);
  rootUrl.ifPresent(builder::setRootUrl);
  return builder.build();
}
 
Example 18
Source File: GCSFilesSource.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
private static Storage constructStorageApiStub() throws GeneralSecurityException, IOException {
  JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport;
  transport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }
  return new Storage.Builder(transport, jsonFactory, credential)
      .setApplicationName("GCS Samples")
      .build();
}
 
Example 19
Source File: ComputeEngineSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    // Authenticate using Google Application Default Credentials.
    GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
    if (credential.createScopedRequired()) {
      List<String> scopes = new ArrayList<>();
      // Set Google Cloud Storage scope to Full Control.
      scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
      // Set Google Compute Engine scope to Read-write.
      scopes.add(ComputeScopes.COMPUTE);
      credential = credential.createScoped(scopes);
    }
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
    // Create Compute Engine object for listing instances.
    Compute compute =
        new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer)
            .setApplicationName(APPLICATION_NAME)
            .build();

    // List out instances, looking for the one created by this sample app.
    boolean foundOurInstance = printInstances(compute);

    Operation op;
    if (foundOurInstance) {
      op = deleteInstance(compute, SAMPLE_INSTANCE_NAME);
    } else {
      op = startInstance(compute, SAMPLE_INSTANCE_NAME);
    }

    // Call Compute Engine API operation and poll for operation completion status
    System.out.println("Waiting for operation completion...");
    Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS);
    if (error == null) {
      System.out.println("Success!");
    } else {
      System.out.println(error.toPrettyString());
    }
  } catch (IOException e) {
    System.err.println(e.getMessage());
  } catch (Throwable t) {
    t.printStackTrace();
  }
  System.exit(1);
}
 
Example 20
Source File: GoogleSpreadsheetWriter.java    From SPDS with Eclipse Public License 2.0 4 votes vote down vote up
private static Sheets getService() throws IOException, GeneralSecurityException {
	// Build a new authorized API client service.
	final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
	return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY,  getCredentials(HTTP_TRANSPORT))
			.setApplicationName(APPLICATION_NAME).build();
}