List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential getApplicationDefault
@Beta public static GoogleCredential getApplicationDefault() throws IOException
From source file:ComputeEngineSample.java
License:Open Source License
public static void main(String[] args) { try {//ww w . j ava2 s . c o m httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Authenticate using Google Application Default Credentials. GoogleCredential credential = GoogleCredential.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); } // 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:ListResources.java
License:Open Source License
/** * Builds and returns a CloudMonitoring service object authorized with the * application default credentials./* w ww.ja va2s . com*/ * * @return CloudMonitoring service object that is ready to make requests. * @throws GeneralSecurityException if authentication fails. * @throws IOException if authentication fails. */ static Monitoring authenticate() throws GeneralSecurityException, IOException { // Grab the Application Default Credentials from the environment. GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(MonitoringScopes.all()); // Create and return the CloudMonitoring service object HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); Monitoring service = new Monitoring.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Monitoring Sample").build(); return service; }
From source file:CloudMonitoringAuthSample.java
License:Apache License
/** * Builds and returns a CloudMonitoring service object authorized with the * application default credentials.//from w w w . j a v a 2 s . c o m * * @return CloudMonitoring service object that is ready to make requests. * @throws GeneralSecurityException if authentication fails. * @throws IOException if authentication fails. */ private static CloudMonitoring authenticate() throws GeneralSecurityException, IOException { // Grab the Application Default Credentials from the environment. GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(CloudMonitoringScopes.all()); // Create and return the CloudMonitoring service object HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); CloudMonitoring service = new CloudMonitoring.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Demo").build(); return service; }
From source file:OnlinePredictionSample.java
License:Apache License
public static void main(String[] args) throws Exception { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); Discovery discovery = new Discovery.Builder(httpTransport, jsonFactory, null).build(); RestDescription api = discovery.apis().getRest("ml", "v1").execute(); RestMethod method = api.getResources().get("projects").getMethods().get("predict"); JsonSchema param = new JsonSchema(); String projectId = "YOUR_PROJECT_ID"; // You should have already deployed a model and a version. // For reference, see https://cloud.google.com/ml-engine/docs/how-tos/deploying-models. String modelId = "YOUR_MODEL_ID"; String versionId = "YOUR_VERSION_ID"; param.set("name", String.format("projects/%s/models/%s/versions/%s", projectId, modelId, versionId)); GenericUrl url = new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true)); System.out.println(url);//from w ww . jav a 2s . c o m String contentType = "application/json"; File requestBodyFile = new File("input.txt"); HttpContent content = new FileContent(contentType, requestBodyFile); System.out.println(content.getLength()); GoogleCredential credential = GoogleCredential.getApplicationDefault(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content); String response = request.execute().parseAsString(); System.out.println(response); }
From source file:StorageSample.java
License:Apache License
/** * Fetches the listing of the given bucket. * * @param bucketName the name of the bucket to list. * * @return the raw XML containing the listing of the bucket. * @throws IOException if there's an error communicating with Cloud Storage. * @throws GeneralSecurityException for errors creating https connection. *//*from w ww . ja v a 2 s.c o m*/ public static String listBucket(final String bucketName) throws IOException, GeneralSecurityException { //[START snippet] // Build an account credential. GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(Collections.singleton(STORAGE_SCOPE)); // Set up and execute a Google Cloud Storage request. String uri = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8"); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); GenericUrl url = new GenericUrl(uri); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); //[END snippet] return content; }
From source file:TaskQueueSample.java
License:Open Source License
private static void run() throws Exception { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // [START auth_and_intitalize_client] // Authenticate using Google Application Default Credentials. GoogleCredential credential = GoogleCredential.getApplicationDefault(); if (credential.createScopedRequired()) { List<String> scopes = new ArrayList<>(); // Set TaskQueue Scopes scopes.add(TaskqueueScopes.TASKQUEUE); scopes.add(TaskqueueScopes.TASKQUEUE_CONSUMER); credential = credential.createScoped(scopes); }// w w w . ja v a2 s . c om // Intialize Taskqueue object. Taskqueue taskQueue = new Taskqueue.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); // [END auth_and_intitalize_client] /* Get the task queue using the name of an existing task queue * listed in the App Engine Task Queue section of the Developers console. * See the following sample for an example App Engine app that creates a * pull task queue: * https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/appengine/taskqueue */ com.google.api.services.taskqueue.model.TaskQueue queue = getQueue(taskQueue); System.out.println("================== Listing Task Queue details =================="); System.out.println(queue); // Lease, process and delete tasks // [START lease_tasks] Tasks tasks = getLeasedTasks(taskQueue); if (tasks.getItems() == null || tasks.getItems().size() == 0) { System.out.println("No tasks to lease, so now exiting"); } else { for (Task leasedTask : tasks.getItems()) { processTask(leasedTask); deleteTask(taskQueue, leasedTask); } } // [END lease_tasks] }
From source file:cloud.google.com.windows.example.ExampleCode.java
License:Open Source License
public void resetPassword() throws Exception { // Get credentials to setup a connection with the Compute API. Credential cred = GoogleCredential.getApplicationDefault(); // Create an instance of the Compute API. Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, null) .setApplicationName(APPLICATION_NAME).setHttpRequestInitializer(cred).build(); // Get the instance object to gain access to the instance's metadata. Instance inst = compute.instances().get(PROJECT_NAME, ZONE_NAME, INSTANCE_NAME).execute(); Metadata metadata = inst.getMetadata(); // Generate the public/private key pair for encryption and decryption. KeyPair keys = generateKeys(); // Update metadata from instance with new windows-keys entry. replaceMetadata(metadata, buildKeyMetadata(keys)); // Tell Compute Engine to update the instance metadata with our changes. compute.instances().setMetadata(PROJECT_NAME, ZONE_NAME, INSTANCE_NAME, metadata).execute(); System.out.println("Updating metadata..."); // Sleep while waiting for metadata to propagate - production code may // want to monitor the status of the metadata update operation. Thread.sleep(30000);/* ww w . j ava 2s .c om*/ System.out.println("Getting serial output..."); // Request the output from serial port 4. // In production code, this operation should be polled. SerialPortOutput output = compute.instances().getSerialPortOutput(PROJECT_NAME, ZONE_NAME, INSTANCE_NAME) .setPort(4).execute(); // Get the last line - this will be a JSON string corresponding to the // most recent password reset attempt. String[] entries = output.getContents().split("\n"); String outputEntry = entries[entries.length - 1]; // Parse output using the json-simple library. JSONParser parser = new JSONParser(); JSONObject passwordDict = (JSONObject) parser.parse(outputEntry); String encryptedPassword = passwordDict.get("encryptedPassword").toString(); // Output user name and decrypted password. System.out.println("\nUser name: " + passwordDict.get("userName").toString()); System.out.println("Password: " + decryptPassword(encryptedPassword, keys)); }
From source file:com.appengine.pubsub.HelloAppEngine.java
License:Open Source License
public void initialize() throws Exception { System.out.println("Initialize the Google APIs Client Library client"); log.info("Initialize the Google APIs Client Library client with logger"); // build the transport NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // get the credentials List<String> scopeList = Arrays.asList(ALL_SCOPES); GoogleCredential credential = GoogleCredential.getApplicationDefault(); if (credential.createScopedRequired()) { credential = credential.createScoped(scopeList); }/*from ww w. j av a 2 s . c om*/ // create the client stub this.client = new Pubsub.Builder(httpTransport, jsonFactory, credential) .setApplicationName(APPLICATION_NAME).build(); }
From source file:com.blackberry.bdp.klogger.LogReader.java
License:Apache License
@Override public void run() { UTF8Validator utf8Validator = null; GoogleCredential credential = null;/*from w w w. j av a2 s . co m*/ // Use credentials from file if available try { credential = GoogleCredential.fromStream(new FileInputStream("credentials.json")) .createScoped(PubsubScopes.all()); } catch (IOException e) { try { credential = GoogleCredential.getApplicationDefault().createScoped(PubsubScopes.all()); } catch (Exception e1) { } } final Pubsub client = new Pubsub.Builder(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(), credential).setApplicationName("vstoyak-kloger-test").build(); if (validateUTF8) { utf8Validator = new UTF8Validator(); } // Calculate send buffer size. If we're validating UTF-8, then theoretically, each byte could be // replaced by the three byte replacement character. So the send buffer needs to be triple // the max line length. If we're encoding the timestamp, then that adds 10 bytes. byte[] sendBytes; { int sendBufferSize = maxLine; if (validateUTF8) { sendBufferSize *= 3; } if (encodeTimestamp) { sendBufferSize += 10; } sendBytes = new byte[sendBufferSize]; } ByteBuffer sendBuffer = ByteBuffer.wrap(sendBytes); try { prepareSource(); while (!finished) { bytesRead = readSource(); if (bytesRead > 0) { LOG.trace("Read {} bytes", bytesRead); } else { if (bytesRead == 0) { // File's return 0 when they have reached the end of the FileChannel continue; } else { if (bytesRead == -1) { LOG.warn("Received -1 while reading from source, finishing up..."); finished = true; continue; } } } mBytesReceived.mark(bytesRead); mBytesReceivedTotal.mark(bytesRead); limit = start + bytesRead; start = 0; while (true) { newline = -1; for (int i = start; i < limit; i++) { if (bytes[i] == '\n') { totalLinesRead++; newline = i; break; } } LOG.trace("Newline at {}", newline); if (newline >= 0) { mLinesReceived.mark(); mLinesReceivedTotal.mark(); LOG.trace("Sending (pos {}, len {}):{}", start, newline - start, new String(bytes, start, newline - start, "UTF-8")); sendBuffer.clear(); if (encodeTimestamp) { sendBuffer.put(new byte[] { (byte) 0xFE, 0x00 }); sendBuffer.putLong(System.currentTimeMillis()); } if (validateUTF8) { utf8Validator.validate(bytes, start, newline - start); sendBuffer.put(utf8Validator.getResultBytes(), 0, utf8Validator.getResultBuffer().limit()); } else { sendBuffer.put(bytes, start, newline - start); } String message = "test Message 1"; if (!"".equals(message)) { String fullTopicName = String.format("projects/%s/topics/%s", "bbm-staging", "vstoyak-kloger-test"); PubsubMessage pubsubMessage = new PubsubMessage(); //pubsubMessage.encodeData(message.getBytes("UTF-8")); pubsubMessage.encodeData(sendBytes); PublishRequest publishRequest = new PublishRequest(); publishRequest.setMessages(ImmutableList.of(pubsubMessage)); try { client.projects().topics().publish(fullTopicName, publishRequest).execute(); } catch (Exception e) { LOG.info("PubSub exception", e); } } //producer.send(sendBytes, 0, sendBuffer.position()); start = newline + 1; continue; } else { LOG.trace("No newline. start={}, limit={}", start, limit); // if the buffer is full, send it all. Otherwise, do nothing. if (start == 0 && limit == maxLine) { mLinesReceived.mark(); mLinesReceivedTotal.mark(); LOG.trace("Sending log with no new-line:{}", new String(bytes, 0, maxLine, "UTF-8")); sendBuffer.clear(); if (encodeTimestamp) { sendBuffer.put(new byte[] { (byte) 0xFE, 0x00 }); sendBuffer.putLong(System.currentTimeMillis()); } if (validateUTF8) { utf8Validator.validate(bytes, 0, maxLine); sendBuffer.put(utf8Validator.getResultBytes(), 0, utf8Validator.getResultBuffer().limit()); } else { sendBuffer.put(bytes, 0, maxLine); } String message = "test Message 2"; if (!"".equals(message)) { String fullTopicName = String.format("projects/%s/topics/%s", "bbm-staging", "vstoyak-kloger-test"); PubsubMessage pubsubMessage = new PubsubMessage(); //pubsubMessage.encodeData(message.getBytes("UTF-8")); pubsubMessage.encodeData(sendBytes); PublishRequest publishRequest = new PublishRequest(); publishRequest.setMessages(ImmutableList.of(pubsubMessage)); try { client.projects().topics().publish(fullTopicName, publishRequest).execute(); } catch (Exception e) { LOG.info("PubSub exception", e); } } //producer.send(sendBytes, 0, sendBuffer.position()); start = 0; break; } // if there is still data, then shift it to the start else { if (start > 0 && start < limit) { int toMove = limit - start; int moveSize; int done = 0; while (done < toMove) { moveSize = Math.min(start - done, limit - start); System.arraycopy(bytes, start, bytes, done, moveSize); done += moveSize; start += moveSize; } start = toMove; break; } else { if (start >= limit) { LOG.trace("All the data has been read"); start = 0; break; } else { // start == 0, so move it to the limit for the next pass. start = limit; break; } } } } } } } catch (Throwable t) { LOG.error("An error has occured: {}", t); } finally { finished(); } LOG.info("Reading source for topic {} is finished", conf.getTopicName()); }
From source file:com.codeu.team34.label.LabelApp.java
License:Open Source License
/** * Connects to the Vision API using Application Default Credentials. *///from ww w . ja va 2 s. c om public static Vision getVisionService() throws IOException, GeneralSecurityException { GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all()); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential) .setApplicationName(APPLICATION_NAME).build(); }