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:org.kie.google.YouTubeClient.java

License:Apache License

YouTube youTube() throws GeneralSecurityException, IOException {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    return new YouTube.Builder(httpTransport, jsonFactory, credential(httpTransport, jsonFactory))
            .setApplicationName(GooglePlusProperties.APPLICATION_NAME).build();
}

From source file:org.mule.modules.google.bigquery.GoogleBigQueryConnector.java

License:Open Source License

/**
 * //from   w ww.ja v a 2  s .co m
 * @param applicationName
 * @param serviceAccount
 * @param scope
 * @param privateKeyP12File
 * 
 * Initiate connection
 */
@SuppressWarnings("unchecked")
@Connect
public void connect(@ConnectionKey String applicationName, @Password String serviceAccount,
        String privateKeyP12File, @Password String storePass, String alias, @Password String keyPass)
        throws ConnectionException {

    logger.info(String.format("Logging into Google BigQuery application %s.", applicationName));
    this.applicationName = applicationName;

    try {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(privateKeyP12File);
        PrivateKey key = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), in,
                storePass, alias, keyPass);
        logger.trace("Key size: " + key.getEncoded().length);
        logger.trace("Key algorithm: " + key.getAlgorithm());

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(serviceAccount).setServiceAccountScopes(SCOPES)
                .setServiceAccountPrivateKey(key).build();

        refreshBigQueryClient();

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage());
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN, null, ex.getMessage(), ex);
    }

}

From source file:org.myLazyClock.calendarApi.CalendarGoogleStrategy.java

License:Open Source License

/**
 * Find the first event before 24h before endDay in google calendar in params
 * @param params Need some params : <br/>
 *  - <strong> tokenRequest </strong> content the google refreshToken of user <br/>
 *  - <strong> gCalId </strong> content the id of calendar <br/>
 *  - <strong> apiId </strong> and <strong> apiSecret </strong> generate by maven in services.ConstantAPI <br/>
 *
 * @param beginDate Lower bound date in which search event
 * @param endDate Upper bound date in which search event
 *
 * @return CalendarEvent the first event find
 * @throws org.myLazyClock.calendarApi.exception.EventNotFoundException if not event found in specific day
 *//*w  ww .  j av  a2s.c o  m*/
@Override
public CalendarEvent getFirstEvent(Map<String, String> params, java.util.Calendar beginDate,
        java.util.Calendar endDate) throws EventNotFoundException, ForbiddenCalendarException {
    if (beginDate == null || endDate == null || params == null || params.get("tokenRequest") == null
            || params.get("tokenRequest").equals("") || params.get("gCalId") == null
            || params.get("gCalId").equals("")) {
        throw new EventNotFoundException();
    }

    DateTime startTime = new DateTime(beginDate.getTime());
    DateTime endTime = new DateTime(endDate.getTime());

    CalendarEvent returnEvent = new CalendarEvent();

    try {

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setClientSecrets(params.get("apiId"), params.get("apiSecret"))
                .build().setRefreshToken(params.get("tokenRequest"));

        Calendar service = new Calendar.Builder(httpTransport, jsonFactory, null)
                .setApplicationName("myLazyClock").setHttpRequestInitializer(credential).build();

        Events events = service.events().list(params.get("gCalId")).setTimeMin(startTime).setTimeMax(endTime)
                .setOrderBy("startTime").setSingleEvents(true).execute();

        if (events.getItems().isEmpty()) {
            throw new EventNotFoundException();
        }

        Event event = events.getItems().get(0);

        returnEvent.setName(event.getSummary());
        returnEvent.setBeginDate(new Date(event.getStart().getDateTime().getValue()));
        returnEvent.setEndDate(new Date(event.getEnd().getDateTime().getValue()));
        returnEvent.setAddress(event.getLocation());

    } catch (GeneralSecurityException e) {
        throw new ForbiddenCalendarException("Accs interdit au calendrier de Google");
    } catch (IOException e) {
        throw new EventNotFoundException(e);
    }

    return returnEvent;
}

