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:com.dotosoft.dotoquiz.tools.thirdparty.GoogleOAuth.java

License:Apache License

public static Credential authenticate(Settings setting) throws Exception {
    log.info("Preparing to authenticate via OAuth...");

    if (dataStoreFile == null) {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFile = new java.io.File(setting.getApi().getDataStoreDir());
        dataStoreFactory = new FileDataStoreFactory(dataStoreFile);
    }/*ww  w.j av a  2  s.  co  m*/

    Credential cred = null;
    String refreshToken = setting.getApi().getRefreshToken();
    if (refreshToken != null) {
        // We have a refresh token - so get some refreshed credentials
        cred = getRefreshedCredentials(refreshToken, setting);
    }

    if (cred == null) {

        // Either there was no valid refresh token, or the credentials could not
        // be created (they may have been revoked). So run the auth flow
        log.info("No credentials - beginning OAuth flow...");

        //            state.setStatus( "Requesting Google Authentication...");

        if (setting.getApi().getClientSecret().getClientId().startsWith("Enter")
                || setting.getApi().getClientSecret().getClientSecret().startsWith("Enter ")) {
            System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ "
                    + "into oauth2-cmdline-sample/src/main/resources/client_secrets.json");
            System.exit(1);
        }

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

        if (setting.getApi().isAllowInteractive()) {
            //             String redirectUrl = clientSecrets.getDetails().getRedirectUris().get(0);
            //             String authorizationUrl = flow.newAuthorizationUrl()
            //                        .setRedirectUri(redirectUrl)
            //                        .setAccessType("offline")
            //                        .setApprovalPrompt("force")
            //                        .build();
            //
            //             // Display the interactive GUI for the user to log in via the browser
            //             String code = initAndShowGUI( authorizationUrl, state );
            //         
            //             log.info("Token received from UI. Requesting credentials...");
            //         
            //             // Now we have the code from the interactive login, set up the
            //             // credentials request and call it.
            //             GoogleTokenResponse response = flow.newTokenRequest(code)
            //                .setRedirectUri(redirectUrl).execute();
            //         
            //             // Retrieve the credential from the request response
            //             cred = new GoogleCredential.Builder().setTransport(httpTransport)
            //                .setJsonFactory(JSON_FACTORY).setClientSecrets(clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret())
            //                .build().setFromTokenResponse(response);

        } else {
            // Retrieve the credential from the request response
            LocalServerReceiver receiver = new LocalServerReceiver.Builder()
                    .setHost(setting.getApi().getAuthenticationServer().getIp())
                    .setPort(setting.getApi().getAuthenticationServer().getPort()).build();
            cred = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
        }

        //          state.setStatus( "Google Authentication succeeded.");
        log.info("Credentials received - storing refresh token...");

        // Squirrel this away for next time
        setting.getApi().setRefreshToken(cred.getRefreshToken());
        setting.saveSettings();
    }

    return cred;
}

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/* ww w. j a v a2s . 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.dtolabs.rundeck.plugin.resources.gcp.InstanceToNodeMapper.java

License:Apache License

/**
 * Perform the query and return the set of instances
 *
 *//*from  w ww. j a va  2 s .  c  o m*/
