com.google.api.client.json.gson.GsonFactory Java Examples

The following examples show how to use com.google.api.client.json.gson.GsonFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 9 votes vote down vote up
public boolean authenticate(String AppName, String ScopeName)
{
    final GoogleSignInAccount SignInAccount = GoogleSignIn.getLastSignedInAccount(mActivityInstance);

    if(SignInAccount != null)
    {
        GoogleAccountCredential AccountCredential;
        Drive.Builder DriveBuilder;

        AccountCredential = GoogleAccountCredential.usingOAuth2(mActivityInstance, Collections.singleton(ScopeName));
        AccountCredential.setSelectedAccount(SignInAccount.getAccount());

        DriveBuilder = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), AccountCredential);
        DriveBuilder.setApplicationName(AppName);
        mDriveService = DriveBuilder.build();

        return true;
    }

    Log.d(TAG, "You have to signin by select account before use this call!");
    return false;
}
 
Example #2
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the {@code result} of a completed sign-in activity initiated from {@link
 * #requestSignIn()}.
 */
private void handleSignInResult(Intent result) {
    GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener(googleAccount -> {
                    Log.d(TAG, "Signed in as " + googleAccount.getEmail());

                    // Use the authenticated account to sign in to the Drive service.
                    GoogleAccountCredential credential =
                        GoogleAccountCredential.usingOAuth2(
                                this, Collections.singleton(DriveScopes.DRIVE_FILE));
                    credential.setSelectedAccount(googleAccount.getAccount());
                    Drive googleDriveService =
                        new Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                           .setApplicationName("Drive API Migration")
                           .build();

                    // The DriveServiceHelper encapsulates all REST API and SAF functionality.
                    // Its instantiation is required before handling any onClick actions.
                    mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
                })
            .addOnFailureListener(exception -> Log.e(TAG, "Unable to sign in.", exception));
}
 
Example #3
Source File: CloudBackend.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
private Mobilebackend getMBSEndpoint() {

        // check if credential has account name
        final GoogleAccountCredential gac = mCredential == null
                || mCredential.getSelectedAccountName() == null ? null : mCredential;

        // create HttpRequestInitializer
        HttpRequestInitializer hri = new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setBackOffPolicy(new ExponentialBackOffPolicy());
                if (gac != null) {
                    gac.initialize(request);
                }
            }
        };

        // build MBS builder
        // (specify gac or hri as the third parameter)
        return new Mobilebackend.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(),
                hri)
                .setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
    }
 
