类com.google.api.client.http.LowLevelHttpResponse源码实例Demo

下面列出了怎么用com.google.api.client.http.LowLevelHttpResponse的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      if (responses.isEmpty()) {
        throw new IOException(
            "Unexpected call to execute(), no injected responses left to return.");
      }
      return responses.remove();
    }
  };
  requests.add(new Request(method, request));
  return request;
}
 
源代码2 项目: endpoints-java   文件: GoogleAuthTest.java
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  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("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
源代码3 项目: copybara   文件: GitTestUtil.java
public static LowLevelHttpRequest mockResponseWithStatus(
    String responseContent, int status, MockRequestAssertion requestValidator) {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      assertWithMessage(
              String.format(
                  "Request <%s> did not match predicate: '%s'",
                  this.getContentAsString(), requestValidator))
          .that(requestValidator.test(this.getContentAsString()))
          .isTrue();
      // Responses contain a IntputStream for content. Cannot be reused between for two
      // consecutive calls. We create new ones per call here.
      return new MockLowLevelHttpResponse()
          .setContentType(Json.MEDIA_TYPE)
          .setContent(responseContent)
          .setStatusCode(status);
    }
  };
}
 
源代码4 项目: copybara   文件: GitHubApiTransportImplTest.java
@Test
public void testPasswordHeaderSet() throws Exception {
  Map<String, List<String>> headers = new HashMap<>();
  httpTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          headers.putAll(this.getHeaders());
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContent("foo");
          return response;
        }
      };
    }
  };
  transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
  transport.get("foo/bar", String.class);
  assertThat(headers).containsEntry("authorization", ImmutableList.of("Basic dXNlcjpTRUNSRVQ="));
}
 
源代码5 项目: copybara   文件: GithubArchiveTest.java
@Test
public void repoExceptionOnDownloadFailure() throws Exception {
  httpTransport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
           MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {
              public LowLevelHttpResponse execute() throws IOException {
                throw new IOException("OH NOES!");
              }
           };
          return request;
        }
      };
  RemoteFileOptions options = new RemoteFileOptions();
  options.transport = () -> new GclientHttpStreamFactory(httpTransport, Duration.ofSeconds(20));
  Console console = new TestingConsole();
  OptionsBuilder optionsBuilder = new OptionsBuilder().setConsole(console);
  optionsBuilder.remoteFile = options;
  skylark = new SkylarkTestExecutor(optionsBuilder);
  ValidationException e = assertThrows(ValidationException.class, () -> skylark.eval("sha256",
      "sha256 = remotefiles.github_archive("
          + "project = 'google/copybara',"
          + "revision='674ac754f91e64a0efb8087e59a176484bd534d1').sha256()"));
  assertThat(e).hasCauseThat().hasCauseThat().hasCauseThat().isInstanceOf(RepoException.class);
}
 
@Test
public void normal() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(200);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  this.task.put(sinkRecords);
}
 
@Test
public void contentLengthTooLarge() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(417);
  when(httpResponse.getContentType()).thenReturn("text/html");
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
@Test
public void invalidToken() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(403);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
@Test
public void invalidIndex() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(400);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
源代码10 项目: beam   文件: BigQueryServicesImplTest.java
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  // Set up the MockHttpRequest for future inspection
  request =
      new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          return response;
        }
      };

  // A mock transport that lets us mock the API responses.
  MockHttpTransport transport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(request).build();

  // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer.
  bigquery =
      new Bigquery.Builder(
              transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer())
          .build();
}
 
源代码11 项目: nomulus   文件: IcannHttpReporterTest.java
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      mockRequest = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(PLAIN_TEXT_UTF_8.toString());
          response.setContent(iirdeaResponse.read());
          return response;
        }
      };
      mockRequest.setUrl(url);
      return mockRequest;
    }
  };
}
 
源代码12 项目: nomulus   文件: DirectoryGroupsConnectionTest.java
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
 
源代码13 项目: java-docs-samples   文件: FirebaseChannelTest.java
@Test
public void firebaseGet() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
 
源代码14 项目: java-docs-samples   文件: FirebaseChannelTest.java
@Test
public void firebaseDelete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
 
源代码15 项目: rides-java-sdk   文件: OAuth2CredentialsTest.java
@Override
public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
    return new MockLowLevelHttpRequest() {

        @Override
        public String getUrl() {
            return url;
        }

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            lastRequestUrl = getUrl();
            lastRequestContent = getContentAsString();

            MockLowLevelHttpResponse mock = new MockLowLevelHttpResponse();
            mock.setStatusCode(httpStatusCode);
            mock.setContent(httpResponseContent);

            return mock;
        }
    };
}
 
