Example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport.

Prototype

public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException 

Source Link

Document

Returns a new instance of NetHttpTransport that uses GoogleUtils#getCertificateTrustStore() for the trusted certificates using com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore) .

Usage

From source file:ComputeEngineSample.java

License:Open Source License

public static void main(String[] args) {
    try {// w  w w.  j  a  v  a2 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:StorageFactory.java

License:Open Source License

private static Storage buildService() throws IOException, GeneralSecurityException {
    HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    // 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);
    }/* ww w . j a v a2 s  .co m*/

    return new Storage.Builder(transport, jsonFactory, credential).setApplicationName("GCS Samples").build();
}

From source file:GoogleDriveAPI.java

License:Apache License

private static void setup(String email) {
    if (currentEmail != email) {
        currentEmail = email;/*from   w w w .  j  a  va  2  s  . c  o m*/
        try {
            /** Directory to store user credentials. */
            java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/" + email);
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
            // authorization
            Credential credential = authorize();
            // set up the global Drive instance
            drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
                    .setApplicationName(APPLICATION_NAME).build();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

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  w w .j a va2 s  .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:DriveSample.java

License:Apache License

public static void main(String UPLOAD_FILE_PATH, String ContentType) {
    Preconditions.checkArgument(!UPLOAD_FILE_PATH.startsWith("Enter "),
            "Please enter the upload file path and download directory in %s", DriveSample.class);

    try {//from  w w w .jav a2s .com
        java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        // authorization
        Credential credential = authorize();
        // set up the global Drive instance
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();

        // run commands

        View.header1("Starting Resumable Media Upload");
        File uploadedFile = uploadFile(true, UPLOAD_FILE, ContentType);

        /*      View.header1("Starting Simple Media Upload");
              uploadedFile = uploadFile(true, UPLOAD_FILE, ContentType);*/

        View.header1("Success!");
        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

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 ww w.j  a v a  2  s  .c  om*/
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:StorageSample2.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
    Set<String> scopes = new HashSet<String>();
    scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
    scopes.add(StorageScopes.DEVSTORAGE_READ_ONLY);
    scopes.add(StorageScopes.DEVSTORAGE_READ_WRITE);
    // Campo Email address criado no console.
    String accountId = Constants.ACCOUNT_ID;
    // Arquivo p12 baixado no console no momento de criar a chave.
    File p12File = new File(Constants.P12_FILE);
    // Autoriza a aplicao
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY).setServiceAccountId(accountId)
            .setServiceAccountPrivateKeyFromP12File(p12File).setServiceAccountScopes(scopes).build();
    return credential;

}

From source file:StorageSample2.java

License:Apache License

public static void main(String[] args) {
    try {//from   w ww . j av  a2  s.  c  o  m
        // Initialize the transport.
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // Authorization.
        Credential credential = authorize();

        // Set up global Storage instance.
        client = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        // Get metadata about the specified bucket.
        Storage.Buckets.Get getBucket = client.buckets().get(BUCKET_NAME);
        getBucket.setProjection("full");
        Bucket bucket = getBucket.execute();
        System.out.println("name: " + BUCKET_NAME);
        System.out.println("location: " + bucket.getLocation());
        System.out.println("timeCreated: " + bucket.getTimeCreated());
        System.out.println("owner: " + bucket.getOwner());

        // List the contents of the bucket.
        Storage.Objects.List listObjects = client.objects().list(BUCKET_NAME);
        com.google.api.services.storage.model.Objects objects;
        do {
            objects = listObjects.execute();
            List<StorageObject> items = objects.getItems();
            if (null == items) {
                System.out
                        .println("There were no objects in the given bucket; try adding some and re-running.");
                break;
            }
            for (StorageObject object : items) {
                System.out.println(object.getName() + " (" + object.getSize() + " bytes)");
            }
            listObjects.setPageToken(objects.getNextPageToken());
        } while (null != objects.getNextPageToken());

    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

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);
    }/*from ww  w  .j a va 2  s.  c  o  m*/
    // 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:PlusSample.java

License:Apache License

public static void main(String[] args) {
    try {/* www  .  j a v  a  2s .co  m*/
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        Credential credential = authorize();
        plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();
        getProfile();
        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}