From source file:org.myLazyClock.restApi.MyLazyClockUserApi.java

License:Open Source License

@ApiMethod(name = "myLazyClockUser.link", httpMethod = ApiMethod.HttpMethod.POST, path = "myLazyClockUser")
public MyLazyClockUserValid linkUser(@Named("code") String code, User user)
        throws UnauthorizedException, InternalServerErrorException {
    if (user == null) {
        throw new UnauthorizedException("Login Required");
    }//from   ww w . ja v  a2s  .  c om

    HttpTransport httpTransport = null;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException | IOException e) {
        throw new InternalServerErrorException(e);
    }
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            ConstantAPI.API_ID, ConstantAPI.API_SECRET, Arrays.asList(Constants.SCOPE_CALENDAR_READ)).build();

    GoogleTokenResponse response = null;
    try {
        response = flow.newTokenRequest(code).setRedirectUri("postmessage").execute();
    } catch (IOException e) {
        throw new InternalServerErrorException(e);
    }

    MyLazyClockUserValid isValid = MyLazyClockUserService.getInstance().add(user, response.getRefreshToken());

    MyLazyClockMemcacheService.getInstance().cleanUserValidity(user);

    return isValid;
}

From source file:org.myLazyClock.services.MyLazyClockUserService.java

License:Open Source License

public MyLazyClockUserValid checkValid(String userId) {
    MyLazyClockUser user = MyLazyClockUserRepository.getInstance().findOne(userId);

    if (user == null) {
        return new MyLazyClockUserValid();
    }/*from  www  . j av  a2s .  co  m*/

    HttpTransport httpTransport = null;
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException | IOException e) {
        return null;
    }
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
            .setJsonFactory(jsonFactory).setClientSecrets(ConstantAPI.API_ID, ConstantAPI.API_SECRET).build()
            .setRefreshToken(user.getToken());

    try {
        credential.refreshToken();
    } catch (IOException ignore) {
    }

    if (credential.getAccessToken() == null || credential.getAccessToken().equals("")) {
        user.setToken(null);
        MyLazyClockUserRepository.getInstance().save(user);
    }

    return MyLazyClockUserValid.fromMyLazyClockUser(user);
}

From source file:org.nuxeo.ecm.liveconnect.google.drive.credential.ServiceAccountCredentialFactory.java

License:Apache License

protected static HttpTransport getHttpTransport() throws IOException {
    try {/*from   www.ja  va 2 s. co m*/
        return GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:org.nuxeo.google.calendar.Publisher.java

License:Apache License

@OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel input) {
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport;//from   w  w  w  . j a  v  a 2  s  . c o  m
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        //Credential credential = new GoogleCredential().setAccessToken(getAccessToken(userEmailAddress));

        OAuth2ServiceProvider serviceProvider = Framework.getLocalService(OAuth2ServiceProviderRegistry.class)
                .getProvider("googledrive");
        Credential storedCredential = serviceProvider.loadCredential(userEmailAddress);

        Credential credential = new GoogleCredential.Builder()
                .setClientSecrets(serviceProvider.getClientId(), serviceProvider.getClientSecret())
                .setJsonFactory(JSON_FACTORY).setTransport(httpTransport).build()
                .setRefreshToken(storedCredential.getRefreshToken())
                .setAccessToken(storedCredential.getAccessToken());

        // Initialize Calendar service with valid OAuth credentials          
        Calendar service = new Calendar.Builder(httpTransport, JSON_FACTORY, credential).build();
        // Create an Event and publish it
        Event event = new Event().setSummary(summary).setLocation(location).setDescription(description);

        DateTime startDateTime = new DateTime(sdf.format(startDate.getTime()));
        EventDateTime start = new EventDateTime().setDate(startDateTime);
        event.setStart(start);

        //weird bug fix
        endDate.add(GregorianCalendar.DAY_OF_MONTH, 1);

        DateTime endDateTime = new DateTime(sdf.format(endDate.getTime()));
        EventDateTime end = new EventDateTime().setDate(endDateTime);
        event.setEnd(end);

        if (attendeeEmailAddress != null && !"".equals(attendeeEmailAddress)) {
            EventAttendee[] attendees = new EventAttendee[] {
                    new EventAttendee().setEmail(attendeeEmailAddress) };
            event.setAttendees(Arrays.asList(attendees));
        }
        String calendarId = "primary";
        event = service.events().insert(calendarId, event).execute();
    } catch (GeneralSecurityException | IOException e) {
        throw new NuxeoException(e);
    }
    return input;
}

