Java Code Examples for java.net.httpurlconnection#HTTP_UNAVAILABLE

The following examples show how to use java.net.httpurlconnection#HTTP_UNAVAILABLE . 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: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private ServiceInvocationException getServiceInvocationException(final Throwable error) {

        if (error instanceof ServiceInvocationException) {
            return (ServiceInvocationException) error;
        } else if (error instanceof ReplyException) {
            final ReplyException ex = (ReplyException) error;
            switch (ex.failureType()) {
            case TIMEOUT:
                return new ServerErrorException(
                        HttpURLConnection.HTTP_UNAVAILABLE,
                        "request could not be processed at the moment");
            default:
                return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            return new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    }
 
Example 2
Source File: DefaultSettingsSpiCallTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public void testRequestWasSuccessful_unsuccessfulStatusCodes() {
  // 204 and 205 are considered unsuccessful in this case, and 206 should never happen. Also
  // test with some of the other common status codes (these are ones that our backend has
  // been known to return).
  final int[] statusCodes = {
    HttpURLConnection.HTTP_NO_CONTENT,
    HttpURLConnection.HTTP_RESET,
    HttpURLConnection.HTTP_PARTIAL,
    HttpURLConnection.HTTP_BAD_REQUEST,
    HttpURLConnection.HTTP_UNAUTHORIZED,
    HttpURLConnection.HTTP_FORBIDDEN,
    HttpURLConnection.HTTP_NOT_FOUND,
    HttpURLConnection.HTTP_NOT_ACCEPTABLE,
    HttpURLConnection.HTTP_INTERNAL_ERROR,
    HttpURLConnection.HTTP_BAD_GATEWAY,
    HttpURLConnection.HTTP_UNAVAILABLE,
    HttpURLConnection.HTTP_GATEWAY_TIMEOUT
  };
  for (int statusCode : statusCodes) {
    assertFalse(defaultSettingsSpiCall.requestWasSuccessful(statusCode));
  }
}
 
Example 3
Source File: HonoSaslAuthenticator.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private SaslOutcome getSaslOutcomeForErrorStatus(final int status) {
    final SaslOutcome saslOutcome;
    switch (status) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            // failed due to an authentication error
            saslOutcome = SaslOutcome.PN_SASL_AUTH;
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            // failed due to a system error
            saslOutcome = SaslOutcome.PN_SASL_SYS;
            break;
        case HttpURLConnection.HTTP_UNAVAILABLE:
            // failed due to a transient error
            saslOutcome = SaslOutcome.PN_SASL_TEMP;
            break;
        default:
            if (status >= 400 && status < 500) {
                // client error
                saslOutcome = SaslOutcome.PN_SASL_PERM;
            } else {
                saslOutcome = SaslOutcome.PN_SASL_TEMP;
            }
    }
    return saslOutcome;
}
 
Example 4
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private static MqttConnectReturnCode getConnectReturnCode(final Throwable e) {

        if (e instanceof MqttConnectionException) {
            return ((MqttConnectionException) e).code();
        } else if (e instanceof ServiceInvocationException) {
            switch (((ServiceInvocationException) e).getErrorCode()) {
            case HttpURLConnection.HTTP_UNAUTHORIZED:
            case HttpURLConnection.HTTP_NOT_FOUND:
                return MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;
            case HttpURLConnection.HTTP_UNAVAILABLE:
                return MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE;
            default:
                return MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED;
            }
        } else {
            return MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED;
        }
    }
 
Example 5
Source File: ProtocolAdapterCommandConsumerFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that an attempt to open a command consumer fails if the peer
 * rejects to open a receiver link.
 *
 * @param ctx The test context.
 */