Example #4
Source File: TictactoeActivity.java    From appengine-endpoints-tictactoe-android with Apache License 2.0 6 votes vote down vote up
/**
 * Called when the activity is first created. It displays the UI, checks
 * for the account previously chosen to sign in (if available), and
 * configures the service object.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  settings = getSharedPreferences(TAG, 0);
  credential = GoogleAccountCredential.usingAudience(this, ClientCredentials.AUDIENCE);
  setAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

  Tictactoe.Builder builder = new Tictactoe.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(),
      credential);
  service = builder.build();

  if (credential.getSelectedAccountName() != null) {
    onSignIn();
  }

  Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
}
 
Example #5
Source File: MessagingService.java    From watchpresenter with Apache License 2.0 6 votes vote down vote up
public static Messaging get(Context context){
    if (messagingService == null) {
        SharedPreferences settings = context.getSharedPreferences(
                "Watchpresenter", Context.MODE_PRIVATE);
        final String accountName = settings.getString(Constants.PREF_ACCOUNT_NAME, null);
        if(accountName == null){
            Log.i(Constants.LOG_TAG, "Cannot send message. No account name found");
        }
        else {
            GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(context,
                    "server:client_id:" + Constants.ANDROID_AUDIENCE);
            credential.setSelectedAccountName(accountName);
            Messaging.Builder builder = new Messaging.Builder(AndroidHttp.newCompatibleTransport(),
                    new GsonFactory(), credential)
                    .setRootUrl(Constants.SERVER_URL);

            messagingService = builder.build();
        }
    }
    return messagingService;
}
 
Example #6
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void open(final TGBrowserCallBack<Object> cb){
	try {
		this.drive = null;
		this.folder = null;
		this.httpTransport = AndroidHttp.newCompatibleTransport();
		
		TGDriveBrowserLogin login = new TGDriveBrowserLogin(this.findActivity(), this.settings, new TGBrowserCallBack<GoogleAccountCredential>() {
			public void onSuccess(GoogleAccountCredential credential) {
				Drive.Builder builder = new Drive.Builder(TGDriveBrowser.this.httpTransport, GsonFactory.getDefaultInstance(), credential);
				builder.setApplicationName(findActivity().getString(R.string.gdrive_application_name));
				TGDriveBrowser.this.drive = builder.build();
				
				cb.onSuccess(null);
			}
			
			public void handleError(Throwable throwable) {
				cb.handleError(throwable);
			}
		});
		login.process();
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #7
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
private void handleSignInONRecnnect() {
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    if  (account != null ){
        Log.d(TAG, "Signed in as " + account.getEmail());

        // Use the authenticated account to sign in to the Drive service.
        GoogleAccountCredential credential =
                GoogleAccountCredential.usingOAuth2(
                        this, Collections.singleton(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccount(account.getAccount());

        googleDriveService =
                new com.google.api.services.drive.Drive.Builder(
                        AndroidHttp.newCompatibleTransport(),
                        new GsonFactory(),
                        credential)
                        .setApplicationName("Drive API DBSync")
                        .build();
    }
}
 
Example #8
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
private void handleSignInResult(Intent result) {
    GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener(googleAccount -> {
                Log.d(TAG, "Signed in as " + googleAccount.getEmail());

                // Use the authenticated account to sign in to the Drive service.
                GoogleAccountCredential credential =
                        GoogleAccountCredential.usingOAuth2(
                                this, Arrays.asList(DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA, DriveScopes.DRIVE_READONLY,
                                        DriveScopes.DRIVE_METADATA_READONLY, DriveScopes.DRIVE_PHOTOS_READONLY));
                credential.setSelectedAccount(googleAccount.getAccount());

                googleDriveService =
                        new com.google.api.services.drive.Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                                .setApplicationName("Drive API DBSync")
                                .build();

                // The DriveServiceHelper encapsulates all REST API and SAF functionality.
                // Its instantiation is required before handling any onClick actions.
                //mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
            })
            .addOnFailureListener(exception -> Log.e(TAG, "Unable to sign in.", exception));
}
 
Example #9
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomToken() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #10
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithDeveloperClaims() throws Exception {
  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync(
      "user1", MapBuilder.of("claim", "value")).get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
  assertEquals(parsedToken.getPayload().getDeveloperClaims().keySet().size(), 1);
  assertEquals(parsedToken.getPayload().getDeveloperClaims().get("claim"), "value");
  assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
}
 
Example #11
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithoutServiceAccountCredentials() throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  response.setContent(content);
  MockHttpTransport transport = new MultiRequestMockHttpTransport(ImmutableList.of(response));

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setServiceAccountId("[email protected]")
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example #12
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createOptionsWithAllValuesSet() throws IOException {
  GsonFactory jsonFactory = new GsonFactory();
  NetHttpTransport httpTransport = new NetHttpTransport();
  FirestoreOptions firestoreOptions = FirestoreOptions.newBuilder()
      .setTimestampsInSnapshotsEnabled(true)
      .build();
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setDatabaseUrl(FIREBASE_DB_URL)
          .setStorageBucket(FIREBASE_STORAGE_BUCKET)
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .setProjectId(FIREBASE_PROJECT_ID)
          .setJsonFactory(jsonFactory)
          .setHttpTransport(httpTransport)
          .setThreadManager(MOCK_THREAD_MANAGER)
          .setConnectTimeout(30000)
          .setReadTimeout(60000)
          .setFirestoreOptions(firestoreOptions)
          .build();
  assertEquals(FIREBASE_DB_URL, firebaseOptions.getDatabaseUrl());
  assertEquals(FIREBASE_STORAGE_BUCKET, firebaseOptions.getStorageBucket());
  assertEquals(FIREBASE_PROJECT_ID, firebaseOptions.getProjectId());
  assertSame(jsonFactory, firebaseOptions.getJsonFactory());
  assertSame(httpTransport, firebaseOptions.getHttpTransport());
  assertSame(MOCK_THREAD_MANAGER, firebaseOptions.getThreadManager());
  assertEquals(30000, firebaseOptions.getConnectTimeout());
  assertEquals(60000, firebaseOptions.getReadTimeout());
  assertSame(firestoreOptions, firebaseOptions.getFirestoreOptions());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
}
 
Example #13
Source File: GoogleClientSecretsTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testLoad() throws Exception {
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(new GsonFactory(), new StringReader(CLIENT_SECRETS));
  Details installed = clientSecrets.getInstalled();
  assertNotNull(installed);
  assertEquals(CLIENT_ID, installed.getClientId());
  assertEquals(CLIENT_SECRET, installed.getClientSecret());
}
 
Example #14
Source File: CloudShellCredentialTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void refreshAccessToken() throws IOException{
  final ServerSocket authSocket = new ServerSocket(0);
  Runnable serverTask =
      new Runnable() {
        @Override
        public void run() {
          try {
            Socket clientSocket = authSocket.accept();
            BufferedReader input =
                new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String lines = input.readLine();
            lines += '\n' + input.readLine();
            assertEquals(CloudShellCredential.GET_AUTH_TOKEN_REQUEST, lines);

            PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream(), true);
            out.println("32\n[\"email\", \"project-id\", \"token\", 1234]");
          } catch (Exception reThrown) {
            throw new RuntimeException(reThrown);
          }
        }
      };
  Thread serverThread = new Thread(serverTask);
  serverThread.start();

  GoogleCredential creds = new CloudShellCredential(
      authSocket.getLocalPort(), GsonFactory.getDefaultInstance());
  assertEquals("token", creds.executeRefreshToken().getAccessToken());
}
 
Example #15
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * Validates the access token issued with an ID Token, by comparing the result of the access token hash
 * with the 'at_hash' claim contained on the ID Token.
 * @param accessTokenString the access token to hash
 * @param idTokenString the ID Token were the 'at_hash' can be found
 * @return true if the result of the hashed access token is equal to the 'at_hash' claim.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @see <a hfre="http://openid.net/specs/openid-connect-core-1_0.html#ImplicitTokenValidation">http://openid.net/specs/openid-connect-core-1_0.html#ImplicitTokenValidation</a>
 */