public INodeSet performQuery() {
    final NodeSetImpl nodeSet = new NodeSetImpl();
    logger.error("Google Crendential performQuery(), this is credential " + credential);
    //if(null!=credential) {
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        compute = new Compute.Builder(httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
                .setHttpRequestInitializer(credential).build();

        final Set<Instance> instances = query(compute, projectId);

        logger.error("Google Crendential query() completed");

        mapInstances(nodeSet, instances);
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    logger.error("Google Crendential perfomquery() completed");
    //final ArrayList<Filter> filters = buildFilters();
    //final Set<Instance> instances = query(ec2, new DescribeInstancesRequest().withFilters(filters));
    return nodeSet;
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Create a registry for Cloud IoT. */
public static void createRegistry(String cloudRegion, String projectId, String registryName,
        String pubsubTopicPath) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
    final String fullPubsubPath = "projects/" + projectId + "/topics/" + pubsubTopicPath;

    DeviceRegistry registry = new DeviceRegistry();
    EventNotificationConfig notificationConfig = new EventNotificationConfig();
    notificationConfig.setPubsubTopicName(fullPubsubPath);
    List<EventNotificationConfig> notificationConfigs = new ArrayList<EventNotificationConfig>();
    notificationConfigs.add(notificationConfig);
    registry.setEventNotificationConfigs(notificationConfigs);
    registry.setId(registryName);//  w  ww.  j a  v a  2  s . c o m

    DeviceRegistry reg = service.projects().locations().registries().create(projectPath, registry).execute();
    System.out.println("Created registry: " + reg.getName());
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Delete this registry from Cloud IoT. */
public static void deleteRegistry(String cloudRegion, String projectId, String registryName)
        throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    String projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
    String registryPath = projectPath + "/registries/" + registryName;

    System.out.println("Deleting: " + registryPath);
    service.projects().locations().registries().delete(registryPath).execute();
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Print all of the devices in this registry to standard out. */
public static void listDevices(String projectId, String cloudRegion, String registryName)
        throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/" + registryName;

    List<Device> devices = service.projects().locations().registries().devices().list(registryPath).execute()
            .getDevices();/*from  w ww. j  a  va2  s  . com*/

    if (devices != null) {
        System.out.println("Found " + devices.size() + " devices");
        for (Device d : devices) {
            System.out.println("Id: " + d.getId());
            if (d.getConfig() != null) {
                // Note that this will show the device config in Base64 encoded format.
                System.out.println("Config: " + d.getConfig().toPrettyString());
            }
            System.out.println();
        }
    } else {
        System.out.println("Registry has no devices.");
    }
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Create a device that is authenticated using ES256. */
public static void createDeviceWithEs256(String deviceId, String publicKeyFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/* w ww  .j  a  v a  2 s.c om*/

    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    final String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("ES256_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    System.out.println("Creating device with id: " + deviceId);
    Device device = new Device();
    device.setId(deviceId);
    device.setCredentials(Arrays.asList(devCredential));

    Device createdDevice = service.projects().locations().registries().devices().create(registryPath, device)
            .execute();

    System.out.println("Created device: " + createdDevice.toPrettyString());
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Create a device that is authenticated using RS256. */
public static void createDeviceWithRs256(String deviceId, String certificateFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/*from ww w  .  j a  v  a  2 s . c om*/

    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(certificateFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("RSA_X509_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    System.out.println("Creating device with id: " + deviceId);
    Device device = new Device();
    device.setId(deviceId);
    device.setCredentials(Arrays.asList(devCredential));
    Device createdDevice = service.projects().locations().registries().devices().create(registryPath, device)
            .execute();

    System.out.println("Created device: " + createdDevice.toPrettyString());
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/**
 * Create a device that has no credentials.
 *
 * <p>This is a valid way to construct a device, however until it is patched with a credential the
 * device will not be able to connect to Cloud IoT.
 *//* ww  w.  j av  a2 s . c o m*/
public static void createDeviceWithNoAuth(String deviceId, String projectId, String cloudRegion,
        String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;

    System.out.println("Creating device with id: " + deviceId);
    Device device = new Device();
    device.setId(deviceId);
    device.setCredentials(new ArrayList<DeviceCredential>());
    Device createdDevice = service.projects().locations().registries().devices().create(registryPath, device)
            .execute();

    System.out.println("Created device: " + createdDevice.toPrettyString());
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

License:Apache License

/** Delete the given device from the registry. */
public static void deleteDevice(String deviceId, String projectId, String cloudRegion, String registryName)
        throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;// w  ww.  ja va2s. co m

    final String devicePath = registryPath + "/devices/" + deviceId;
    System.out.println("Deleting device " + devicePath);
    service.projects().locations().registries().devices().delete(devicePath).execute();
}