@Test
public void testCreateCommandConsumerFailsIfPeerRejectsLink(final VertxTestContext ctx) {

    final Handler<CommandContext> commandHandler = VertxMockSupport.mockHandler();
    final ServerErrorException ex = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE);
    when(connection.createReceiver(
            anyString(),
            any(ProtonQoS.class),
            any(ProtonMessageHandler.class),
            anyInt(),
            anyBoolean(),
            VertxMockSupport.anyHandler()))
    .thenReturn(Future.failedFuture(ex));

    commandConsumerFactory.createCommandConsumer(tenantId, deviceId, commandHandler, null, null)
        .onComplete(ctx.failing(t -> {
            ctx.verify(() -> assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE));
            ctx.completeNow();
        }));
}
 
Example 6
Source File: HTTPResultMapper.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
default int getSuggestedHTTPStatusCode() {
	switch (getResult()) {
	case OK:
	case WARNING:
		return HttpURLConnection.HTTP_OK;
	case UNKNOWN:
	default:
	case UNAVAILABLE:
	case ERROR:
	case CRITICAL:
	case MAINTENANCE:
		return HttpURLConnection.HTTP_UNAVAILABLE;
	}
}
 
Example 7
Source File: OsmApiErrorFactoryTest.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testError()
{
	for(int i = 0; i < 600; ++i)
	{
		RuntimeException e = OsmApiErrorFactory.createError(i, "test", "description");
		
		if(i >= 400 && i < 500) assertTrue(e instanceof OsmApiException);
		else assertTrue(e instanceof OsmConnectionException);
		
		switch(i)
		{
			case HttpURLConnection.HTTP_UNAVAILABLE:
				assertTrue(e instanceof OsmServiceUnavailableException);
				break;
			case HttpURLConnection.HTTP_NOT_FOUND:
			case HttpURLConnection.HTTP_GONE:
				assertTrue(e instanceof OsmNotFoundException);
				break;
			case HttpURLConnection.HTTP_FORBIDDEN:
				assertTrue(e instanceof OsmAuthorizationException);
				break;
			case HttpURLConnection.HTTP_CONFLICT:
				assertTrue(e instanceof OsmConflictException);
				break;
			case HttpURLConnection.HTTP_BAD_REQUEST:
				assertTrue(e instanceof OsmBadUserInputException);
				break;
		}
	}
}
 
Example 8
Source File: X509AuthHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the handler returns the status code conveyed in a
 * failed Tenant service invocation in the response.
 *
 * @param ctx The vert.x test context.
 * @throws SSLPeerUnverifiedException if the client certificate cannot be determined.
 */
@Test
public void testHandleFailsWithStatusCodeFromAuthProvider(final VertxTestContext ctx) throws SSLPeerUnverifiedException {

    // GIVEN an auth handler configured with an auth provider that
    // fails with a 503 error code during authentication
    final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE);
    when(clientAuth.validateClientCertificate(any(Certificate[].class), (SpanContext) any())).thenReturn(Future.failedFuture(error));

    // WHEN trying to authenticate a request that contains a client certificate
    final X509Certificate clientCert = getClientCertificate("CN=device", "CN=tenant");
    final SSLSession sslSession = mock(SSLSession.class);
    when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { clientCert });

    final MqttEndpoint endpoint = mock(MqttEndpoint.class);
    when(endpoint.isSsl()).thenReturn(true);
    when(endpoint.sslSession()).thenReturn(sslSession);

    final MqttContext context = MqttContext.fromConnectPacket(endpoint);
    authHandler.authenticateDevice(context)
        // THEN the request context is failed with the 503 error code
        .onComplete(ctx.failing(t -> {
            ctx.verify(() -> {
                assertThat(t).isEqualTo(error);
            });
            ctx.completeNow();
        }));
}
 