From source file:org.nuxeo.google.task.Publisher.java

License:Apache License

@OperationMethod(collector = DocumentModelCollector.class)
public DocumentModel run(DocumentModel input) {
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport;//from   w w w . ja  v a 2s.c  o  m
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        OAuth2ServiceProvider serviceProvider = Framework.getLocalService(OAuth2ServiceProviderRegistry.class)
                .getProvider("googledrive");
        Credential storedCredential = serviceProvider.loadCredential(userEmailAddress);

        Credential credential = new GoogleCredential.Builder()
                .setClientSecrets(serviceProvider.getClientId(), serviceProvider.getClientSecret())
                .setJsonFactory(JSON_FACTORY).setTransport(httpTransport).build()
                .setRefreshToken(storedCredential.getRefreshToken())
                .setAccessToken(storedCredential.getAccessToken());

        // Initialize Tasks service with valid OAuth credentials          
        Tasks service = new Tasks.Builder(httpTransport, JSON_FACTORY, credential).build();

        // Create a Task and publish it
        DateTime dueDateTime = new DateTime(dueDate.getTime());

        Task task = new Task().setTitle(title).setNotes(notes).setDue(dueDateTime);

        task = service.tasks().insert("@default", task).execute();
    } catch (GeneralSecurityException | IOException e) {
        throw new NuxeoException(e);
    }
    return input;
}

From source file:org.nuxeo.naturallanguage.core.google.GoogleNaturalLanguageImpl.java

License:Apache License

private CloudNaturalLanguageAPI getLanguageService() throws IOException, GeneralSecurityException {

    if (naturalLanguageClient == null) {
        synchronized (this) {
            if (naturalLanguageClient == null) {
                GoogleCredential credential = null;
                if (usesServiceAccount()) {
                    File file = new File(googleConfig.getCredentialFilePath());
                    credential = GoogleCredential.fromStream(new FileInputStream(file))
                            .createScoped(CloudNaturalLanguageAPIScopes.all());
                }/*from  www  .ja va 2s.  c om*/

                JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
                naturalLanguageClient = new CloudNaturalLanguageAPI.Builder(
                        GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
                                .setApplicationName(googleConfig.getAppName()).build();
            }
        }
    }
    return naturalLanguageClient;
}

From source file:org.nuxeo.vision.core.service.VisionImpl.java

License:Apache License

private com.google.api.services.vision.v1.Vision getVisionService()
        throws IOException, GeneralSecurityException {
    // thread safe lazy initialization of the google vision client
    // see https://en.wikipedia.org/wiki/Double-checked_locking
    com.google.api.services.vision.v1.Vision result = visionClient;
    if (result == null) {
        synchronized (this) {
            result = visionClient;/*  w  w w  .jav  a  2s. c o m*/
            if (result == null) {
                GoogleCredential credential = null;
                if (usesServiceAccount()) {
                    File file = new File(googleConfig.getCredentialFilePath());
                    credential = GoogleCredential.fromStream(new FileInputStream(file))
                            .createScoped(VisionScopes.all());
                }
                JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
                result = visionClient = new com.google.api.services.vision.v1.Vision.Builder(
                        GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
                                .setApplicationName(googleConfig.getAppName()).build();
            }
        }
    }
    return result;
}