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:edu.umass.cs.ripples.paol.CalendarParser.java

License:Apache License

public static void main(String[] args) {
    try {/*from w w  w. j  av  a  2s.co m*/
        try {

            if (args.length != 2) {
                errPrintln("Usage: <program to run> <name of calendar>");
                System.exit(1);
            }

            // initialize the transport
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

            // authorization
            Credential credential = authorize();

            // set up global Calendar instance
            client = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                    credential).setApplicationName(APPLICATION_NAME).build();

            // get calendars
            Map<String, String> sumryToIdMap = initSumryToIdMap();
            String calKey = null;
            String captureProgram = args[0];
            String calendarName = args[1];
            if ((calKey = sumryToIdMap.get(calendarName)) == null) {
                println("Calendar '" + calendarName + "' was not found. Here are the available calendars:");
                for (String key : sumryToIdMap.keySet())
                    println(key);
                System.exit(1);
            }

            println("Calendar '" + calendarName + "' was found. Writing cron lines");
            println("Setting semester\n");
            if (!setSemester(SEM_DATES))
                errPrintln("Failed to set semester");
            Calendar calendar = client.calendars().get(calKey).execute();
            // create file and BufferedWriter
            File cronLines = new File(CRON_TEMP);
            if (cronLines.exists())
                cronLines.delete();
            cronLines.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(cronLines));
            writeEvents(captureProgram, calendar, writer);
            writer.close();
            System.exit(0);

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

From source file:fi.gapps.intra.thesis.controller.TaskQueueSample.java

License:Open Source License

public static void run() throws Exception {
    parseParams();//  ww w  .  j ava 2 s .  c  om
    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);
    }
    // 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:fr.acxio.tools.agia.google.GoogleDriveServiceImpl.java

License:Apache License

@Override
public void connect() throws GoogleException {
    try {//ww  w  . ja  v  a  2s  . co  m
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = authorize();
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                .build();

    } catch (IOException e) {
        throw new GoogleException(e);
    } catch (GeneralSecurityException e) {
        throw new GoogleException(e);
    }
}

From source file:fusiontables.FusionTablesSample.java

License:Apache License

public static void main(String[] args) {
    try {//w ww .  jav  a2  s  . co m
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
        // authorization
        Credential credential = authorize();
        // set up global FusionTables instance
        fusiontables = new Fusiontables.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
        // run commands

        listTables();
        String tableId = createTable();

        System.out.println("using table " + tableId);

        insertData(tableId);
        showRows(tableId);
        deleteTable(tableId);
        // success!
        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:gavisualizer.GoogleApiManager.java

private Analytics initializeAnalytics() throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY).setServiceAccountId(_serviceAccountEmail)
            .setServiceAccountPrivateKeyFromP12File(new File(_certificatePath))
            .setServiceAccountScopes(AnalyticsScopes.all()).build();

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
            .build();/*from   www  . j  a  va 2  s. co  m*/
}

From source file:gobblin.source.extractor.extract.google.GoogleCommon.java

License:Apache License

/**
 * Provides HttpTransport. If both proxyUrl and postStr is defined, it provides transport with Proxy.
 * @param proxyUrl Optional./*w  w w.j a  v  a 2 s  . com*/
 * @param portStr Optional. String type for port so that user can easily pass null. (e.g: state.getProp(key))
 * @return
 * @throws NumberFormatException
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static HttpTransport newTransport(String proxyUrl, String portStr)
        throws NumberFormatException, GeneralSecurityException, IOException {
    if (!StringUtils.isEmpty(proxyUrl) && !StringUtils.isEmpty(portStr)) {
        return new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore())
                .setProxy(
                        new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(portStr))))
                .build();
    }
    return GoogleNetHttpTransport.newTrustedTransport();
}

From source file:google.drive.example.v2.cmdline.DriveSample.java

License:Apache License