private boolean isValidAccessToken(String accessTokenString, String idTokenString) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    boolean isValidAt = false;
    if (!TextUtils.isEmpty(accessTokenString) && !TextUtils.isEmpty(idTokenString)) {
        IdToken idToken = IdToken.parse(new GsonFactory(), idTokenString);
        String alg = idToken.getHeader().getAlgorithm();
        byte[] atBytes = accessTokenString.getBytes("UTF-8");
        String atHash = idToken.getPayload().getAccessTokenHash();

        String forgedAtHash;
        if ("HS256".equals(alg) || "RS256".equals(alg)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(atBytes, 0, atBytes.length);
            atBytes = digest.digest();
            atBytes = Arrays.copyOfRange(atBytes, 0, atBytes.length / 2);
            forgedAtHash = Base64.encodeToString(atBytes, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);

            Log.d(TAG, "Alg : " + alg);
            Log.d(TAG, "Receive at_hash : " + atHash);
            Log.d(TAG, "Forged at_hash  : " + forgedAtHash);

            isValidAt = atHash.equals(forgedAtHash);
        } else {
            Log.w(TAG, "Unsupported alg claim : " +alg + ". Supported alg are HS256, RS256");
        }

    } else {
        Log.w(TAG, "Can't verify access token, AT or idToken empty");
    }

    return true;//isValidAt;
}
 
Example #16
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * Validates an IdToken.
 * TODO: Look into verifying the token nonce as well?
 *
 * @param idTokenString the IdToken to validate
 * @return true if the idToken is valid, false otherwise.
 * @throws IOException when the IdToken can not be parse.
 * @see IdTokenVerifier#verify(IdToken)
 */
private boolean isValidIdToken(@NonNull String idTokenString) throws IOException {

    List<String> audiences = Collections.singletonList(clientId);
    IdTokenVerifier verifier = new IdTokenVerifier.Builder()
            .setAudience(audiences)
            .setAcceptableTimeSkewSeconds(1000)
            .setIssuer(issuerId)
            .build();

    IdToken idToken = IdToken.parse(new GsonFactory(), idTokenString);

    return true;//verifier.verify(idToken);
}
 
Example #17
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 *  Exchanges a Refresh Token for a new set of tokens.
 *
 *  Note that the Token Server may require you to use the `offline_access` scope to receive
 *  Refresh Tokens.
 *
 * @param refreshToken the refresh token used to request new Access Token / idToken.
 * @return the parsed successful token response received from the token endpoint
 * @throws IOException for an error response
 */
