Java 类com.google.api.client.http.HttpResponseException 实例源码

项目:firebase-admin-java    文件:FirebaseUserManagerTest.java   
@Test
public void testGetUserUnexpectedHttpError() throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  response.setContent("{\"not\" json}");
  response.setStatusCode(500);
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(response)
      .build();
  FirebaseUserManager userManager = new FirebaseUserManager(gson, transport, credentials);
  try {
    userManager.getUserById("testuser");
    fail("No error thrown for JSON error");
  }  catch (FirebaseAuthException e) {
    assertTrue(e.getCause() instanceof HttpResponseException);
    assertEquals("Unexpected HTTP response with status: 500; body: {\"not\" json}",
        e.getMessage());
    assertEquals(FirebaseUserManager.INTERNAL_ERROR, e.getErrorCode());
  }
}
项目:java-monitoring-client-library    文件:StackdriverWriterTest.java   
@Test
public void registerMetric_fetchesStackdriverDefinition() throws Exception {
  // Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to
  // register a metric that's already been registered, so we fake one here.
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(400);
  httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);

  writer.registerMetric(metric);

  verify(client.projects().metricDescriptors().get("metric")).execute();
}
项目:java-monitoring-client-library    文件:StackdriverWriterTest.java   
@Test
public void registerMetric_rethrowsException() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(404);
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);

  assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
  assertThat(exception.getStatusCode()).isEqualTo(404);
}
项目:java-monitoring-client-library    文件:StackdriverWriterTest.java   
@Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(400);
  httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  when(metricDescriptorGet.execute())
      .thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
  writer.registerMetric(metric);

  TimeSeries timeSeries =
      writer.getEncodedTimeSeries(
          MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L));

  assertThat(timeSeries.getMetric().getLabels()).isEmpty();
}
项目:minikube-build-tools-for-java    文件:ManifestPusherIntegrationTest.java   
@Test
public void testPush_missingBlobs() throws IOException, RegistryException {
  RegistryClient registryClient = new RegistryClient(null, "gcr.io", "distroless/java");
  ManifestTemplate manifestTemplate = registryClient.pullManifest("latest");

  registryClient = new RegistryClient(null, "localhost:5000", "busybox");
  try {
    registryClient.pushManifest((V22ManifestTemplate) manifestTemplate, "latest");
    Assert.fail("Pushing manifest without its BLOBs should fail");

  } catch (RegistryErrorException ex) {
    HttpResponseException httpResponseException = (HttpResponseException) ex.getCause();
    Assert.assertEquals(
        HttpStatusCodes.STATUS_CODE_BAD_REQUEST, httpResponseException.getStatusCode());
  }
}
项目:minikube-build-tools-for-java    文件:BlobCheckerTest.java   
@Test
public void testHandleHttpResponseException() throws IOException, RegistryErrorException {
  HttpResponseException mockHttpResponseException = Mockito.mock(HttpResponseException.class);
  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);

  ErrorResponseTemplate emptyErrorResponseTemplate =
      new ErrorResponseTemplate()
          .addError(new ErrorEntryTemplate(ErrorCodes.BLOB_UNKNOWN.name(), "some message"));
  Mockito.when(mockHttpResponseException.getContent())
      .thenReturn(Blobs.writeToString(JsonTemplateMapper.toBlob(emptyErrorResponseTemplate)));

  BlobDescriptor blobDescriptor =
      testBlobChecker.handleHttpResponseException(mockHttpResponseException);

  Assert.assertNull(blobDescriptor);
}
项目:minikube-build-tools-for-java    文件:BlobCheckerTest.java   
@Test
public void testHandleHttpResponseException_hasOtherErrors()
    throws IOException, RegistryErrorException {
  HttpResponseException mockHttpResponseException = Mockito.mock(HttpResponseException.class);
  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);

  ErrorResponseTemplate emptyErrorResponseTemplate =
      new ErrorResponseTemplate()
          .addError(new ErrorEntryTemplate(ErrorCodes.BLOB_UNKNOWN.name(), "some message"))
          .addError(new ErrorEntryTemplate(ErrorCodes.MANIFEST_UNKNOWN.name(), "some message"));
  Mockito.when(mockHttpResponseException.getContent())
      .thenReturn(Blobs.writeToString(JsonTemplateMapper.toBlob(emptyErrorResponseTemplate)));

  try {
    testBlobChecker.handleHttpResponseException(mockHttpResponseException);
    Assert.fail("Non-BLOB_UNKNOWN errors should not be handled");

  } catch (HttpResponseException ex) {
    Assert.assertEquals(mockHttpResponseException, ex);
  }
}
项目:minikube-build-tools-for-java    文件:BlobCheckerTest.java   
@Test
public void testHandleHttpResponseException_notBlobUnknown()
    throws IOException, RegistryErrorException {
  HttpResponseException mockHttpResponseException = Mockito.mock(HttpResponseException.class);
  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND);

  ErrorResponseTemplate emptyErrorResponseTemplate = new ErrorResponseTemplate();
  Mockito.when(mockHttpResponseException.getContent())
      .thenReturn(Blobs.writeToString(JsonTemplateMapper.toBlob(emptyErrorResponseTemplate)));

  try {
    testBlobChecker.handleHttpResponseException(mockHttpResponseException);
    Assert.fail("Non-BLOB_UNKNOWN errors should not be handled");

  } catch (HttpResponseException ex) {
    Assert.assertEquals(mockHttpResponseException, ex);
  }
}
项目:minikube-build-tools-for-java    文件:AuthenticationMethodRetrieverTest.java   
@Test
public void tsetHandleHttpResponseException_noHeader() throws HttpResponseException {
  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
  Mockito.when(mockHttpResponseException.getHeaders()).thenReturn(mockHeaders);
  Mockito.when(mockHeaders.getAuthenticate()).thenReturn(null);

  try {
    testAuthenticationMethodRetriever.handleHttpResponseException(mockHttpResponseException);
    Assert.fail(
        "Authentication method retriever should fail if 'WWW-Authenticate' header is not found");

  } catch (RegistryErrorException ex) {
    Assert.assertThat(
        ex.getMessage(), CoreMatchers.containsString("'WWW-Authenticate' header not found"));
  }
}
项目:minikube-build-tools-for-java    文件:AuthenticationMethodRetrieverTest.java   
@Test
public void testHandleHttpResponseException_badAuthenticationMethod()
    throws HttpResponseException {
  String authenticationMethod = "bad authentication method";

  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
  Mockito.when(mockHttpResponseException.getHeaders()).thenReturn(mockHeaders);
  Mockito.when(mockHeaders.getAuthenticate()).thenReturn(authenticationMethod);

  try {
    testAuthenticationMethodRetriever.handleHttpResponseException(mockHttpResponseException);
    Assert.fail(
        "Authentication method retriever should fail if 'WWW-Authenticate' header failed to parse");

  } catch (RegistryErrorException ex) {
    Assert.assertThat(
        ex.getMessage(),
        CoreMatchers.containsString(
            "Failed get authentication method from 'WWW-Authenticate' header"));
  }
}
项目:minikube-build-tools-for-java    文件:AuthenticationMethodRetrieverTest.java   
@Test
public void testHandleHttpResponseException_pass()
    throws RegistryErrorException, HttpResponseException, MalformedURLException {
  String authenticationMethod =
      "Bearer realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\"";

  Mockito.when(mockHttpResponseException.getStatusCode())
      .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
  Mockito.when(mockHttpResponseException.getHeaders()).thenReturn(mockHeaders);
  Mockito.when(mockHeaders.getAuthenticate()).thenReturn(authenticationMethod);

  RegistryAuthenticator registryAuthenticator =
      testAuthenticationMethodRetriever.handleHttpResponseException(mockHttpResponseException);

  Assert.assertEquals(
      new URL("https://somerealm?service=someservice&scope=repository:someImageName:pull"),
      registryAuthenticator.getAuthenticationUrl());
}
项目:cyberduck    文件:DriveExceptionMappingService.java   
@Override
public BackgroundException map(final IOException failure) {
    final StringBuilder buffer = new StringBuilder();
    if(failure instanceof GoogleJsonResponseException) {
        final GoogleJsonResponseException error = (GoogleJsonResponseException) failure;
        this.append(buffer, error.getDetails().getMessage());
        switch(error.getDetails().getCode()) {
            case HttpStatus.SC_FORBIDDEN:
                final List<GoogleJsonError.ErrorInfo> errors = error.getDetails().getErrors();
                for(GoogleJsonError.ErrorInfo info : errors) {
                    if("usageLimits".equals(info.getDomain())) {
                        return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(5), failure);
                    }
                }
                break;
        }
    }
    if(failure instanceof HttpResponseException) {
        final HttpResponseException response = (HttpResponseException) failure;
        this.append(buffer, response.getStatusMessage());
        return new HttpResponseExceptionMappingService().map(new org.apache.http.client
                .HttpResponseException(response.getStatusCode(), buffer.toString()));
    }
    return super.map(failure);
}
项目:Xero-Java    文件:XeroClient.java   
/**
 * @deprecated As of xero-java-sdk version 0.6.0, to be removed
 * in favour of {@link XeroExceptionHandler#convertException(IOException)}
 */
