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:api.BooksService.java

License:Open Source License

private static Volumes getVolumes(String query) {
    try {/* w  w w.ja v a  2s  . co  m*/
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        final Books books = new Books.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, null)
                .setApplicationName(APPLICATION_NAME).build();
        System.out.println("Query Google Books: [" + query + "]");
        List volumesList = books.volumes().list(query);
        Volumes volumes = volumesList.execute();
        if (volumes != null) {
            if (volumes.getTotalItems() == 0 || volumes.getItems() == null) {
                System.out.println("No matches found.");
                return null;
            }
            return volumes;
        }
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(BooksService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Verifique a conexo com a Internet.", "Livros Online",
                JOptionPane.WARNING_MESSAGE);
        Logger.getLogger(BooksService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:app.logica.gestores.GestorEmail.java

License:Open Source License

public GestorEmail() {
    final java.util.logging.Logger buggyLogger = java.util.logging.Logger
            .getLogger(FileDataStoreFactory.class.getName());
    buggyLogger.setLevel(java.util.logging.Level.SEVERE);

    try {//ww w . j a  va  2 s.c  o  m
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:bean.EnvioAnality.java

private static Analytics initializeAnalytics() throws Exception {

    String realPath = FacesContext.getCurrentInstance().getExternalContext()
            .getRealPath("/resources/libs/proyectoMuna-24eefc45ccfa.p12");

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountPrivateKeyFromP12File(new File(realPath))
            .setServiceAccountScopes(AnalyticsScopes.all()).build();

    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
            .build();/* w  ww  . j  a va 2 s  .  c o m*/
}

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 {/*from   ww  w  .j  ava 2 s .c  o m*/
        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  ww  .  j  ava 2s  .co  m
        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:br.usp.poli.lta.cereda.macro.util.GoogleDriveController.java

License:Open Source License

/**
 * Construtor./*from w w  w  .  ja v  a 2 s.  c o m*/
 */
private GoogleDriveController() {

    // originalmente, o servio  invlido
    service = null;

    // tenta obter a configurao do Google Drive a partir de um arquivo de
    // propriedades localizado no diretrio de usurio
    File config = new File(
            System.getProperty("user.home").concat(File.separator).concat("me-driveconfig.properties"));

    // se a configurao no existe, lanar exceo
    if (!config.exists()) {
        exception = new TextRetrievalException(
                "No encontrei o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio.");
    } else {

        // a configurao existe, carrega o mapa de chaves e valores e
        // faz a autenticao no Google Drive
        Properties properties = new Properties();
        try {

            // obtm o arquivo de propriedades e verifica se as chaves so
            // vlidas
            properties.load(new FileReader(config));
            if (properties.containsKey("id") && properties.containsKey("secret")) {

                // cria as chaves de acesso de acordo com as informaes
                // contidas no arquivo de propriedades
                GoogleClientSecrets secrets = new GoogleClientSecrets();
                GoogleClientSecrets.Details details = new GoogleClientSecrets.Details();
                details.setClientId(properties.getProperty("id"));
                details.setClientSecret(properties.getProperty("secret"));
                secrets.setInstalled(details);

                // cria um novo transporte HTTP e a factory do JSON para
                // parsing da API do Google Drive
                HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
                JsonFactory factory = JacksonFactory.getDefaultInstance();

                // define o diretrio do usurio como o local para
                // armazenamento das credenciais de autenticao do
                // Google Drive
                FileDataStoreFactory store = new FileDataStoreFactory(
                        new File(System.getProperty("user.home")));

                // cria um fluxo de autorizao do Google a partir de todas
                // as informaes coletadas anteriormente
                GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, factory,
                        secrets, Collections.singleton(DriveScopes.DRIVE_FILE)).setDataStoreFactory(store)
                                .build();

                // cria uma nova credencial a partir da autorizao
                Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                        .authorize("user");

                // cria efetivamente um novo servio do Google Drive
                // utilizando as informaes coletadas anteriormente
                service = new Drive.Builder(transport, factory, credential)
                        .setApplicationName("macro-expander/1.0").build();
            } else {
                // as chaves so invlidas, configura uma nova exceo
                exception = new TextRetrievalException(
                        "O arquivo de configurao do Google Drive ('me-driveconfig.properties') no possui as chaves 'id' e 'secret'.");
            }
        } catch (IOException ex) {
            // erro de leitura do arquivo de configurao
            exception = new TextRetrievalException(
                    "No consegui ler o arquivo de configurao do Google Drive ('me-driveconfig.properties') no diretrio do usurio.");
        } catch (GeneralSecurityException ex) {
            // erro de conexo
            exception = new TextRetrievalException("No foi possvel estabelecer uma conexo segura.");
        }
    }
}

From source file:calendariotaller.CalendarSample.java

License:Apache License

public static void main(String[] args) {
    try {//from ww w .  ja va2  s.  co m
        // initialize the transport
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // initialize the data store factory
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        // authorization
        Credential credential = authorize();

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

        // run commands
        showCalendars();
        addCalendarsUsingBatch();
        Calendar calendar = addCalendar();
        updateCalendar(calendar);
        addEvent(calendar);
        showEvents(calendar);
        deleteCalendarsUsingBatch();
        deleteCalendar(calendar);

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

From source file:calendar_cmdline_sample.CalendarSample.java

License:Apache License

public static void main(String[] args) {
    try {/*w  w w .j  a  va2  s. c om*/
        // initialize the transport
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // initialize the data store factory
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        // authorization
        Credential credential = authorize();

        // set up global Calendar instance
        client = new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName("KiK-Office").build();

        // run commands
        // showCalendars();

        String pageToken = null;
        DateTime now = new DateTime(System.currentTimeMillis());

        do {
            DateTime timeMax = new DateTime(LocalDateTime.now().plusMonths(1).toString());
            Events events = client.events().list("3h5je7hsq4ujjlm6upbjuu88j4@group.calendar.google.com")
                    .setTimeMax(timeMax).setPageToken(pageToken).setTimeMin(now).setOrderBy("startTime")
                    .setSingleEvents(true).execute();
            List<Event> items = events.getItems();
            for (Event event : items) {
                System.out.println(event.getSummary());
            }
            pageToken = events.getNextPageToken();
        } while (pageToken != null);

        /*
         * addCalendarsUsingBatch(); Calendar calendar = addCalendar();
         * updateCalendar(calendar); addEvent(calendar);
         * showEvents(calendar); deleteCalendarsUsingBatch();
         * deleteCalendar(calendar);
         */

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

From source file:cane.brothers.google.api.samples.spreadsheet.oauth2.SpreadsheetEntriesSample.java

License:Apache License

/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {

    // load client secrets
    clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(SpreadsheetEntriesSample.class.getResourceAsStream(CLIENT_SECRETS)));

    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "
                + "into client_secrets.json");
        System.exit(1);/*w  w w. j av  a2 s  .com*/
    }

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, SCOPES).setDataStoreFactory(dataStoreFactory).build();

    AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver());

    // authorize
    return app.authorize("user");
}

From source file:clientevideo.ClienteVideo.java

public static void main(String[] args) throws GeneralSecurityException, IOException, Exception {
    JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".dados");
    DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);

    // Build a new authorized API client service.
    Drive driveService = getDriveService();

    FileList result = driveService.files().list().execute();

    System.out.println(result);/* w  w  w  .j a va  2s  .c  o  m*/

    //        File arqTeste = new File();
    //        arqTeste.setName("TESTE");
    //        arqTeste.setMimeType("application/vnd.google-apps.drive-sdk");
    //        arqTeste.setDescription("Testano alguma coisa");
    //        // Print the names and IDs for up to 10 files.
    //        File arq = driveService.files().create(arqTeste).execute();
    //        System.out.println(arq);  

    File fileMetadata = new File();
    fileMetadata.setName("foto.jpg");
    java.io.File filePath = new java.io.File("/var/www/html/pessoal/drive/jules.jpg");
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    File file = driveService.files().create(fileMetadata, mediaContent).setFields("id").execute();

    //        driveService.files().delete(result.getFiles().get(0).getId()).execute();
}