Example 9
Source File: HonoConnectionImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void failConnectionAttempt(final Throwable connectionFailureCause, final Handler<AsyncResult<HonoConnection>> connectionHandler) {

        log.info("stopping connection attempt to server [{}:{}, role: {}] due to terminal error",
                connectionFactory.getHost(),
                connectionFactory.getPort(),
                connectionFactory.getServerRole(),
                connectionFailureCause);

        final ServiceInvocationException serviceInvocationException;
        if (connectionFailureCause == null) {
            serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                    "failed to connect");
        } else if (connectionFailureCause instanceof AuthenticationException) {
            // wrong credentials?
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                    "failed to authenticate with server");
        } else if (connectionFailureCause instanceof MechanismMismatchException) {
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                    "no suitable SASL mechanism found for authentication with server");
        } else if (connectionFailureCause instanceof SSLException) {
            serviceInvocationException = new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                    "TLS handshake with server failed: " + connectionFailureCause.getMessage(), connectionFailureCause);
        } else {
            serviceInvocationException = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                    "failed to connect", connectionFailureCause);
        }
        connectionHandler.handle(Future.failedFuture(serviceInvocationException));
    }
 
Example 10
Source File: AvaticaHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public byte[] send(byte[] request) {
  // TODO back-off policy?
  while (true) {
    try {
      final HttpURLConnection connection = openConnection();
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);
      try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
        wr.write(request);
        wr.flush();
        wr.close();
      }
      final int responseCode = connection.getResponseCode();
      final InputStream inputStream;
      if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        // Could be sitting behind a load-balancer, try again.
        continue;
      } else if (responseCode != HttpURLConnection.HTTP_OK) {
        inputStream = connection.getErrorStream();
        if (inputStream == null) {
          // HTTP Transport exception that resulted in no content coming back
          throw new RuntimeException("Failed to read data from the server: HTTP/" + responseCode);
        }
      } else {
        inputStream = connection.getInputStream();
      }
      return AvaticaUtils.readFullyToBytes(inputStream);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 11
Source File: CheckUtil.java    From cloudflare-scrape-Android with MIT License 5 votes vote down vote up
private void getVisitCookie(String url, String ua) throws IOException {
    URL connUrl = new URL(url);
    mGetMainConn = (HttpURLConnection) connUrl.openConnection();
    mGetMainConn.setRequestMethod("GET");
    mGetMainConn.setConnectTimeout(CONN_TIMEOUT);
    mGetMainConn.setReadTimeout(CONN_TIMEOUT);
    mGetMainConn.setRequestProperty("user-agent",ua);
    mGetMainConn.setRequestProperty("accept",ACCEPT);
    mGetMainConn.setRequestProperty("referer", url);
    if (mCookieList!=null&&mCookieList.size()>0){
        mGetMainConn.setRequestProperty("cookie", ConvertUtil.listToString(mCookieList));
    }
    mGetMainConn.setUseCaches(false);
    mGetMainConn.connect();
    switch (mGetMainConn.getResponseCode()){
        case HttpURLConnection.HTTP_OK:
            if (mCookieList == null || mCookieList.size() == 0){
                mCookieList = mCookieManager.getCookieStore().getCookies();
                checkCookie(mCookieList);
            }
            canVisit = true;
            break;
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            hasNewUrl = true;
            break;
        case HttpURLConnection.HTTP_FORBIDDEN:
        case HttpURLConnection.HTTP_UNAVAILABLE:
            break;
        default:
            LogUtil.e("MainUrl","UnCatch Http code: "+mGetMainConn.getResponseCode());
            break;
    }
}
 
Example 12
Source File: PaymentsAPIResponseTest.java    From amazon-pay-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrottledRequest() throws Exception {
    final String rawResponse = loadTestFile("Throttled.xml");
    final ResponseData response = new ResponseData(HttpURLConnection.HTTP_UNAVAILABLE, rawResponse);
    try {
        Parser.marshalXML(ErrorResponse.class, response);
        Assert.fail();
    } catch (AmazonServiceException e) {
        Assert.assertEquals(e.getResponseXml(), rawResponse);
        Assert.assertEquals(e.getStatusCode(), HttpURLConnection.HTTP_UNAVAILABLE);
        Assert.assertEquals(e.getErrorCode(), "RequestThrottled");
        Assert.assertEquals(e.getRequestId(), "d702fd8e-206f-4da4-95e0-1e7422474077");
    }
}
 
