com.google.api.client.json.GenericJson Java Examples
The following examples show how to use
com.google.api.client.json.GenericJson.
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: GoogleCredentialTest.java From google-api-java-client with Apache License 2.0 | 6 votes |
public void testFromStreamServiceAccountMissingClientIdThrows() throws IOException { final String serviceAccountEmail = "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_email", serviceAccountEmail); serviceAccountContents.put("private_key", SA_KEY_TEXT); serviceAccountContents.put("private_key_id", SA_KEY_ID); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("client_id")); } }
Example #2
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testCreateSessionCookie() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( TestUtils.loadResource("createSessionCookie.json")); SessionCookieOptions options = SessionCookieOptions.builder() .setExpiresIn(TimeUnit.HOURS.toMillis(1)) .build(); String cookie = FirebaseAuth.getInstance().createSessionCookieAsync("testToken", options).get(); assertEquals("MockCookieString", cookie); checkRequestHeaders(interceptor); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals(2, parsed.size()); assertEquals("testToken", parsed.get("idToken")); assertEquals(new BigDecimal(3600), parsed.get("validDuration")); }
Example #3
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testImportUsers() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement("{}"); ImportUserRecord user1 = ImportUserRecord.builder().setUid("user1").build(); ImportUserRecord user2 = ImportUserRecord.builder().setUid("user2").build(); List<ImportUserRecord> users = ImmutableList.of(user1, user2); UserImportResult result = FirebaseAuth.getInstance().importUsersAsync(users, null).get(); checkRequestHeaders(interceptor); assertEquals(2, result.getSuccessCount()); assertEquals(0, result.getFailureCount()); assertTrue(result.getErrors().isEmpty()); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals(1, parsed.size()); List<Map<String, Object>> expected = ImmutableList.of( user1.getProperties(jsonFactory), user2.getProperties(jsonFactory) ); assertEquals(expected, parsed.get("users")); }
Example #4
Source File: MockHttpTransportHelper.java From hadoop-connectors with Apache License 2.0 | 6 votes |
public static MockLowLevelHttpResponse jsonErrorResponse(ErrorResponses errorResponse) throws IOException { GoogleJsonError.ErrorInfo errorInfo = new GoogleJsonError.ErrorInfo(); errorInfo.setReason(errorResponse.getErrorReason()); errorInfo.setDomain(errorResponse.getErrorDomain()); errorInfo.setFactory(JSON_FACTORY); GoogleJsonError jsonError = new GoogleJsonError(); jsonError.setCode(errorResponse.getErrorCode()); jsonError.setErrors(ImmutableList.of(errorInfo)); jsonError.setMessage(errorResponse.getErrorMessage()); jsonError.setFactory(JSON_FACTORY); GenericJson errorResponseJson = new GenericJson(); errorResponseJson.set("error", jsonError); errorResponseJson.setFactory(JSON_FACTORY); return new MockLowLevelHttpResponse() .setContent(errorResponseJson.toPrettyString()) .setContentType(Json.MEDIA_TYPE) .setStatusCode(errorResponse.getResponseCode()); }
Example #5
Source File: BatchRequestServiceTest.java From connector-sdk with Apache License 2.0 | 6 votes |
@Test public void testBatchRequestIOException() throws Exception { BatchRequestService batchService = setupService(); batchService.startAsync().awaitRunning(); assertTrue(batchService.isRunning()); BatchRequest batchRequest = getMockBatchRequest(); when(batchRequestHelper.createBatch(any())).thenReturn(batchRequest); AsyncRequest<GenericJson> requestToBatch = new AsyncRequest<GenericJson>(testRequest, retryPolicy, operationStats); GoogleJsonError error = new GoogleJsonError(); error.setCode(403); error.setMessage("unauthorized"); doAnswer( invocation -> { throw new IOException(); }) .when(batchRequestHelper) .executeBatchRequest(batchRequest); batchService.add(requestToBatch); batchService.flush(); batchService.stopAsync().awaitTerminated(); validateFailedResult(requestToBatch.getFuture()); assertFalse(batchService.isRunning()); }
Example #6
Source File: GoogleIdTokenVerifierTest.java From styx with Apache License 2.0 | 6 votes |
private String createToken() throws GeneralSecurityException, IOException { var issuedAt = Instant.now().getEpochSecond(); var expiredAt = issuedAt + 3600; // One hour later var payload = new GoogleIdToken.Payload(); payload.setAuthorizedParty("103411466401044735393"); payload.setEmail("[email protected]"); payload.setEmailVerified(true); payload.setIssuedAtTimeSeconds(issuedAt); payload.setExpirationTimeSeconds(expiredAt); payload.setIssuer("https://accounts.google.com"); payload.setSubject("103411466401044735393"); GenericJson googleMetadata = new GenericJson() .set("compute_engine", new GenericJson() .set("instance_creation_timestamp", 1556025719L) .set("instance_id", "5850837338805153689") .set("instance_name", "gew1-metricscatalogbro-b-b7z2") .set("project_id", "metrics-catalog") .set("project_number", 283581591831L) .set("zone", "europe-west1-d") ); payload.set("google", googleMetadata); var header = new JsonWebSignature.Header().setAlgorithm("RS256"); return JsonWebSignature.signUsingRsaSha256(privateKey, Utils.getDefaultJsonFactory(), header, payload); }
Example #7
Source File: FullTraversalConnector.java From connector-sdk with Apache License 2.0 | 6 votes |
/** * Performs the asynchronously pushed operation from the {@link Repository}. * * <p>This is <em>only</em> used when the {@link Repository} supports asynchronous operations * outside of normal traversals. Use this operation for any asynchronously triggered action, such * as document deletion, modification, or creation. * * @param asyncOp the operation asynchronously pushed from the {@link Repository} */ @Subscribe public synchronized void handleAsyncOperation(AsyncApiOperation asyncOp) { logger.log(Level.INFO, "Processing an asynchronous repository operation."); try { String queueName = queueCheckpoint.getCurrentQueueName(); ExecuteCounter executeCounter = new ExecuteCounter(); ListenableFuture<List<GenericJson>> future = listeningExecutorService.submit( new ExecuteOperationCallable(asyncOp.getOperation(), executeCounter, 0L, queueName)); asyncOp.setResult(future); } catch (IOException e) { logger.log( Level.WARNING, "Exception occured while processing an asynchronous repository operation: ", e); asyncOp.getResult().cancel(true); } }
Example #8
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithEmailLink( String email, String oobCode) throws IOException { GenericUrl url = new GenericUrl(EMAIL_LINK_SIGN_IN_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "email", email, "oobCode", oobCode); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example #9
Source File: GoogleCredentialTest.java From google-api-java-client with Apache License 2.0 | 6 votes |
static String createUserJson(String clientId, String clientSecret, String refreshToken) throws IOException { GenericJson userCredentialContents = new GenericJson(); userCredentialContents.setFactory(JSON_FACTORY); if (clientId != null) { userCredentialContents.put("client_id", clientId); } if (clientSecret != null) { userCredentialContents.put("client_secret", clientSecret); } if (refreshToken != null) { userCredentialContents.put("refresh_token", refreshToken); } userCredentialContents.put("type", GoogleCredential.USER_FILE_TYPE); String json = userCredentialContents.toPrettyString(); return json; }
Example #10
Source File: GoogleCredentialTest.java From google-api-java-client with Apache License 2.0 | 6 votes |
public void testFromStreamServiceAccountMissingPrivateKeyThrows() throws IOException { final String serviceAccountId = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com"; final String serviceAccountEmail = "36680232662-vrd7ji19qgchd0ah2csanun6bnr@developer.gserviceaccount.com"; MockHttpTransport transport = new MockTokenServerTransport(); // Write out user file GenericJson serviceAccountContents = new GenericJson(); serviceAccountContents.setFactory(JSON_FACTORY); serviceAccountContents.put("client_id", serviceAccountId); serviceAccountContents.put("client_email", serviceAccountEmail); serviceAccountContents.put("private_key_id", SA_KEY_ID); serviceAccountContents.put("type", GoogleCredential.SERVICE_ACCOUNT_FILE_TYPE); String json = serviceAccountContents.toPrettyString(); InputStream serviceAccountStream = new ByteArrayInputStream(json.getBytes()); try { GoogleCredential.fromStream(serviceAccountStream, transport, JSON_FACTORY); fail(); } catch (IOException expected) { assertTrue(expected.getMessage().contains("private_key")); } }
Example #11
Source File: ListingConnector.java From connector-sdk with Apache License 2.0 | 6 votes |
/** * Performs the asynchronously pushed operation from the {@link Repository}. * * <p>This is <em>only</em> used when the {@link Repository} supports asynchronous operations * outside of normal traversals. Use this operation for triggered actions (such as created, * modified, or deleted documents) that cannot be queried from a full or incremental traversal or * when the change should be detected and acted on immediately. * * @param asyncOp the operation asynchronously pushed from the {@link Repository} */ @Subscribe public void handleAsyncOperation(AsyncApiOperation asyncOp) { ListenableFuture<List<GenericJson>> result = listeningExecutorService.submit( () -> { logger.log(Level.INFO, "Processing an asynchronous repository operation."); try { return execute( Collections.singleton(asyncOp.getOperation()), "asynchronous repository operation"); } catch (IOException ex) { logger.log( Level.WARNING, "Exception occured while processing an asynchronous repository operation: ", ex); throw ex; } }); asyncOp.setResult(result); }
Example #12
Source File: DataflowApiUtils.java From beam with Apache License 2.0 | 6 votes |
/** * Determines the serialized size (in bytes) of the {@link GenericJson} object that will be * serialized and sent to the Google Cloud Dataflow service API. * * <p>Uses only constant memory. */ public static long computeSerializedSizeBytes(GenericJson object) throws IOException { JsonFactory factory = object.getFactory(); if (factory == null) { factory = Transport.getJsonFactory(); } CountingOutputStream stream = new CountingOutputStream(ByteStreams.nullOutputStream()); JsonGenerator generator = null; try { generator = factory.createJsonGenerator(stream, StandardCharsets.UTF_8); generator.serialize(object); generator.close(); // also closes the stream. } finally { if (generator != null) { generator.close(); } } return stream.getCount(); }
Example #13
Source File: FirebaseUserManager.java From firebase-admin-java with Apache License 2.0 | 6 votes |
String getEmailActionLink(EmailLinkType type, String email, @Nullable ActionCodeSettings settings) throws FirebaseAuthException { ImmutableMap.Builder<String, Object> payload = ImmutableMap.<String, Object>builder() .put("requestType", type.name()) .put("email", email) .put("returnOobLink", true); if (settings != null) { payload.putAll(settings.getProperties()); } GenericJson response = post("/accounts:sendOobCode", payload.build(), GenericJson.class); if (response != null) { String link = (String) response.get("oobLink"); if (!Strings.isNullOrEmpty(link)) { return link; } } throw new FirebaseAuthException(INTERNAL_ERROR, "Failed to create email action link"); }
Example #14
Source File: BaseApiServiceTest.java From connector-sdk with Apache License 2.0 | 6 votes |
@Test public void testIOExceptionRetry() throws Exception { MockLowLevelHttpRequest request = new MockLowLevelHttpRequest("https://www.googleapis.com/mock/v1") { @Override public MockLowLevelHttpResponse execute() throws IOException { throw new IOException("something is wrong"); } }; MockLowLevelHttpRequest retryRequest = buildRequest(200, new GenericJson()); HttpTransport transport = new TestingHttpTransport(ImmutableList.of(request, retryRequest)); TestApiService apiService = new TestApiService.Builder() .setTransport(transport) .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build()) .build(); validateEmptyItem(apiService.get()); }
Example #15
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithCustomToken(String customToken) throws IOException { GenericUrl url = new GenericUrl(VERIFY_CUSTOM_TOKEN_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "token", customToken, "returnSecureToken", true); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example #16
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testGenerateEmailVerificationLink() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( TestUtils.loadResource("generateEmailLink.json")); String link = FirebaseAuth.getInstance() .generateEmailVerificationLinkAsync("[email protected]").get(); assertEquals("https://mock-oob-link.for.auth.tests", link); checkRequestHeaders(interceptor); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals(3, parsed.size()); assertEquals("[email protected]", parsed.get("email")); assertEquals("VERIFY_EMAIL", parsed.get("requestType")); assertTrue((Boolean) parsed.get("returnOobLink")); }
Example #17
Source File: RepositoryContextTest.java From connector-sdk with Apache License 2.0 | 6 votes |
@Test public void invokePostApiOperationAsync_resultIsSet() throws Exception { ListenableFuture<List<GenericJson>> result = Futures.immediateFuture(ImmutableList.of()); doAnswer(invocation -> { AsyncApiOperation asyncApiOperation = invocation.getArgument(0); asyncApiOperation.setResult(result); return null; }).when(mockEventBus).post(any()); ApiOperation apiOperation = ApiOperations.deleteItem(DOC_ID); ListenableFuture<List<GenericJson>> res = repositoryContext.postApiOperationAsync(apiOperation); ArgumentCaptor<AsyncApiOperation> argumentCaptor = ArgumentCaptor.forClass(AsyncApiOperation.class); verify(mockEventBus).post(argumentCaptor.capture()); assertSame(argumentCaptor.getValue().getOperation(), apiOperation); assertSame(result.get(), res.get()); }
Example #18
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testSetCustomAttributes() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( TestUtils.loadResource("createUser.json")); // should not throw ImmutableMap<String, Object> claims = ImmutableMap.<String, Object>of( "admin", true, "package", "gold"); FirebaseAuth.getInstance().setCustomUserClaimsAsync("testuser", claims).get(); checkRequestHeaders(interceptor); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals("testuser", parsed.get("localId")); assertEquals(jsonFactory.toString(claims), parsed.get("customAttributes")); }
Example #19
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithPassword(String email, String password) throws IOException { GenericUrl url = new GenericUrl(VERIFY_PASSWORD_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "email", email, "password", password, "returnSecureToken", true); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example #20
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Test public void testGeneratePasswordResetLinkWithSettings() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( TestUtils.loadResource("generateEmailLink.json")); String link = FirebaseAuth.getInstance() .generatePasswordResetLinkAsync("[email protected]", ACTION_CODE_SETTINGS).get(); assertEquals("https://mock-oob-link.for.auth.tests", link); checkRequestHeaders(interceptor); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals(3 + ACTION_CODE_SETTINGS_MAP.size(), parsed.size()); assertEquals("[email protected]", parsed.get("email")); assertEquals("PASSWORD_RESET", parsed.get("requestType")); assertTrue((Boolean) parsed.get("returnOobLink")); for (Map.Entry<String, Object> entry : ACTION_CODE_SETTINGS_MAP.entrySet()) { assertEquals(entry.getValue(), parsed.get(entry.getKey())); } }
Example #21
Source File: TopicManagementResponse.java From firebase-admin-java with Apache License 2.0 | 6 votes |
TopicManagementResponse(List<GenericJson> results) { checkArgument(results != null && !results.isEmpty(), "unexpected response from topic management service"); int successCount = 0; ImmutableList.Builder<Error> errors = ImmutableList.builder(); for (int i = 0; i < results.size(); i++) { Map result = results.get(i); if (result.isEmpty()) { successCount++; } else { errors.add(new Error(i, (String) result.get("error"))); } } this.successCount = successCount; this.errors = errors.build(); }
Example #22
Source File: FirebaseUserManagerTest.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@Test public void testImportUsersError() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( TestUtils.loadResource("importUsersError.json")); ImportUserRecord user1 = ImportUserRecord.builder() .setUid("user1") .build(); ImportUserRecord user2 = ImportUserRecord.builder() .setUid("user2") .build(); ImportUserRecord user3 = ImportUserRecord.builder() .setUid("user3") .build(); List<ImportUserRecord> users = ImmutableList.of(user1, user2, user3); UserImportResult result = FirebaseAuth.getInstance().importUsersAsync(users, null).get(); checkRequestHeaders(interceptor); assertEquals(1, result.getSuccessCount()); assertEquals(2, result.getFailureCount()); assertEquals(2, result.getErrors().size()); ErrorInfo error = result.getErrors().get(0); assertEquals(0, error.getIndex()); assertEquals("Some error occurred in user1", error.getReason()); error = result.getErrors().get(1); assertEquals(2, error.getIndex()); assertEquals("Another error occurred in user3", error.getReason()); ByteArrayOutputStream out = new ByteArrayOutputStream(); interceptor.getResponse().getRequest().getContent().writeTo(out); JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); GenericJson parsed = jsonFactory.fromString(new String(out.toByteArray()), GenericJson.class); assertEquals(1, parsed.size()); List<Map<String, Object>> expected = ImmutableList.of( user1.getProperties(jsonFactory), user2.getProperties(jsonFactory), user3.getProperties(jsonFactory) ); assertEquals(expected, parsed.get("users")); }
Example #23
Source File: OicSecurityRealm.java From oic-auth-plugin with MIT License | 5 votes |
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException { GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo); if(LOGGER.isLoggable(Level.FINEST)) { StringBuilder grantedAuthoritiesAsString = new StringBuilder("("); for(GrantedAuthority grantedAuthority : grantedAuthorities) { grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority()); } grantedAuthoritiesAsString.append(" )"); LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities); SecurityContextHolder.getContext().setAuthentication(token); User user = User.get(token.getName()); // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object. user.addProperty(new OicUserProperty(userName, grantedAuthorities)); if(emailFieldName!=null) { String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName); if (email != null) { user.addProperty(new Mailer.UserProperty(email)); } } if(fullNameFieldName!=null) { String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName); if (fullName != null) { user.setFullName(fullName); } } OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities); SecurityListener.fireAuthenticated(userDetails); return token; }
Example #24
Source File: CoreSocketFactoryTest.java From cloud-sql-jdbc-socket-factory with Apache License 2.0 | 5 votes |
private static GoogleJsonResponseException fakeGoogleJsonResponseException( int status, ErrorInfo errorInfo, String message) throws IOException { final JsonFactory jsonFactory = new JacksonFactory(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { errorInfo.setFactory(jsonFactory); GoogleJsonError jsonError = new GoogleJsonError(); jsonError.setCode(status); jsonError.setErrors(Collections.singletonList(errorInfo)); jsonError.setMessage(message); jsonError.setFactory(jsonFactory); GenericJson errorResponse = new GenericJson(); errorResponse.set("error", jsonError); errorResponse.setFactory(jsonFactory); return new MockLowLevelHttpRequest() .setResponse( new MockLowLevelHttpResponse() .setContent(errorResponse.toPrettyString()) .setContentType(Json.MEDIA_TYPE) .setStatusCode(status)); } }; HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); return GoogleJsonResponseException.from(jsonFactory, response); }
Example #25
Source File: PackageUtilTest.java From beam with Apache License 2.0 | 5 votes |
/** Builds a fake GoogleJsonResponseException for testing API error handling. */ private static GoogleJsonResponseException googleJsonResponseException( final int status, final String reason, final String message) throws IOException { final JsonFactory jsonFactory = new JacksonFactory(); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { ErrorInfo errorInfo = new ErrorInfo(); errorInfo.setReason(reason); errorInfo.setMessage(message); errorInfo.setFactory(jsonFactory); GenericJson error = new GenericJson(); error.set("code", status); error.set("errors", Arrays.asList(errorInfo)); error.setFactory(jsonFactory); GenericJson errorResponse = new GenericJson(); errorResponse.set("error", error); errorResponse.setFactory(jsonFactory); return new MockLowLevelHttpRequest() .setResponse( new MockLowLevelHttpResponse() .setContent(errorResponse.toPrettyString()) .setContentType(Json.MEDIA_TYPE) .setStatusCode(status)); } }; HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); return GoogleJsonResponseException.from(jsonFactory, response); }
Example #26
Source File: FirebaseUserManager.java From firebase-admin-java with Apache License 2.0 | 5 votes |
String createUser(CreateRequest request) throws FirebaseAuthException { GenericJson response = post( "/accounts", request.getProperties(), GenericJson.class); if (response != null) { String uid = (String) response.get("localId"); if (!Strings.isNullOrEmpty(uid)) { return uid; } } throw new FirebaseAuthException(INTERNAL_ERROR, "Failed to create new user"); }
Example #27
Source File: TestingHttpTransport.java From connector-sdk with Apache License 2.0 | 5 votes |
/** * Add a request/response pair for simulated {@link IndexingService#poll(PollItemsRequest)} * command. * * * @param sourceId source ID * @param response the desired returned response */ public void addPollItemReqResp(String sourceId, GenericJson response) { String url = new RequestUrlBuilder() .setBaseUrl(DEFAULT_BASE_URL) .setSourceId(sourceId) .setType(TYPE_ITEM + ITEM_POLL) .build(); this.setRequestResponse(METHOD_POST, url, response); }
Example #28
Source File: AbstractJsonParserTest.java From google-http-java-client with Apache License 2.0 | 5 votes |
public void testParse_basic() throws IOException { JsonObjectParser parser = new JsonObjectParser(newJsonFactory()); InputStream inputStream = new ByteArrayInputStream(TEST_JSON.getBytes(StandardCharsets.UTF_8)); GenericJson json = parser.parseAndClose(inputStream, StandardCharsets.UTF_8, GenericJson.class); assertTrue(json.get("strValue") instanceof String); assertEquals("bar", json.get("strValue")); assertTrue(json.get("intValue") instanceof BigDecimal); assertEquals(new BigDecimal(123), json.get("intValue")); assertTrue(json.get("boolValue") instanceof Boolean); assertEquals(Boolean.FALSE, json.get("boolValue")); }
Example #29
Source File: BatchRequestServiceTest.java From connector-sdk with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void testNonRetryableException() throws Exception { when(retryPolicy.isRetryableStatusCode(0)).thenReturn(false); BatchRequestService batchService = setupService(); batchService.startAsync().awaitRunning(); assertTrue(batchService.isRunning()); BatchRequest batchRequest = getMockBatchRequest(); when(batchRequestHelper.createBatch(any())).thenReturn(batchRequest); AsyncRequest<GenericJson> requestToBatch = new AsyncRequest<GenericJson>(testRequest, retryPolicy, operationStats); assertEquals(0, requestToBatch.getRetries()); assertEquals(Status.NEW, requestToBatch.getStatus()); doAnswer( i -> { throw new IOException("Non-retryable exception"); }) .when(batchRequestHelper) .executeBatchRequest(batchRequest); batchService.add(requestToBatch); batchService.flush(); batchService.stopAsync().awaitTerminated(); verify(retryPolicy).isRetryableStatusCode(0); validateFailedResult(requestToBatch.getFuture()); assertEquals(Status.FAILED, requestToBatch.getStatus()); assertEquals(0, requestToBatch.getRetries()); assertFalse(batchService.isRunning()); }
Example #30
Source File: IntegrationTestUtils.java From firebase-admin-java with Apache License 2.0 | 5 votes |
private static synchronized GenericJson ensureServiceAccount() { if (serviceAccount == null) { try (InputStream stream = new FileInputStream(IT_SERVICE_ACCOUNT_PATH)) { serviceAccount = Utils.getDefaultJsonFactory().fromInputStream(stream, GenericJson.class); } catch (IOException e) { String msg = String.format("Failed to read service account certificate from %s. " + "Integration tests require a service account credential obtained from a Firebase " + "project. See CONTRIBUTING.md for more details.", IT_SERVICE_ACCOUNT_PATH); throw new RuntimeException(msg, e); } } return serviceAccount; }