public static void main(String[] args) {
    Preconditions.checkArgument(/*from   w ww  .ja  va 2 s .com*/
            !UPLOAD_FILE_PATH.startsWith("Enter ") && !DIR_FOR_DOWNLOADS.startsWith("Enter "),
            "Please enter the upload file path and download directory in %s", DriveSample.class);

    try {
        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(false);

        View.header1("Updating Uploaded File Name");
        File updatedFile = updateFileWithTestSuffix(uploadedFile.getId());

        View.header1("Starting Resumable Media Download");
        downloadFile(false, updatedFile);

        View.header1("Starting Simple Media Upload");
        uploadedFile = uploadFile(true);

        View.header1("Starting Simple Media Download");
        downloadFile(true, uploadedFile);

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

From source file:googleApi.BookSearch.java

License:Apache License

public static java.util.List<Book> queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
    ClientCredentials.errorIfNotSpecified();

    if (jsonFactory == null || query.length() == 0)
        return null;
    // Set up Books client.
    final Books books = new Books.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, null)
            .setApplicationName(APPLICATION_NAME)
            .setGoogleClientRequestInitializer(new BooksRequestInitializer(ClientCredentials.API_KEY)).build();

    // Set query string and filter only Google eBooks.
    System.out.println("Query: [" + query + "]");
    List volumesList = books.volumes().list(query);
    volumesList.setFilter("ebooks");

    // Execute the query.
    Volumes volumes = volumesList.execute();
    if (volumes.getTotalItems() == 0 || volumes.getItems() == null) {
        System.out.println("No matches found.");
        return null;
    }/*from   w ww .  j av  a 2s .  c o m*/

    ArrayList bookList = new ArrayList();

    // Output results.
    for (Volume volume : volumes.getItems()) {

        int bookID;
        String title;
        String author = null;
        String ISBN10 = null;
        String ISBN13 = null;
        String genre = null;
        String edition = null;
        String publisher = null;
        String description = null;
        String imageLink = null;

        Volume.VolumeInfo volumeInfo = volume.getVolumeInfo();
        Volume.SaleInfo saleInfo = volume.getSaleInfo();
        System.out.println("==========");

        // Title.
        title = volumeInfo.getTitle();
        System.out.println("Title: " + title);
        if (volumeInfo.getIndustryIdentifiers() != null) {
            for (IndustryIdentifiers iden : volumeInfo.getIndustryIdentifiers()) {
                if (iden.getType().equals("ISBN_13")) {
                    ISBN13 = iden.getIdentifier();
                    System.out.println("ISBN13 : " + ISBN13);
                } else if (iden.getType().equals("ISBN_10")) {
                    ISBN10 = iden.getIdentifier();
                    System.out.println("ISBN10 : " + ISBN10);
                }
            }
        }

        System.out.println("Title: " + title);

        //authors
        java.util.List<String> authors = volumeInfo.getAuthors();
        if (authors != null && !authors.isEmpty()) {
            System.out.print("Author(s): ");
            for (int i = 0; i < authors.size(); ++i) {
                System.out.print(authors.get(i));
                if (i == 0) {
                    author = authors.get(i);
                } else if (i != 0 && i <= authors.size()) {
                    author = author + ", " + authors.get(i);
                }

                //author = authors.get(i) + ", " + author;
                if (i < authors.size() - 1) {
                    System.out.print(", ");
                    // author = author + ", " + authors.get(i);
                }
            }
            System.out.println();
        }

        // Description (if any).
        if (volumeInfo.getDescription() != null && volumeInfo.getDescription().length() > 0) {

            description = volumeInfo.getDescription();
            System.out.println("Description: " + description);
        }

        //publisher
        if (volumeInfo.getPublisher() != null) {
            publisher = volumeInfo.getPublisher();
        }

        //image link
        if (volumeInfo.getImageLinks() != null) {
            imageLink = volumeInfo.getImageLinks().getThumbnail();
        }

        if (volumeInfo.getCategories() != null) {
            int length = 0;
            length = volumeInfo.getCategories().toString().length();
            genre = volumeInfo.getCategories().toString().substring(1, length - 1);
        }

        Book googleBook;
        googleBook = new Book(title, author, ISBN10, ISBN13, genre, edition, publisher, description);
        googleBook.setImageLink(imageLink);
        boolean add = bookList.add(googleBook);
    }

    System.out.println("==========");
    System.out.println(volumes.getTotalItems() + " total results at http://books.google.com/ebooks?q="
            + URLEncoder.encode(query, "UTF-8"));
    return bookList;
}

From source file:GoogleAPI.DriveService.java

License:Apache License

public static Drive getDriveService() throws Exception {
    Drive drive;//from   w ww  .j  a v  a2  s .co m
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
    Credential credential = authorize();
    // // set up the global Drive instance
    drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
            .build();
    return drive;
}

From source file:guru.nidi.google.sheet.SimpleCredential.java

License:Apache License

public SimpleCredential(String serviceAccountEmail, File serviceAccountPrivateKeyFileP12)
        throws GeneralSecurityException, IOException {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    jsonFactory = JacksonFactory.getDefaultInstance();

    credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
            .setServiceAccountId(serviceAccountEmail)
            .setServiceAccountScopes(Arrays.asList(SCOPE_SHEET, SCOPE_DRIVE))
            .setServiceAccountPrivateKeyFromP12File(serviceAccountPrivateKeyFileP12).build();
}