public TokenResponse refreshTokens(String refreshToken) throws IOException {

    List<String> scopesList = Arrays.asList(scopes);

    RefreshTokenRequest request = new RefreshTokenRequest(
            AndroidHttp.newCompatibleTransport(),
            new GsonFactory(),
            new GenericUrl(tokenEndpoint),
            refreshToken);

    if (!scopesList.isEmpty()) {
        request.setScopes(scopesList);
    }

    // This are extra query parameters that can be specific to an OP. For instance prompt -> consent
    // tells the Authorization Server that it SHOULD prompt the End-User for consent before returning
    // information to the Client.
    if (extras != null) {
        for (Map.Entry<String, String> queryParam : extras.entrySet()) {
            request.set(queryParam.getKey(), queryParam.getValue());
        }
    }

    // If the oidc client is confidential (needs authentication)
    if (!TextUtils.isEmpty(clientSecret)) {
        request.setClientAuthentication(new BasicAuthentication(clientId, clientSecret));
    } else {
        request.set("client_id", clientId);
    }

    if (useOAuth2) {
        if (scopesList.contains("openid")) {
            Log.w(TAG, "Using OAuth2 only request but scopes contain values for OpenId Connect");
        }
        return request.executeUnparsed().parseAs(TokenResponse.class);
    } else {
        return IdTokenResponse.execute(request);
    }
}
 
Example #18
Source File: Checker.java    From gplus-verifytoken-java with Apache License 2.0 5 votes vote down vote up
public Checker(String[] clientIDs, String audience) {
    mClientIDs = Arrays.asList(clientIDs);
    mAudience = audience;
    NetHttpTransport transport = new NetHttpTransport();
    mJFactory = new GsonFactory();
    mVerifier = new GoogleIdTokenVerifier(transport, mJFactory);
}
 