Example 13
Source File: HonoBasicAuthHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the handler returns the status code conveyed in a
 * failed {@code AuthProvider} invocation in the response.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleFailsWithStatusCodeFromAuthProvider() {

    // GIVEN an auth handler configured with an auth provider that
    // fails with a 503 error code during authentication
    final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE);
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture(error));
        return null;
    }).when(authProvider).authenticate(any(JsonObject.class), any(Handler.class));

    // WHEN trying to authenticate a request using the HTTP BASIC scheme
    final String authorization = new StringBuffer()
            .append("BASIC ")
            .append(Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8)))
            .toString();
    final MultiMap headers = mock(MultiMap.class);
    when(headers.get(eq(HttpHeaders.AUTHORIZATION))).thenReturn(authorization);
    final HttpServerRequest req = mock(HttpServerRequest.class);
    when(req.headers()).thenReturn(headers);
    final HttpServerResponse resp = mock(HttpServerResponse.class);
    final RoutingContext ctx = mock(RoutingContext.class);
    when(ctx.request()).thenReturn(req);
    when(ctx.response()).thenReturn(resp);
    authHandler.handle(ctx);

    // THEN the request context is failed with the 503 error code
    verify(ctx).fail(error);
}
 
Example 14
Source File: HttpTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void sendUpdate(List<SDCMetricsJson> sdcMetricsJsonList) throws StageException {
  int delaySecs = 1;
  int attempts = 0;
  while (attempts < retryAttempts || retryAttempts == -1) {
    if (attempts > 0) {
      delaySecs = delaySecs * 2;
      delaySecs = Math.min(delaySecs, 60);
      LOG.warn("Post attempt '{}', waiting for '{}' seconds before retrying ...",
        attempts, delaySecs);
      StatsUtil.sleep(delaySecs);
    }
    attempts++;
    Response response = null;
    try {
      response = target.request()
        .header(SSOConstants.X_REST_CALL, SSOConstants.SDC_COMPONENT_NAME)
        .header(SSOConstants.X_APP_AUTH_TOKEN, sdcAuthToken.replaceAll("(\\r|\\n)", ""))
        .header(SSOConstants.X_APP_COMPONENT_ID, sdcId)
        .post(
          Entity.json(
            sdcMetricsJsonList
          )
        );
      if (response.getStatus() == HttpURLConnection.HTTP_OK) {
        return;
      } else if (response.getStatus() == HttpURLConnection.HTTP_UNAVAILABLE) {
        LOG.warn("Error writing to time-series app: DPM unavailable");
        // retry
      } else if (response.getStatus() == HttpURLConnection.HTTP_FORBIDDEN) {
        // no retry in this case
        String errorResponseMessage = response.readEntity(String.class);
        LOG.error(Utils.format(Errors.HTTP_02.getMessage(), errorResponseMessage));
        throw new StageException(Errors.HTTP_02, errorResponseMessage);
      } else {
        String responseMessage = response.readEntity(String.class);
        LOG.error(Utils.format(Errors.HTTP_02.getMessage(), responseMessage));
        //retry
      }
    } catch (Exception ex) {
      LOG.error(Utils.format(Errors.HTTP_02.getMessage(), ex.toString(), ex));
      // retry
    } finally {
      if (response != null) {
        response.close();
      }
    }
  }
  // no success after retry
  throw new StageException(Errors.HTTP_03, retryAttempts);
}
 
