List of usage examples for com.google.api.client.googleapis.javanet GoogleNetHttpTransport newTrustedTransport
public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException
From source file:it.noovle.dataflow.TwitterProcessor.java
License:Open Source License
/** * Connects to the Natural Language API using Application Default Credentials. */// ww w . java 2s.c o m private static CloudNaturalLanguageAPI getLanguageService() throws IOException, GeneralSecurityException { final GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(CloudNaturalLanguageAPIScopes.all()); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); return new CloudNaturalLanguageAPI.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { credential.initialize(request); } }).setApplicationName(APPLICATION_NAME).build(); }
From source file:it.polimi.meteocal.ejb.HandleAuthGoogleImpl.java
License:Open Source License
/** * Method that return the Plus object that allows the access to the * GooglePlus API/*from ww w . j a va 2s.c o m*/ * * @param user the user in MeteoCal * @return null if there was a problem with the creation of the Plus object */ public static Plus getPlusObject(User user) { Plus plus = null; final User utente2 = user; if (user.getGoogleToken() == null) { // Case in wich google plus is not connected return null; } try { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()).setClientSecrets(CLIENT_ID, CLIENT_SECRET) .addRefreshListener(new CredentialRefreshListener() { @Override public void onTokenResponse(Credential credential, TokenResponse tokenResponse) { HandleAuthGoogleImpl.setGoogleToken(credential, tokenResponse, utente2); // Handle success. LOGGER.log(Level.INFO, "Credential was refreshed successfully."); } @Override public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) { // Handle error. LOGGER.log(Level.ERROR, "Credential was not refreshed successfully. " + "Redirect to error page or login screen."); } }) /* You can also add a credential store listener to have credentials stored automatically. .addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)) */ .build(); // Set authorized credentials. credential.setFromTokenResponse( JSON_FACTORY.fromString(user.getGoogleToken(), GoogleTokenResponse.class)); /* Though not necessary when first created, you can manually refresh the token, which is needed after 60 minutes. */ if (credential.getExpiresInSeconds() < 1) { boolean ref = credential.refreshToken(); LOGGER.log(Level.INFO, "Refresh token: " + ref); LOGGER.log(Level.INFO, "Access token: " + credential.getAccessToken()); LOGGER.log(Level.INFO, "Refresh token: " + credential.getRefreshToken()); } // Create a new authorized API client. plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME) .build(); } catch (IOException | GeneralSecurityException e) { LOGGER.log(Level.ERROR, e, e); } return plus; }
From source file:it.polimi.meteocal.ejb.HandleAuthGoogleImpl.java
License:Open Source License
/** * Method that updates the google token in the DB using the refresh token * * @param credential the credential for access the google API * @param tokenResponse the http response with the token * @param user the user in MeteoCal/*from ww w.j a v a 2 s . co m*/ * @see Credential * @see TokenResponse */ protected static void setGoogleToken(Credential credential, TokenResponse tokenResponse, User user) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("MeteoCalEJB"); EntityManager em = emf.createEntityManager(); try { HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); String tokenGoogle = tokenResponse.toString(); LOGGER.log(Level.INFO, tokenGoogle); JsonParser parser = new JsonParser(); JsonObject newToken = parser.parse(tokenGoogle).getAsJsonObject(); JsonObject oldToken = parser.parse(user.getGoogleToken()).getAsJsonObject(); newToken.add("refresh_token", oldToken.get("refresh_token")); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setLenient(true); Streams.write(newToken, jsonWriter); tokenGoogle = stringWriter.toString(); LOGGER.log(Level.INFO, tokenGoogle); if (tokenGoogle.contains("refresh_token")) { LOGGER.log(Level.INFO, "GoogleToken updated"); user.setGoogleToken(tokenGoogle); em.merge(user); em.joinTransaction(); em.flush(); } } catch (GeneralSecurityException | IOException e) { LOGGER.log(Level.ERROR, e, e); } em.close(); emf.close(); }
From source file:it.polimi.meteocal.ejb.HandleAuthGoogleImpl.java
License:Open Source License
@Override public boolean doLoginGoogle(String code) { try {/*from w ww .ja va 2 s . c o m*/ httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleTokenResponse tokenResponse = flow.newTokenRequest(code) .setRedirectUri("http://www.meteocal.tk/MeteoCal-web/loginGoogle.xhtml").execute(); GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()).setClientSecrets(CLIENT_ID, CLIENT_SECRET) .addRefreshListener(new RefreshListener()).build(); // Set authorized credentials. credential.setFromTokenResponse(tokenResponse); // Though not necessary when first created, you can manually refresh // the // token, which is needed after 60 minutes. // credential.refreshToken(); String tokenGoogle = tokenResponse.toString(); // Insert new data in the DB Plus plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); Person mePerson = plus.people().get("me").execute(); if (!AuthUtil.isUserLogged()) { // Saves the new data of the user in the DB User user = null; TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_GOOGLE_ID, User.class); q.setParameter("googleId", mePerson.getId()); TypedQuery<User> q2 = em.createNamedQuery(User.FIND_BY_EMAIL, User.class); if (mePerson.getEmails() != null) { q2.setParameter("email", mePerson.getEmails().get(0).getValue()); } else { q2.setParameter("email", ""); } if (q.getResultList().isEmpty() && q2.getResultList().isEmpty()) { // The user is not in the system user = new User(); user.setGoogleId(mePerson.getId()); user.setGoogleToken(tokenGoogle); user.setFirstName(mePerson.getName().getGivenName()); user.setLastName(mePerson.getName().getFamilyName()); user.setAvatar(mePerson.getImage().getUrl()); if (mePerson.getEmails() != null) { user.setEmail(mePerson.getEmails().get(0).getValue()); } if (mePerson.getBirthday() != null) { try { user.setDateBirth(new SimpleDateFormat("MM/dd").parse(mePerson.getBirthday())); } catch (ParseException ex) { LOGGER.log(Level.WARN, ex); } } try { user.setPassword(PasswordHash.createHash(user.getFirstName() + "." + user.getLastName())); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { LOGGER.log(Level.FATAL, ex, ex); } LOGGER.log(Level.INFO, user.toString()); Setting setting = new Setting(); setting.setTimeZone(TimeZone.getTimeZone("GMT+1")); user.setSetting(setting); em.persist(user); em.flush(); em.refresh(user); } else if (!q.getResultList().isEmpty()) { // The user is already in the system LOGGER.log(Level.INFO, "User already registered with Google"); user = q.getResultList().get(0); if (tokenGoogle.contains("refresh_token")) { LOGGER.log(Level.INFO, "GoogleToken updated"); user.setGoogleToken(tokenGoogle); em.merge(user); em.flush(); } } else { LOGGER.log(Level.INFO, "User already registered with classic method"); user = q2.getResultList().get(0); //TODO merge informazioni da google mancanti em.merge(user); em.flush(); } // Make the session for the user AuthUtil.makeUserSession(user.getId()); } else { // User already registered in the system User utente = em.find(User.class, AuthUtil.getUserID()); TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_GOOGLE_ID, User.class); q.setParameter("googleId", mePerson.getId()); if (q.getResultList().isEmpty()) { // The user account isn't already present in the db so set the new GooglePlus data utente.setGoogleId(mePerson.getId()); utente.setGoogleToken(tokenGoogle); em.merge(utente); em.flush(); } else { // User account already in the system LOGGER.log(Level.INFO, "User already registered with GooglePlus"); User oldUser = q.getResultList().get(0); if (!Objects.equals(utente.getId(), oldUser.getId())) { // Need to merge the two account utente = HandleUserImpl.mergeUserAccount(utente, oldUser); // set the new GooglePlus data utente.setGoogleId(mePerson.getId()); utente.setGoogleToken(tokenGoogle); em.merge(utente); em.flush(); // Transfer all the settings HandleUserImpl.mergeOldUserNewUser(em, utente, oldUser); em.remove(oldUser); em.flush(); } } } } catch (IOException e) { LOGGER.log(Level.ERROR, e); return false; } catch (GeneralSecurityException ex) { LOGGER.log(Level.ERROR, ex); } return true; }
From source file:jp.co.opentone.bsol.framework.core.google.vision.GoogleVisionApiClient.java
License:Apache License
private Vision createVision() throws IOException, GeneralSecurityException { GoogleCredential credential = GoogleCredential .fromStream(Files.newInputStream(Paths.get(config.getAccountFilePath()))) .createScoped(VisionScopes.all()); Vision vision = new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(config.getApplicationName()) .build();// w w w. ja va 2s . c o m return vision; }
From source file:me.tango.devops.google.CredentialsManager.java
License:Apache License
/** Configure. */ public static void setup(final String file) throws IOException, GeneralSecurityException { clientSecretFile = file;//from 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); }
From source file:mx.gob.hidalgo.repss.planeacion.services.google.GoogleCloudStorage.java
License:Apache License
/** * Returns an authenticated Storage object used to make service calls to Cloud Storage. *//*from w ww .ja va2 s .co m*/ private static Storage getService() throws IOException, GeneralSecurityException { if (null == storageService) { GoogleCredential credential = GoogleCredential.getApplicationDefault(); // Depending on the environment that provides the default credentials (e.g. 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()) { credential = credential.createScoped(StorageScopes.all()); } HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); } return storageService; }
From source file:name.herve.gcms.CalendarWrapper.java
License:Open Source License
public void init() throws IOException { try {//from ww w .jav a 2s . c o m jsonFactory = new JacksonFactory(); httpTransport = GoogleNetHttpTransport.newTrustedTransport(); Credential credential = authorize(); client = new Calendar.Builder(httpTransport, jsonFactory, credential) .setApplicationName(APPLICATION_NAME).build(); } catch (GeneralSecurityException e) { throw new IOException(e); } catch (Exception e) { throw new IOException(e); } }
From source file:net.bis5.slack.command.gcal.AppConfig.java
License:Apache License
public HttpTransport newTransport() { try {//from ww w .ja v a2 s .c o m return GoogleNetHttpTransport.newTrustedTransport(); } catch (GeneralSecurityException | IOException e) { throw new RuntimeException(e); } }
From source file:net.derquinse.bocas.gcs.GCSBocasService.java
License:Apache License
private static synchronized void init() { try {/* w w w . j a v a2 s. c o m*/ HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); JSON_FACTORY = JacksonFactory.getDefaultInstance(); } catch (Exception e) { throw new BocasException(e); } }