protected RuntimeException convertException(IOException ioe) {
    if (ioe instanceof HttpResponseException) {
        HttpResponseException googleException = (HttpResponseException) ioe;

        if (googleException.getStatusCode() == 400 ||
            googleException.getStatusCode() == 401 ||
            googleException.getStatusCode() == 404 ||
            googleException.getStatusCode() == 500 ||
            googleException.getStatusCode() == 503) {
            return newApiException(googleException);
        } else {
            return newApiException(googleException);
        }
    }
    return new RuntimeException(ioe);
}
项目:Xero-Java    文件:OAuthAccessToken.java   
public boolean execute() throws IOException {
  try {
    HttpResponse response = request.execute();

    isSuccess = response.isSuccessStatusCode();

    if (isSuccess) {
      Map<String, String> oauthKeys = getQueryMap(response.parseAsString());

      this.token = oauthKeys.get("oauth_token");
      this.tokenSecret = oauthKeys.get("oauth_token_secret");
      this.sessionHandle = oauthKeys.get("oauth_session_handle");
      this.tokenTimestamp = System.currentTimeMillis() / 1000l;
      isSuccess = true;
    } else {

    }
  } catch (HttpResponseException e) {

    Map<String, String> oauthError = getQueryMap(e.getMessage());
    this.problem = oauthError.get("oauth_problem");
    this.advice = oauthError.get("oauth_problem_advice");
    isSuccess = false;
  }
  return isSuccess;
}
项目:Xero-Java    文件:XeroExceptionHandler.java   
/**
 * For backwards comparability with xero-java-sdk version 0.6.0 keep the old way of handling exceptions
 *
 * @param ioe exception to convert
 * @return the converted exception
 */