Example 15
Source File: Sentry.java    From Sentry-Android with MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 16
Source File: Cloudflare.java    From cloudflare-scrape-Android with MIT License 4 votes vote down vote up
private void getVisitCookie() throws IOException, InterruptedException {
    ConnUrl = new URL(mUrl);
    mGetMainConn = (HttpURLConnection) ConnUrl.openConnection();
    mGetMainConn.setRequestMethod("GET");
    mGetMainConn.setConnectTimeout(CONN_TIMEOUT);
    mGetMainConn.setReadTimeout(CONN_TIMEOUT);
    if (!TextUtils.isEmpty(mUser_agent)){
        mGetMainConn.setRequestProperty("user-agent",mUser_agent);
    }
    mGetMainConn.setRequestProperty("accept",ACCEPT);
    mGetMainConn.setRequestProperty("referer", mUrl);
    if (mCookieList!=null&&mCookieList.size()>0){
        mGetMainConn.setRequestProperty("cookie",listToString(mCookieList));
    }
    mGetMainConn.setUseCaches(false);
    mGetMainConn.connect();
    switch (mGetMainConn.getResponseCode()){
        case HttpURLConnection.HTTP_OK:
            e("MainUrl","visit website success");
            mCookieList = mCookieManager.getCookieStore().getCookies();
            checkCookie(mCookieList);
            return;
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            hasNewUrl = true;
            mUrl = mGetMainConn.getHeaderField("Location");
            mCookieList = mCookieManager.getCookieStore().getCookies();
            checkCookie(mCookieList);
            e("MainUrl","HTTP 301 :"+mUrl);
            return;
        case HttpURLConnection.HTTP_FORBIDDEN:
            e("MainUrl","IP block or cookie err");
            return;
        case HttpURLConnection.HTTP_UNAVAILABLE:
            InputStream mInputStream = mCheckConn.getErrorStream();
            BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = mBufferedReader.readLine()) != null){
                sb.append(str);
            }
            mInputStream.close();
            mBufferedReader.close();
            mCookieList = mCookieManager.getCookieStore().getCookies();
            str = sb.toString();
            getCheckAnswer(str);
            break;
        default:
            e("MainUrl","UnCatch Http code: "+mGetMainConn.getHeaderField("Location"));
            break;
    }
}
 
Example 17
Source File: StorageException.java    From azure-storage-android with Apache License 2.0 4 votes vote down vote up
/**
 * Translates the specified HTTP status code into a storage exception.
 * 
 * @param statusCode
 *            The HTTP status code returned by the operation.
 * @param statusDescription
 *            A <code>String</code> that represents the status description.
 * @param inner
 *            An <code>Exception</code> object that represents a reference to the initial exception, if one exists.
 * 
 * @return A <code>StorageException</code> object that represents translated exception.
 **/
protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription,
        final Exception inner) {
    String errorCode;
    switch (statusCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        errorCode = StorageErrorCode.ACCESS_DENIED.toString();
        break;
    case HttpURLConnection.HTTP_GONE:
    case HttpURLConnection.HTTP_NOT_FOUND:
        errorCode = StorageErrorCode.RESOURCE_NOT_FOUND.toString();
        break;
    case 416:
    case HttpURLConnection.HTTP_BAD_REQUEST:
        // 416: RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection
        errorCode = StorageErrorCode.BAD_REQUEST.toString();
        break;

    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_NOT_MODIFIED:
        errorCode = StorageErrorCode.CONDITION_FAILED.toString();
        break;

    case HttpURLConnection.HTTP_CONFLICT:
        errorCode = StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString();
        break;

    case HttpURLConnection.HTTP_UNAVAILABLE:
        errorCode = StorageErrorCode.SERVER_BUSY.toString();
        break;

    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        errorCode = StorageErrorCode.SERVICE_TIMEOUT.toString();
        break;

    case HttpURLConnection.HTTP_INTERNAL_ERROR:
        errorCode = StorageErrorCode.SERVICE_INTERNAL_ERROR.toString();
        break;

    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
        errorCode = StorageErrorCode.NOT_IMPLEMENTED.toString();
        break;

    case HttpURLConnection.HTTP_BAD_GATEWAY:
        errorCode = StorageErrorCode.BAD_GATEWAY.toString();
        break;

    case HttpURLConnection.HTTP_VERSION:
        errorCode = StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString();
        break;
    default:
        errorCode = null;
    }

    if (errorCode == null) {
        return null;
    } else {
        return new StorageException(errorCode, statusDescription, statusCode, null, inner);
    }
}
 