源代码16 项目: google-http-java-client   文件: UrlFetchRequest.java
@Override
public LowLevelHttpResponse execute() throws IOException {
  // write content
  if (getStreamingContent() != null) {
    String contentType = getContentType();
    if (contentType != null) {
      addHeader("Content-Type", contentType);
    }
    String contentEncoding = getContentEncoding();
    if (contentEncoding != null) {
      addHeader("Content-Encoding", contentEncoding);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    getStreamingContent().writeTo(out);
    byte[] payload = out.toByteArray();
    if (payload.length != 0) {
      request.setPayload(payload);
    }
  }
  // connect
  URLFetchService service = URLFetchServiceFactory.getURLFetchService();
  HTTPResponse response = service.fetch(request);
  return new UrlFetchResponse(response);
}
 
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
@Test
public void testInterruptedWriteWithResponse() throws Exception {
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)) {
        @Override
        public OutputStream getOutputStream() throws IOException {
          return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              throw new IOException("Error writing request body to server");
            }
          };
        }
      };
  connection.setResponseCode(401);
  connection.setRequestMethod("POST");
  NetHttpRequest request = new NetHttpRequest(connection);
  InputStream is = NetHttpRequestTest.class.getClassLoader().getResourceAsStream("file.txt");
  HttpContent content = new InputStreamContent("text/plain", is);
  request.setStreamingContent(content);

  LowLevelHttpResponse response = request.execute();
  assertEquals(401, response.getStatusCode());
}
 
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  request.setConfig(requestConfig.build());
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
public static HttpResponse fakeResponse(Map<String, Object> headers, InputStream content)
    throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() {
              MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
              headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
              return response.setContent(content);
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  return request.execute();
}
 
public static MockHttpTransport mockTransport(LowLevelHttpResponse... responsesIn) {
  return new MockHttpTransport() {
    int responsesIndex = 0;
    final LowLevelHttpResponse[] responses = responsesIn;

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return responses[responsesIndex++];
        }
      };
    }
  };
}
 
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      MockLowLevelHttpResponse r = new MockLowLevelHttpResponse();
      r.setStatusCode(200);
      r.addHeader("Cache-Control", "max-age=" + MAX_AGE);
      if (useAgeHeader) {
        r.addHeader("Age", String.valueOf(AGE));
      }
      r.setContentType(Json.MEDIA_TYPE);
      r.setContent(TEST_CERTIFICATES);
      return r;
    }
  };
}
 
public void testExecuteUsingHead() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          assertEquals("HEAD", method);
          assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
          return new MockLowLevelHttpResponse();
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.put("testId", "foo");
  request.executeUsingHead();
}
 
public void testExecute_void() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContent("{\"a\":\"ignored\"}")
              .setContentType(Json.MEDIA_TYPE);
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<Void> request =
      new MockGoogleClientRequest<Void>(client, HttpMethods.GET, URI_TEMPLATE, null, Void.class);
  Void v = request.execute();
  assertNull(v);
}
 
public void testReturnRawInputStream_defaultFalse() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  InputStream inputStream = request.executeAsInputStream();
  // The response will be wrapped because of gzip encoding
  assertFalse(inputStream instanceof ByteArrayInputStream);
}
 
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH,
      JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(
      client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      String firstHeader = getFirstHeaderValue(expectedHeader);
      assertTrue(
          String.format(
              "Expected header value to match %s, instead got %s.",
              expectedHeaderValue,
              firstHeader
          ),
          firstHeader.matches(expectedHeaderValue)
      );
      return new MockLowLevelHttpResponse();
    }
  };
}
 
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
源代码29 项目: googleads-java-lib   文件: BatchJobUploaderTest.java
/**
 * Tests that IOExceptions from executing an upload request are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_ioException_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  BatchJobUploadStatus uploadStatus =
      new BatchJobUploadStatus(0, URI.create("http://www.example.com"));
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus);
}
 
源代码30 项目: googleads-java-lib   文件: BatchJobUploaderTest.java
/**
 * Tests that IOExceptions from initiating an upload are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  thrown.expectMessage("initiate upload");
  uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(
      0, URI.create("http://www.example.com")));
}
 
 类方法
 同包方法