Example #19
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCustomTokenWithDiscoveredServiceAccount() throws Exception {
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  List<MockLowLevelHttpResponse> responses = ImmutableList.of(
      // Service account discovery response
      new MockLowLevelHttpResponse().setContent("[email protected]"),

      // Sign blob response
      new MockLowLevelHttpResponse().setContent(content)
  );
  MockHttpTransport transport = new MultiRequestMockHttpTransport(responses);

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example #20
Source File: GerritEndpointTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
private String postLabel() {
  Map<String, Object> result = new LinkedHashMap<>();
  result.put("labels", ImmutableMap.of("Code-Review",  1));
  try {
    return GsonFactory.getDefaultInstance().toPrettyString(result);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: GitHubPrOriginTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
private String toJson(Object obj) {
  try {
    return GsonFactory.getDefaultInstance().toPrettyString(obj);
  } catch (IOException e) {
    // Unexpected
    throw new IllegalStateException(e);
  }
}
 
Example #22
Source File: Checker.java    From gplus-verifytoken-java with Apache License 2.0 5 votes vote down vote up
public Checker(String[] clientIDs, String audience) {
    mClientIDs = Arrays.asList(clientIDs);
    mAudience = audience;
    NetHttpTransport transport = new NetHttpTransport();
    mJFactory = new GsonFactory();
    mVerifier = new GoogleIdTokenVerifier(transport, mJFactory);
}
 
Example #23
Source File: AbstractGitHubApiTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(String s) {
  try {
    T requestObject = GsonFactory.getDefaultInstance().createJsonParser(s).parse(clazz);
    called = true;
    return predicate.test(requestObject);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #24
Source File: QueryBuilder.java    From android-google-places with MIT License 5 votes vote down vote up
/**
 * @param transport
 * @return
 */
private static HttpRequestFactory createRequestFactory(final HttpTransport transport) {

	return transport.createRequestFactory(new HttpRequestInitializer() {
		public void initialize(HttpRequest request) {
			request.setHeaders(new HttpHeaders());
			request.setParser(new JsonObjectParser(new GsonFactory()));
		}
	});
}
 
Example #25
Source File: GoogleTranslator.java    From alexa-meets-polly with Apache License 2.0 5 votes vote down vote up
public GoogleTranslator(final String locale) {
    super(locale, "/languages-google.yml");

    try {
        this.translator = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(), null)
                .setApplicationName(SkillConfig.getGoogleProjectName())
                .build();
    } catch (final GeneralSecurityException | IOException ex) {
        log.log(Level.SEVERE, null, ex);
    }
}
 
Example #26
Source File: CloudVisionUtils.java    From doorbell with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an annotated image request for the provided image to be executed
 * using the provided API interface.
 *
 * @param imageBytes image bytes in JPEG format.
 * @return collection of annotation descriptions and scores.
 */
public static Map<String, Float> annotateImage(byte[] imageBytes) throws IOException {
    // Construct the Vision API instance
    HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
    VisionRequestInitializer initializer = new VisionRequestInitializer(CLOUD_VISION_API_KEY);
    Vision vision = new Vision.Builder(httpTransport, jsonFactory, null)
            .setVisionRequestInitializer(initializer)
            .build();

    // Create the image request
    AnnotateImageRequest imageRequest = new AnnotateImageRequest();
    Image img = new Image();
    img.encodeContent(imageBytes);
    imageRequest.setImage(img);

    // Add the features we want
    Feature labelDetection = new Feature();
    labelDetection.setType(LABEL_DETECTION);
    labelDetection.setMaxResults(MAX_LABEL_RESULTS);
    imageRequest.setFeatures(Collections.singletonList(labelDetection));

    // Batch and execute the request
    BatchAnnotateImagesRequest requestBatch = new BatchAnnotateImagesRequest();
    requestBatch.setRequests(Collections.singletonList(imageRequest));
    BatchAnnotateImagesResponse response = vision.images()
            .annotate(requestBatch)
            // Due to a bug: requests to Vision API containing large images fail when GZipped.
            .setDisableGZipContent(true)
            .execute();

    return convertResponseToMap(response);
}
 
Example #27
Source File: GerritApiTest.java    From copybara with Apache License 2.0 4 votes vote down vote up
private static String mockReviewResult() throws IOException {
  Map<String, Object> result = new LinkedHashMap<>();
  result.put("labels", ImmutableMap.of("Code-Review", (short) -1));
  return GsonFactory.getDefaultInstance().toPrettyString(result);
}
 
Example #28
Source File: GsonNotificationCallback.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected JsonFactory getJsonFactory() {
  return GsonFactory.getDefaultInstance();
}
 
Example #29
Source File: YouTubeSampleTest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testParsing() throws IOException {
  final InputStream contents = getClass().getClassLoader().getResourceAsStream("youtube-search.json");
  Preconditions.checkNotNull(contents);
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContentType(Json.MEDIA_TYPE);
              result.setContent(contents);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setParser(new JsonObjectParser(new GsonFactory()));
  HttpResponse response = request.execute();

  YouTubeSample.ListResponse listResponse = YouTubeSample.parseJson(response);
  assertEquals(5, listResponse.getPageInfo().getResultsPerPage());
  assertEquals(1000000, listResponse.getPageInfo().getTotalResults());
  assertEquals(5, listResponse.getSearchResults().size());
  for (YouTubeSample.SearchResult searchResult : listResponse.getSearchResults()) {
    assertEquals("youtube#searchResult", searchResult.getKind());
    assertNotNull(searchResult.getId());
    assertEquals("youtube#video", searchResult.getId().getKind());
    assertNotNull(searchResult.getId().getVideoId());
    YouTubeSample.Snippet snippet = searchResult.getSnippet();
    assertNotNull(snippet);
    assertNotNull(snippet.getChannelId());
    assertNotNull(snippet.getDescription());
    assertNotNull(snippet.getTitle());
    assertNotNull(snippet.getPublishedAt());
    Map<String, YouTubeSample.Thumbnail> thumbnails = snippet.getThumbnails();
    assertNotNull(thumbnails);

    for (Map.Entry<String, YouTubeSample.Thumbnail> entry : thumbnails.entrySet()) {
      assertNotNull(entry.getKey());
      YouTubeSample.Thumbnail thumbnail = entry.getValue();
      assertNotNull(thumbnail);
      assertNotNull(thumbnail.getUrl());
      assertNotNull(thumbnail.getWidth());
      assertNotNull(thumbnail.getHeight());
    }
  }
}
 
Example #30
Source File: ConnectActivity.java    From android-java-connect-rest-sample with MIT License 4 votes vote down vote up
private void connect() {
    // define the post-auth callback
    AuthenticationCallback<String> callback =
            new AuthenticationCallback<String>() {

                @Override
                public void onSuccess(String idToken) {
                    String name = "";
                    String preferredUsername = "";
                    try {
                        // get the user info from the id token
                        IdToken claims = IdToken.parse(new GsonFactory(), idToken);
                        name = claims.getPayload().get("name").toString();
                        preferredUsername = claims.getPayload().get("preferred_username").toString();
                    } catch (IOException ioe) {
                        Log.e(TAG, ioe.getMessage());
                    } catch (NullPointerException npe) {
                        Log.e(TAG, npe.getMessage());

                    }

                    // Prepare the SendMailActivity intent
                    Intent sendMailActivity =
                            new Intent(ConnectActivity.this, SendMailActivity.class);

                    // take the user's info along
                    sendMailActivity.putExtra(SendMailActivity.ARG_GIVEN_NAME, name);
                    sendMailActivity.putExtra(SendMailActivity.ARG_DISPLAY_ID, preferredUsername);

                    // actually start the activity
                    startActivity(sendMailActivity);

                    resetUIForConnect();
                }

                @Override
                public void onError(Exception exc) {
                    showConnectErrorUI();
                }
            };

    AuthenticationManager mgr = AuthenticationManager.getInstance(this);
    mgr.connect(this, callback);
}