public XeroApiException convertException(IOException ioe) {
    if (ioe instanceof HttpResponseException) {
        HttpResponseException httpResponseException = (HttpResponseException) ioe;
        if (httpResponseException.getStatusCode() == 400) {
            return handleBadRequest(httpResponseException);
        } else if (httpResponseException.getStatusCode() == 401 ||
            httpResponseException.getStatusCode() == 404 ||
            httpResponseException.getStatusCode() == 500 ||
            httpResponseException.getStatusCode() == 503) {
            return newApiException(httpResponseException);
        } else {
            return newApiException(httpResponseException);
        }
    }
    throw new XeroClientException(ioe.getMessage(), ioe);
}
项目:TaskApp    文件:GtasksInvoker.java   
private synchronized void handleException(IOException e) throws IOException {
    Timber.e(e, e.getMessage());
    if (e instanceof HttpResponseException) {
        HttpResponseException h = (HttpResponseException) e;
        int statusCode = h.getStatusCode();
        if (statusCode == 401 || statusCode == 403) {
            accountManager.clearToken(credential);
        } else if (statusCode == 400 || statusCode == 500) {
            throw h;
        } else if (statusCode == 404) {
            throw new HttpNotFoundException(h);
        } else {
            Timber.e(e, "%s: %s", statusCode, h.getStatusMessage());
        }
        // 503 errors are generally either 1) quota limit reached or 2) problems on Google's end
    }
}
项目:styx    文件:KubernetesGCPServiceAccountSecretManagerTest.java   
@Test
public void shouldHandleTooManyKeysCreated() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);

  final GoogleJsonResponseException resourceExhausted = new GoogleJsonResponseException(
      new HttpResponseException.Builder(429, "RESOURCE_EXHAUSTED", new HttpHeaders()),
      new GoogleJsonError().set("status", "RESOURCE_EXHAUSTED"));

  doThrow(resourceExhausted).when(serviceAccountKeyManager).createJsonKey(any());
  doThrow(resourceExhausted).when(serviceAccountKeyManager).createP12Key(any());

  exception.expect(InvalidExecutionException.class);
  exception.expectMessage("Maximum number of keys on service account reached: " + SERVICE_ACCOUNT);

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
项目:cloud-sql-jdbc-socket-factory    文件:SslSocketFactoryTest.java   
@Test
public void create_adminApiNotEnabled() throws IOException {
  ErrorInfo error = new ErrorInfo();
  error.setReason(SslSocketFactory.ADMIN_API_NOT_ENABLED_REASON);
  GoogleJsonError details = new GoogleJsonError();
  details.setErrors(ImmutableList.of(error));
  when(adminApiInstancesGet.execute())
      .thenThrow(
          new GoogleJsonResponseException(
              new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
              details));

  SslSocketFactory sslSocketFactory =
      new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
  try {
    sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
    fail("Expected RuntimeException");
  } catch (RuntimeException e) {
    // TODO(berezv): should we throw something more specific than RuntimeException?
    assertThat(e.getMessage()).contains("Cloud SQL API is not enabled");
  }
}
项目:cloud-sql-jdbc-socket-factory    文件:SslSocketFactoryTest.java   
@Test
public void create_notAuthorizedToGetInstance() throws IOException {
  ErrorInfo error = new ErrorInfo();
  error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON);
  GoogleJsonError details = new GoogleJsonError();
  details.setErrors(ImmutableList.of(error));
  when(adminApiInstancesGet.execute())
      .thenThrow(
          new GoogleJsonResponseException(
              new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
              details));

  SslSocketFactory sslSocketFactory =
      new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
  try {
    sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
    fail("Expected RuntimeException");
  } catch (RuntimeException e) {
    // TODO(berezv): should we throw something more specific than RuntimeException?
    assertThat(e.getMessage()).contains("not authorized");
  }
}
项目:cloud-sql-jdbc-socket-factory    文件:SslSocketFactoryTest.java   
@Test
public void create_notAuthorizedToCreateEphemeralCertificate() throws IOException {
  ErrorInfo error = new ErrorInfo();
  error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON);
  GoogleJsonError details = new GoogleJsonError();
  details.setErrors(ImmutableList.of(error));
  when(adminApiSslCertsCreateEphemeral.execute())
      .thenThrow(
          new GoogleJsonResponseException(
              new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
              details));

  SslSocketFactory sslSocketFactory =
      new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
  try {
    sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
    fail();
  } catch (RuntimeException e) {
    // TODO(berezv): should we throw something more specific than RuntimeException?
    assertThat(e.getMessage()).contains("Unable to obtain ephemeral certificate");
  }
}
项目:jenkins-deployment-manager-plugin    文件:TemplatedCloudDeploymentTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  this.workspace = new FilePath(PathUtils.makeTempDir(dir, "the", "workspace"));
  this.configFilePath = workspace.child(CONFIG_FILE);
  this.importPaths = ImmutableList.of(workspace.child(TestFixture.IMPORT_PATH_1),
      workspace.child(TestFixture.IMPORT_PATH_2));

  // TODO: Add some values for testing
  this.environment = new EnvVars();

  when(credentials.getId()).thenReturn(ROBOT_ID);
  when(credentials.getProjectId()).thenReturn(PROJECT_ID);
  SystemCredentialsProvider.getInstance().getCredentials().add(credentials);

  notFoundException = new NotFoundException();

  executorException = new ExecutorException() {};

  forbiddenJsonException =
      new HttpResponseException.Builder(STATUS_CODE_FORBIDDEN, STATUS_MESSAGE, headers).build();
}
项目:beam    文件:RetryHttpRequestInitializerTest.java   
/**
 * Tests that a non-retriable error is not retried.
 */