Example 18
Source File: AggregatedMetricsFetcher.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public MetricRegistryJson fetchLatestAggregatedMetrics(
    PipelineConfiguration pipelineConfiguration,
    RuleDefinitionsJson ruleDefJson,
    List<Stage.ConfigIssue> issues
) {
  // fetch last persisted metrics for the following counters, timers, meters and histograms
  MetricRegistryJson metricRegistryJson = buildMetricRegistryJson(pipelineConfiguration, ruleDefJson);

  client = ClientBuilder.newBuilder().build();
  client.register(new CsrfProtectionFilter("CSRF"));
  client.register(GZipEncoder.class);
  target = client.target(targetUrl);
  Entity<MetricRegistryJson> metricRegistryJsonEntity = Entity.json(metricRegistryJson);
  String errorResponseMessage = null;
  int delaySecs = 1;
  int attempts = 0;

  // Wait for a few random seconds before starting the stopwatch
  int waitSeconds = new Random().nextInt(60);
  try {
    Thread.sleep(waitSeconds * 1000);
  } catch (InterruptedException e) {
    // No-op
  }

  while (attempts < retryAttempts || retryAttempts == -1) {
    if (attempts > 0) {
      delaySecs = delaySecs * 2;
      delaySecs = Math.min(delaySecs, 60);
      LOG.warn("DPM fetchLatestAggregatedMetrics attempt '{}', waiting for '{}' seconds before retrying ...",
          attempts, delaySecs);
      StatsUtil.sleep(delaySecs);
    }
    attempts++;

    Response response = null;
    try {
      response = target
          .queryParam("jobId", jobId)
          .queryParam("pipelineId", pipelineId)
          .queryParam("pipelineVersion", pipelineVersion)
          .request()
          .header(SSOConstants.X_REST_CALL, SSOConstants.SDC_COMPONENT_NAME)
          .header(SSOConstants.X_APP_AUTH_TOKEN, authToken.replaceAll("(\\r|\\n)", ""))
          .header(SSOConstants.X_APP_COMPONENT_ID, appComponentId)
          .post(metricRegistryJsonEntity);

      if (response.getStatus() == HttpURLConnection.HTTP_OK) {
        metricRegistryJson = response.readEntity(MetricRegistryJson.class);
        break;
      } else if (response.getStatus() == HttpURLConnection.HTTP_UNAVAILABLE) {
        errorResponseMessage = "Error requesting latest stats from time-series app: DPM unavailable";
        LOG.warn(errorResponseMessage);
        metricRegistryJson = null;
      }  else if (response.getStatus() == HttpURLConnection.HTTP_FORBIDDEN) {
        errorResponseMessage = response.readEntity(String.class);
        LOG.error(Utils.format(Errors.STATS_02.getMessage(), errorResponseMessage));
        metricRegistryJson = null;
        break;
      } else {
        errorResponseMessage = response.readEntity(String.class);
        LOG.warn("Error requesting latest stats from time-series app, HTTP status '{}': {}",
            response.getStatus(), errorResponseMessage);
        metricRegistryJson = null;
      }
    } catch (Exception ex) {
      errorResponseMessage = ex.toString();
      LOG.warn("Error requesting latest stats from time-series app : {}", ex.toString());
      metricRegistryJson = null;
    }  finally {
      if (response != null) {
        response.close();
      }
    }
  }

  if (metricRegistryJson == null) {
    issues.add(
        context.createConfigIssue(
            Groups.STATS.getLabel(),
            "targetUrl",
            Errors.STATS_02,
            errorResponseMessage
        )
    );
  }

  return metricRegistryJson;
}
 
Example 19
Source File: GenieServerUnavailableException.java    From genie with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param msg   human readable message
 * @param cause reason for this exception
 */
public GenieServerUnavailableException(final String msg, final Throwable cause) {
    super(HttpURLConnection.HTTP_UNAVAILABLE, msg, cause);
}
 
Example 20
Source File: GenieServerUnavailableException.java    From genie with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param msg human readable message
 */
public GenieServerUnavailableException(final String msg) {
    super(HttpURLConnection.HTTP_UNAVAILABLE, msg);
}