List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential fromStream
@Beta public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport, JsonFactory jsonFactory) throws IOException
From source file:br.unb.cic.bionimbuz.controller.elasticitycontroller.GoogleAPI.java
@Override public void createinstance(String type, String instanceName) throws IOException { System.out.println("================== Setup =================="); try {// w w w .j av a2 s. c om httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Authenticate using Google Application Default Credentials. //GoogleCredential credential = GoogleCredential.getApplicationDefault(); GoogleCredential credential; //InputStream auth = new ByteArrayInputStream(authpath.getBytes(StandardCharsets.UTF_8)); InputStream is = null; is = new FileInputStream(SystemConstants.FILE_CREDENTIALS_GOOGLE); credential = GoogleCredential.fromStream(is, httpTransport, JSON_FACTORY); if (credential.createScopedRequired()) { List<String> scopes = new ArrayList(); // Set Google Clo ud 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); } // Create Compute Engine object for listing instances. Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); System.out.println("================== Starting New Instance =================="); // Create VM Instance object with the required properties. com.google.api.services.compute.model.Instance instance = new com.google.api.services.compute.model.Instance(); instance.setName(instanceName); instance.setMachineType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/" + ZONE_NAME + "/machineTypes/" + type); // Add Network Interface to be used by VM Instance. NetworkInterface ifc = new NetworkInterface(); ifc.setNetwork( "https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/global/networks/default"); List<AccessConfig> configs = new ArrayList(); AccessConfig config = new AccessConfig(); config.setType(NETWORK_INTERFACE_CONFIG); config.setName(NETWORK_ACCESS_CONFIG); configs.add(config); ifc.setAccessConfigs(configs); instance.setNetworkInterfaces(Collections.singletonList(ifc)); //get Internal ip, do a method that set it // Add attached Persistent Disk to be used by VM Instance. AttachedDisk disk = new AttachedDisk(); disk.setBoot(true); disk.setAutoDelete(true); disk.setType("PERSISTENT"); AttachedDiskInitializeParams params = new AttachedDiskInitializeParams(); // Assign the Persistent Disk the same name as the VM Instance. params.setDiskName(instanceName); // Specify the source operating system machine image to be used by the VM Instance. params.setSourceImage(SOURCE_IMAGE_PREFIX + SOURCE_IMAGE_PATH); // Specify the disk type as Standard Persistent Disk params.setDiskType("https://www.googleapis.com/compute/v1/projects/" + PROJECT_ID + "/zones/" + ZONE_NAME + "/diskTypes/pd-standard"); disk.setInitializeParams(params); instance.setDisks(Collections.singletonList(disk)); // Initialize the service account to be used by the VM Instance and set the API access scopes. ServiceAccount account = new ServiceAccount(); account.setEmail("default"); List<String> scopes = new ArrayList(); scopes.add("https://www.googleapis.com/auth/devstorage.full_control"); scopes.add("https://www.googleapis.com/auth/compute"); account.setScopes(scopes); instance.setServiceAccounts(Collections.singletonList(account)); // Optional - Add a startup script to be used by the VM Instance. Metadata meta = new Metadata(); Metadata.Items item = new Metadata.Items(); item.setKey("startup-script-url"); // If you put a script called "vm-startup.sh" in this Google Cloud Storage bucket, it will execute on VM startup. // This assumes you've created a bucket named the same as your PROJECT_ID // For info on creating buckets see: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets item.setValue("gs://" + PROJECT_ID + "/vm-startup.sh"); meta.setItems(Collections.singletonList(item)); instance.setMetadata(meta); System.out.println(instance.toPrettyString()); Compute.Instances.Insert insert = compute.instances().insert(PROJECT_ID, ZONE_NAME, instance); insert.execute(); try { Thread.sleep(15000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("OK"); String instanceCreatedName = instance.getName(); System.out.println(instanceCreatedName); Compute.Instances.Get get = compute.instances().get(PROJECT_ID, ZONE_NAME, instanceCreatedName); Instance instanceCreated = get.execute(); setIpInstance(instanceCreated.getNetworkInterfaces().get(0).getAccessConfigs().get(0).getNatIP()); } catch (GeneralSecurityException ex) { Logger.getLogger(GoogleAPI.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:br.unb.cic.bionimbuz.elasticity.legacy.FULLGoogleAPI.java
License:Apache License
public static void main(String[] args) { try {//from w w w . jav a 2 s .c om httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Authenticate using Google Application Default Credentials. //GoogleCredential credential = GoogleCredential.getApplicationDefault(); GoogleCredential credential; //InputStream auth = new ByteArrayInputStream(authpath.getBytes(StandardCharsets.UTF_8)); InputStream is = null; is = new FileInputStream(authpath); credential = GoogleCredential.fromStream(is, httpTransport, JSON_FACTORY); if (credential.createScopedRequired()) { List<String> scopes = new ArrayList(); // Set Google Clo ud 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); } // Create Compute Engine object for listing instances. Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, credential) .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); }
From source file:com.cloudera.director.google.internal.GoogleCredentials.java
License:Apache License
private Compute buildCompute() { try {/*from w w w.j a va2s . com*/ JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; if (jsonKey != null) { credential = GoogleCredential .fromStream(new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); } else { Collection COMPUTE_SCOPES = Collections.singletonList(ComputeScopes.COMPUTE); credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY) .createScoped(COMPUTE_SCOPES); } return new Compute.Builder(httpTransport, JSON_FACTORY, null) .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) .setHttpRequestInitializer(credential).build(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.cloudera.director.google.internal.GoogleCredentials.java
License:Apache License
private SQLAdmin buildSQLAdmin() { try {/*w ww. j a v a2 s .c o m*/ JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential; if (jsonKey != null) { credential = GoogleCredential .fromStream(new ByteArrayInputStream(jsonKey.getBytes()), httpTransport, JSON_FACTORY) .createScoped(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)); } else { Collection SQLSERVICE_ADMIN_SCOPES = Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN); credential = GoogleCredential.getApplicationDefault(httpTransport, JSON_FACTORY) .createScoped(SQLSERVICE_ADMIN_SCOPES); } return new SQLAdmin.Builder(httpTransport, JSON_FACTORY, null) .setApplicationName(Names.buildApplicationNameVersionTag(applicationProperties)) .setHttpRequestInitializer(credential).build(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.drextended.gppublisher.bamboo.util.AndroidPublisherHelper.java
License:Open Source License
/** * Performs all necessary setup steps for running requests against the API. * * @throws GeneralSecurityException//from w w w . j a va 2s . c o m * @throws IOException * @throws IllegalArgumentException */ public void init() throws IOException, GeneralSecurityException, IllegalArgumentException { mLogger.addBuildLogEntry("Initializing..."); Preconditions.checkArgument(!Strings.isNullOrEmpty(mApplicationName), "Application name cannot be null or empty!"); Preconditions.checkArgument(!Strings.isNullOrEmpty(mPackageName), "Package name cannot be null or empty!"); Preconditions.checkArgument(!Strings.isNullOrEmpty(mTrack), "Track cannot be null or empty!"); Preconditions.checkArgument(!Strings.isNullOrEmpty(mApkPath), "Apk/aab path cannot be null or empty!"); if (TRACK_ROLLOUT.equals(mTrack)) { try { mRolloutFraction = Double.parseDouble(mRolloutFractionString); } catch (NumberFormatException ex) { throw new IllegalArgumentException( "User fraction cannot be parsed as double: " + mRolloutFractionString); } if (mRolloutFraction < 0 || mRolloutFraction >= 1) { throw new IllegalArgumentException( "User fraction must be in range (0 <= fraction < 1): " + mRolloutFractionString); } } else if (TRACK_CUSTOM.equals(mTrack)) { Preconditions.checkArgument(!Strings.isNullOrEmpty(mTrackCustomNames), "Not specified names for custom tracks!"); mCustomTracks = mTrackCustomNames.split(",\\s*"); } String apkFullPath = relativeToFullPath(mApkPath); mApkFile = new File(apkFullPath); Preconditions.checkArgument(mApkFile.exists(), "Apk file not found in path: " + apkFullPath); if (!Strings.isNullOrEmpty(mDeobfuscationFilePath)) { String deobfuscationFullPath = relativeToFullPath(mDeobfuscationFilePath); mDeobfuscationFile = new File(deobfuscationFullPath); Preconditions.checkArgument(mDeobfuscationFile.exists(), "Mapping (deobfuscation) file not found in path: " + deobfuscationFullPath); } final InputStream jsonKeyInputStream; if (mFindJsonKeyInFile) { Preconditions.checkArgument(!Strings.isNullOrEmpty(mJsonKeyPath), "Secret json key path cannot be null or empty!"); String jsonKeyFullPath = relativeToFullPath(mJsonKeyPath); File jsonKeyFile = new File(jsonKeyFullPath); Preconditions.checkArgument(jsonKeyFile.exists(), "Secret json key file not found in path: " + jsonKeyFullPath); jsonKeyInputStream = new FileInputStream(jsonKeyFile); } else { Preconditions.checkArgument(!Strings.isNullOrEmpty(mJsonKeyContent), "Secret json key content cannot be null or empty!"); jsonKeyInputStream = IOUtils.toInputStream(mJsonKeyContent); } if (!Strings.isNullOrEmpty(mRecentChangesListings)) { String[] rcParts = mRecentChangesListings.trim().split("\\s*,\\s*"); mReleaseNotes = new ArrayList<LocalizedText>(rcParts.length); for (String rcPart : rcParts) { String[] rcPieces = rcPart.split("\\s*::\\s*"); Preconditions.checkArgument(rcPieces.length == 2, "Wrong recent changes entry: " + rcPart); String languageCode = rcPieces[0]; String recentChangesFilePath = relativeToFullPath(rcPieces[1]); Preconditions.checkArgument( !Strings.isNullOrEmpty(languageCode) && !Strings.isNullOrEmpty(recentChangesFilePath), "Wrong recent changes entry: " + rcPart + ", lang = " + languageCode + ", path = " + recentChangesFilePath); File rcFile = new File(recentChangesFilePath); Preconditions.checkArgument(rcFile.exists(), "Recent changes file for language \"" + languageCode + "\" not found in path: " + recentChangesFilePath); FileInputStream inputStream = new FileInputStream(rcFile); String recentChanges = null; try { recentChanges = IOUtils.toString(inputStream); } finally { inputStream.close(); } mReleaseNotes.add(new LocalizedText().setLanguage(languageCode).setText(recentChanges)); } } mLogger.addBuildLogEntry("Initialized successfully!"); mLogger.addBuildLogEntry("Creating AndroidPublisher Api Service..."); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); Credential credential = GoogleCredential.fromStream(jsonKeyInputStream, httpTransport, jsonFactory) .createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER)); mAndroidPublisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, new RequestInitializer(credential)).setApplicationName(mApplicationName).build(); mLogger.addBuildLogEntry("AndroidPublisher Api Service created!"); }
From source file:com.google.cloud.hadoop.util.CredentialFactory.java
License:Open Source License
/*** * Get credentials listed in a JSON file. * @param serviceAccountJsonKeyFile A file path pointing to a JSON file containing credentials. * @param scopes The OAuth scopes that the credential should be valid for. *//* w w w .j a va2 s. c om*/ public Credential getCredentialFromJsonKeyFile(String serviceAccountJsonKeyFile, List<String> scopes) throws IOException, GeneralSecurityException { LOG.debug("getCredentialFromJsonKeyFile({}, {})", serviceAccountJsonKeyFile, scopes); try (FileInputStream fis = new FileInputStream(serviceAccountJsonKeyFile)) { return GoogleCredentialWithRetry.fromGoogleCredential( GoogleCredential.fromStream(fis, getHttpTransport(), JSON_FACTORY).createScoped(scopes)); } }
From source file:com.netflix.spinnaker.clouddriver.artifacts.gcs.GcsArtifactCredentials.java
License:Apache License
public GcsArtifactCredentials(String applicationName, GcsArtifactAccount account) throws IOException, GeneralSecurityException { HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); String credentialsPath = account.getJsonPath(); GoogleCredential credential;/*from w w w .j a v a 2s . co m*/ if (!StringUtils.isEmpty(credentialsPath)) { FileInputStream stream = new FileInputStream(credentialsPath); credential = GoogleCredential.fromStream(stream, transport, jsonFactory) .createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_READ_ONLY)); log.info("Loaded credentials from {}", credentialsPath); } else { log.info( "artifacts.gcs.enabled without artifacts.gcs.[].jsonPath. Using default application credentials."); credential = GoogleCredential.getApplicationDefault(); } name = account.getName(); storage = new Storage.Builder(transport, jsonFactory, credential).setApplicationName(applicationName) .build(); }
From source file:com.netflix.spinnaker.clouddriver.google.security.GoogleNamedAccountCredentials.java
License:Apache License
private GoogleCredentials buildCredentials() { JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = buildHttpTransport(); try {//from w ww . j a v a 2s. co m if (jsonKey != null) { try (InputStream credentialStream = new ByteArrayInputStream(jsonKey.getBytes("UTF-8"))) { // JSON key was specified in matching config on key server. GoogleCredential credential = GoogleCredential .fromStream(credentialStream, httpTransport, jsonFactory) .createScoped(Collections.singleton(ComputeScopes.COMPUTE)); Compute compute = new Compute.Builder(httpTransport, jsonFactory, null) .setApplicationName(applicationName) .setHttpRequestInitializer(setHttpTimeout(credential)) .setServicePath(alphaListed ? COMPUTE_ALPHA_SERVICE_PATH : COMPUTE_SERVICE_PATH) .build(); return new GoogleCredentials(projectName, compute, alphaListed, imageProjects, requiredGroupMembership, accountName); } } else { // No JSON key was specified in matching config on key server, so use application default credentials. GoogleCredential credential = GoogleCredential.getApplicationDefault(); Compute compute = new Compute.Builder(httpTransport, jsonFactory, credential) .setApplicationName(applicationName).build(); return new GoogleCredentials(projectName, compute, alphaListed, imageProjects, requiredGroupMembership, accountName); } } catch (IOException ioe) { throw new RuntimeException("failed to create credentials", ioe); } }
From source file:com.netflix.spinnaker.front50.model.GcsStorageService.java
License:Apache License
private GoogleCredential loadCredential(HttpTransport transport, JsonFactory factory, String jsonPath) throws IOException { GoogleCredential credential;//from w ww .j a v a 2 s . c om if (!jsonPath.isEmpty()) { FileInputStream stream = new FileInputStream(jsonPath); credential = GoogleCredential.fromStream(stream, transport, factory) .createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)); log.info("Loaded credentials from from " + jsonPath); } else { log.info("spinnaker.gcs.enabled without spinnaker.gcs.jsonPath. " + "Using default application credentials. Using default credentials."); credential = GoogleCredential.getApplicationDefault(); } return credential; }
From source file:com.netflix.spinnaker.halyard.backup.kms.v1.google.GoogleKms.java
License:Apache License
private static GoogleCredential loadKmsCredential(HttpTransport transport, JsonFactory factory, String jsonPath) throws IOException { GoogleCredential credential;/* ww w .ja v a 2 s .c o m*/ if (!jsonPath.isEmpty()) { FileInputStream stream = new FileInputStream(jsonPath); credential = GoogleCredential.fromStream(stream, transport, factory); log.info("Loaded kms credentials from " + jsonPath); } else { log.info("Using kms default application credentials."); credential = GoogleCredential.getApplicationDefault(); } if (credential.createScopedRequired()) { credential = credential.createScoped(CloudKMSScopes.all()); } return credential; }