@Test
public void testErrorCodeForbidden() throws IOException {
  when(mockLowLevelRequest.execute())
      .thenReturn(mockLowLevelResponse);
  when(mockLowLevelResponse.getStatusCode())
      .thenReturn(403)  // Non-retryable error.
      .thenReturn(200); // Shouldn't happen.

  try {
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
  } catch (HttpResponseException e) {
    assertThat(e.getMessage(), Matchers.containsString("403"));
  }

  verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
  verify(mockLowLevelRequest, atLeastOnce())
      .addHeader(anyString(), anyString());
  verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
  verify(mockLowLevelRequest).execute();
  verify(mockLowLevelResponse).getStatusCode();
  expectedLogs.verifyWarn("Request failed with code 403");
}
项目:gaso    文件:GooglePlaces.java   
public Station getStationDetails(Station station) throws Exception {
    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory
                .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("reference", station.getReference());
        request.getUrl().put("sensor", "false");

        String place = request.execute().parseAsString();

        return parser.stationFromJson(station, place);

    } catch (HttpResponseException e) {
        Log.e("ErrorDetails", e.getMessage());
        throw e;
    }
}
项目:java-asana    文件:AsanaError.java   
public static AsanaError mapException(HttpResponseException exception) throws AsanaError {
    switch (exception.getStatusCode()) {
        case ForbiddenError.STATUS:
            return new ForbiddenError(exception);
        case InvalidRequestError.STATUS:
            return new InvalidRequestError(exception);
        case InvalidTokenError.STATUS:
            return new InvalidTokenError(exception);
        case NoAuthorizationError.STATUS:
            return new NoAuthorizationError(exception);
        case NotFoundError.STATUS:
            return new NotFoundError(exception);
        case RateLimitEnforcedError.STATUS:
            return new RateLimitEnforcedError(exception);
        case ServerError.STATUS:
            return new ServerError(exception);
        default:
            return new AsanaError(exception.getStatusMessage(), exception.getStatusCode(), exception);
    }
}
项目:providence    文件:HttpClientHandlerNetworkTest.java   
@Test
public void testBrokenPipe_NetHttpTransport() throws Failure {
    HttpRequestFactory factory = new NetHttpTransport().createRequestFactory();

    TestService.Iface client = new TestService.Client(new HttpClientHandler(
            this::endpoint, factory, provider));

    try {
        // The request must be larger than the socket read buffer, to force it to fail the write to socket.
        client.test(new Request(Strings.times("request ", 1024 * 1024)));
        fail("No exception");
    } catch (HttpResponseException e) {
        fail("When did this become a HttpResponseException?");
    } catch (IOException ex) {
        // TODO: This should be a HttpResponseException
        assertThat(ex.getMessage(), is("Error writing request body to server"));
    }
}
项目:providence    文件:HttpClientHandlerTest.java   
@Test
public void testSimpleRequest_404_notFound() throws IOException, Failure, TException {
    TestService.Iface client = new TestService.Client(new HttpClientHandler(
            this::notfound, factory(), provider, instrumentation));

    try {
        client.test(new Request("request"));
        fail("No exception");
    } catch (HttpResponseException ex) {
        assertThat(ex.getStatusCode(), is(404));
        assertThat(ex.getStatusMessage(), is("Not Found"));
    }

    verify(instrumentation).onTransportException(any(HttpResponseException.class), anyDouble(), any(PServiceCall.class), isNull());
    verifyNoMoreInteractions(impl, instrumentation);
}
项目:providence    文件:HttpClientHandlerTest.java   
@Test
public void testSimpleRequest_405_notSupported() throws IOException, Failure, TException {
    GenericUrl url = endpoint();
    url.setRawPath("/does_not_exists");
    TestService.Iface client = new TestService.Client(new HttpClientHandler(
            () -> url, factory(), provider, instrumentation));

    try {
        client.test(new Request("request"));
        fail("No exception");
    } catch (HttpResponseException ex) {
        assertThat(ex.getStatusCode(), is(405));
        assertThat(ex.getStatusMessage(), is("HTTP method POST is not supported by this URL"));
    }

    verify(instrumentation).onTransportException(any(HttpResponseException.class), anyDouble(), any(PServiceCall.class), isNull());
    verifyNoMoreInteractions(impl, instrumentation);
}
项目:bitbucket-api-client-java    文件:ClientTest.java   
@Test
public void testGetService() throws IOException {
    Client client = new Client();
    Service service1 = client.getService();
    assertNotNull(service1);
    assertFalse(service1.isAuthenticated());
    assertNull(service1.getCurrentUser());

    client.setUser(USER);
    client.setPassword(PASSWORD);
    Service service2 = client.getService();
    assertNotNull(service2);
    assertFalse(service2.isAuthenticated());
    try {
        BitbucketUser currentUser = service2.getCurrentUser();
        assertNotNull(currentUser);
    } catch (HttpResponseException exception) {
        // Expected.
        assertEquals(401, exception.getStatusCode());
    }
}
项目:SwissKnightMinecraft    文件:Downloader.java   
public void download(int projectID, int fileID) throws IOException {
    GenericUrl projectURL = new GenericUrl("http://minecraft.curseforge.com/projects/" + projectID);
    HttpRequest projectRequest = requestFactory.buildGetRequest(projectURL);
    // This will redirect - the point of this is just to obtain the new URL!
    HttpResponse projectResponse = projectRequest.execute();
    projectResponse.disconnect();

    GenericUrl newURL = projectResponse.getRequest().getUrl();
    newURL.appendRawPath("/files/" + fileID + "/download");
    try {
        download(newURL);
    } catch (HttpResponseException e) {
        // TODO Return this, instead of only logging
        log("FAILED to download "+ newURL + "; you should manually download another version of this mod from " + projectURL);
    }
}
项目:SLAMon    文件:HttpGetHandlerTest.java   
@Test
public void testHttpError() throws Exception {
    handler.requestFactory = new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    return new MockLowLevelHttpResponse().setStatusCode(500);
                }
            };
        }
    }.createRequestFactory();
    Map<String, Object> map = new HashMap<>();
    map.put("url", "http://url.to.be.tested");
    expectedException.expect(HttpResponseException.class);
    Map<String, Object> result = handler.execute(map);
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }
}
项目:GeoNote    文件:GooglePlaces.java   
public PlaceDetails getPlaceDetails(Place place) throws Exception {
    try {
        System.out.println("Perform Place Detail....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));

        request.getUrl().put("key", this.apiKey);
        request.getUrl().put("reference", place.reference);
        request.getUrl().put("sensor", "false");

        if (PRINT_AS_STRING) {
            System.out.println(request.execute().parseAsString());
        } else {
            PlaceDetails placeDetails = request.execute().parseAs(PlaceDetails.class);
            System.out.println(placeDetails);
            return placeDetails;
        }

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }

    return null;
}
项目:google-storage-plugin    文件:RetryStorageOperation.java   
/**
 * Keeps performing actions until credentials expire. When they do, calls
 * initCredentials() and continues. It relies on the RepeatOperation to keep
 * any state required to start where it left off.
 *
 * HttpResponseException with the code Unauthorized is caught. Any other
 * exceptions are passed through.
 *
 * @param a Operation to execute
 * @param retries How many times to attempt to refresh credentials if there is
 * no progress. (Every time an action successfully completes, the retry budget
 * is reset)
 * @param <Ex> An action-specific exception that might be throwns.
 */
public static <Ex extends Throwable> void
performRequestWithReinitCredentials(RepeatOperation<Ex> a, int retries)
    throws IOException, InterruptedException, ExecutorException, Ex {
  int budget = retries;
  do {
    a.initCredentials();
    try {
      while (a.moreWork()) {
        a.act();
        budget = retries;
      }
    } catch (HttpResponseException e) {
      if (budget > 0 && e.getStatusCode() == STATUS_CODE_UNAUTHORIZED) {
        logger.fine("Remote credentials expired, retrying.");
        budget--;
      } else {
        throw new IOException(Messages.AbstractUpload_ExceptionFileUpload(),
            e);
      }
    }
    // Other exceptions are raised further for the client to deal with
  } while (a.moreWork());
}
项目:bigdata-interop    文件:RetryDeterminerTest.java   
HttpResponseException makeHttpException(int status) throws IOException {
  MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
  MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
  resp.setStatusCode(status);
  builder.setLowLevelHttpResponse(resp);
  try {
    HttpResponse res =
        builder.build()
            .createRequestFactory()
            .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
            .execute();
    return new HttpResponseException(res);
  } catch (HttpResponseException exception) {
    return exception; // Throws the exception we want anyway, so just return it.
  }
}
项目:kork    文件:StackdriverWriter.java   
/**
 * Helper function for logging time series errors in more detail.
 *
 * @see #findProblematicTimeSeriesElement
 */
private void handleTimeSeriesResponseException(
     HttpResponseException rex, String msg, List<TimeSeries> nextN) {
  Matcher matcher = INVALID_LABEL_REGEX.matcher(rex.getContent());
  TimeSeries ts = null;
  String label = null;
  if (matcher.find()) {
    int tsIndex = Integer.parseInt(matcher.group(1));
    ts = nextN.get(tsIndex);
    label = matcher.group(2);
    log.error("{}:  time series element: {}",
              rex.getMessage(), ts.toString());
    cache.addLabel(ts.getMetric().getType(), label);
    try {
      log.info("Retrying individual time series element");
      CreateTimeSeriesRequest tsRequest = new CreateTimeSeriesRequest();
      tsRequest.setTimeSeries(nextN.subList(tsIndex, tsIndex + 1));
      service.projects().timeSeries().create(projectResourceName, tsRequest)
          .execute();
    } catch (IOException ioex) {
      log.error("Retry failed with " + ioex);
    }
  } else {
    log.error("Caught HttpResponseException {}", msg, rex);
  }
}
项目:google-oauth-plugin    文件:ExecutorTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  notFoundJsonException = new HttpResponseException.Builder(
      STATUS_CODE_NOT_FOUND, STATUS_MESSAGE, headers).build();
  conflictJsonException = new HttpResponseException.Builder(
      409 /* STATUS_CODE_CONFLICT */, STATUS_MESSAGE, headers).build();
  forbiddenJsonException = new HttpResponseException.Builder(
      STATUS_CODE_FORBIDDEN, STATUS_MESSAGE, headers).build();
  errorJsonException = new HttpResponseException.Builder(
      STATUS_CODE_SERVER_ERROR, STATUS_MESSAGE, headers).build();

  timeoutException = new SocketTimeoutException(STATUS_MESSAGE);

  underTest = new Executor.Default() {
      @Override
      public void sleep() {
        // Don't really sleep...
      }
    };
}
项目:rva    文件:RiseRemoteServiceServlet.java   
private void handleResourceException(HttpResponseException e) throws ServiceFailedException {
    if (isDevelopmentMode) {
        System.out.printf("Status: %s %s", e.getStatusCode(), 
                e.getStatusMessage());
        System.out.println();
    }

    if (e.getStatusCode() >= 500) {
        log.severe(e.getStatusCode() + " - " + e.getStatusMessage());
    }
    else {
        log.warning(e.getStatusCode() + " - " + e.getStatusMessage());
    }

    throw new ServiceFailedException(e.getStatusCode());
}
项目:appengine-gcs-client    文件:URLFetchUtilsTest.java   
@Test
public void testDescribeRequestAndResponseForApiClient() throws Exception {
  HttpRequestInitializer initializer = mock(HttpRequestInitializer.class);
  NetHttpTransport transport = new NetHttpTransport();
  Storage storage = new Storage.Builder(transport, new JacksonFactory(), initializer)
      .setApplicationName("bla").build();
  HttpRequest request = storage.objects().delete("bucket", "object").buildHttpRequest();
  request.getHeaders().clear();
  request.getHeaders().put("k1", "v1");
  request.getHeaders().put("k2", "v2");
  HttpResponseException exception = null;
  try {
    request.execute();
  } catch (HttpResponseException ex) {
    exception = ex;
  }
  String expected = "Request: DELETE " + Storage.DEFAULT_BASE_URL + "b/bucket/o/object\n"
      + "k1: v1\nk2: v2\n\nno content\n\nResponse: 40";
  String result =
      URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), exception);
  assertTrue(expected + "\nis not a prefix of:\n" + result, result.startsWith(expected));
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }
}
项目:GeoNote    文件:GooglePlaces.java   
public PlaceDetails getPlaceDetails(Place place) throws Exception {
    try {
        System.out.println("Perform Place Detail....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));

        request.getUrl().put("key", this.apiKey);
        request.getUrl().put("reference", place.reference);
        request.getUrl().put("sensor", "false");

        if (PRINT_AS_STRING) {
            System.out.println(request.execute().parseAsString());
        } else {
            PlaceDetails placeDetails = request.execute().parseAs(PlaceDetails.class);
            System.out.println(placeDetails);
            return placeDetails;
        }

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }

    return null;
}