Java Code Examples for retrofit.client.Response#getStatus()

The following examples show how to use retrofit.client.Response#getStatus() . 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: ManagementApiUtil.java    From apiman-cli with Apache License 2.0 6 votes vote down vote up
private static void httpError(int expectedStatus, Response response) throws CommandException {
    if (null == response) {
        throw new IllegalArgumentException("Response was null");
    }

    // obtain response body
    String body = null;

    if (null != response.getBody()) {
        try (InputStream errStream = response.getBody().in()) {
            body = CharStreams.toString(new InputStreamReader(errStream));
        } catch (IOException ignored) {
        }
    }

    throw new CommandException("HTTP " + response.getStatus() + " "
            + response.getReason() + " but expected " + expectedStatus + ":\n" + body);
}
 
Example 2
Source File: ApiFactory.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public static String getErrorMessage(Response response) {
    String text = responseToString(response);
    try {
        JSONObject object = new JSONObject(text);
        if (object.has("errors")) {
            JSONArray errors = object.getJSONArray("errors");
            if (errors.length() > 0) {
                JSONObject error = errors.getJSONObject(0);
                if (error.has("message")) {
                    return error.getString("message");
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("Api", "getErrorMessage: "+text );
    }
    if (response.getStatus() > 500) {
        return App.getContext().getString(R.string.check_network);
    }
    return null;
}
 
Example 3
Source File: PipelineInitiator.java    From echo with Apache License 2.0 6 votes vote down vote up
private static boolean isRetryableError(Throwable error) {
  if (!(error instanceof RetrofitError)) {
    return false;
  }
  RetrofitError retrofitError = (RetrofitError) error;

  if (retrofitError.getKind() == Kind.NETWORK) {
    return true;
  }

  if (retrofitError.getKind() == Kind.HTTP) {
    Response response = retrofitError.getResponse();
    return (response != null && response.getStatus() != HttpStatus.BAD_REQUEST.value());
  }

  return false;
}
 
Example 4
Source File: UserFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkUnfollowingRes(Response res) {
    stopMenuLoading();

    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
}
 
Example 5
Source File: BaseService.java    From tilt-game-android with MIT License 5 votes vote down vote up
protected void handleError(RetrofitError error, Intent intent, String broadcast) {
    if (!sAppIdInitialized) {
        throw new Error("Call setApplicationIdPrefix(BuildConfig.APPLICATION_ID) before handling errors");
    }

    Response response = error.getResponse();
    int status = (response == null) ? 0 : response.getStatus();
    ApiErrorVO errorVO = null;
    if (response != null) {
        Header header = getHeaderByName(response.getHeaders(), "Content-Type");
        if (header != null) {
            if (header.getValue().contains("application/json")) {
                try {
                    errorVO = (ApiErrorVO) error.getBodyAs(ApiErrorVO.class);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }
    }

    if (errorVO == null) {
        errorVO = new ApiErrorVO();
    }
    errorVO.setErrorKind(error.getKind());

    Intent broadcastIntent = new Intent(BROADCAST_ERROR);
    broadcastIntent.putExtra(KEY_ORIGINAL_ACTION, TextUtils.isEmpty(broadcast) ? intent.getAction() : broadcast);
    broadcastIntent.putExtra(KEY_API_ERROR_OBJECT, errorVO);
    broadcastIntent.putExtra(KEY_HTTP_STATUS, status);
    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
 
Example 6
Source File: FetchCategoryPage.java    From Mover with Apache License 2.0 5 votes vote down vote up
@Override
public Mover doBackgroundJob() {
    Response response;

    /**
     * NOTES
     *
     * if category page equals empty quotes("") it's means
     * that selected page is category_home page :)
     *
     */

    if(mCategory.equals("") && mPageNumber < 2){
        response = mService.home();
    }else if(mCategory.equals("") && mPageNumber >= 2){
        response = mService.home(mPageNumber);
    }else{
        response = mService.category(mCategory, mPageNumber);
    }

    if(response.getStatus() >= 200 && response.getStatus() <= 300) {

        byte[] data = ((TypedByteArray) response.getBody()).getBytes();
        String htmlSource = new String(data);

        if(mPageNumber > 1){
            return new Mover.PaginatedPage(mCategory, mPageNumber).from(htmlSource);
        }

        return new Mover.CategoryPage(mCategory).from(htmlSource);
    }

    throw RetrofitError.httpError(response.getUrl(), response, null, Response.class);
}
 
Example 7
Source File: NetworkErrorHandler.java    From android-atleap with Apache License 2.0 5 votes vote down vote up
@Override
public Throwable handleError(RetrofitError retrofitError) {
    if (retrofitError.isNetworkError()) {
        Log.w(TAG, "Cannot connect to " + retrofitError.getUrl());
        return new NoNetworkException();
    }


    Response response = retrofitError.getResponse();
    if (response != null) {
        int status = response.getStatus();
        if (status == 401) {
            //throw our own exception about unauthorized access
            Log.w(TAG, "Access in not authorized " + retrofitError.getUrl());
            Context context = AppContext.getContext();
            AuthHelper.reCreateAuthTokenForLastAccountBlocking(context, Constants.ACCOUNT_TYPE, Constants.ACCOUNT_TOKEN_TYPE, null, null, null);
            return new UnauthorizedException("Access in not authorized " + retrofitError.getUrl(), retrofitError);
        } else if (status >= 300) {
            Log.w(TAG, "Error " + String.valueOf(status) + " while accessing " + retrofitError.getUrl());
            return retrofitError;
        }
    }

    int index = ExceptionUtils.indexOfType(retrofitError, ServerErrorException.class);

    if (index >= 0) {
        List<Throwable> errorList = ExceptionUtils.getThrowableList(retrofitError);
        ServerErrorException serverErrorException = (ServerErrorException)errorList.get(index);
        if (serverErrorException instanceof DeveloperErrorException) {
            Log.e(TAG, "Developer error with code" + serverErrorException.getErrorCode(), serverErrorException);
        }
        return serverErrorException;
    }

    return retrofitError;
}
 
Example 8
Source File: ManagementApiServiceImpl.java    From apiman-cli with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void waitForServer(int waitTime) {
    if (waitTime == 0) {
        return;
    }

    LOGGER.info("Waiting {} seconds for server to start...", waitTime);
    final StatusApi apiClient = buildServerApiClient(StatusApi.class);

    final long start = System.currentTimeMillis();
    while (true) {
        if (System.currentTimeMillis() - start > waitTime * 1000) {
            throw new CommandException("Timed out after " + waitTime + " seconds waiting for server to start");
        }

        try {
            final Response response = apiClient.checkStatus();
            if (HttpURLConnection.HTTP_OK == response.getStatus()) {
                LOGGER.info("Server started");
                break;
            }

            Thread.sleep(STATUS_CHECK_INTERVAL);
        } catch (Exception ignored) {
        }
    }
}
 
Example 9
Source File: ApiManager.java    From UPPlatform_Android_SDK with Apache License 2.0 5 votes vote down vote up
@Override public Throwable handleError(RetrofitError cause) {
    Response r = cause.getResponse();
    if (r != null && r.getStatus() == 401) {
        return cause.getCause();
    }
    return cause;
}
 
Example 10
Source File: TeamFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkFollowingRes(Response res) {
    stopMenuLoading();
    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
    TypedInput body = res.getBody();
}
 
Example 11
Source File: TeamFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkUnfollowingRes(Response res) {
    stopMenuLoading();

    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
}
 
Example 12
Source File: TeamFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void updateFollowingStatus(Response response) {
    stopMenuLoading();
    if (response.getStatus() == 204) {
        mIsFollowing = true;
    } else if (response.getStatus() == 404) {
        mIsFollowing = false;
    }

    mFollowMenu.setChecked(mIsFollowing);
    mFollowMenu.setTitle(mIsFollowing ? R.string.action_unfollow : R.string.action_follow);
}
 
Example 13
Source File: ManagementApiUtil.java    From apiman-cli with Apache License 2.0 5 votes vote down vote up
public static void invokeAndCheckResponse(int expectedStatus, Supplier<Response> request) throws CommandException {
    try {
        // invoke the request
        final Response response = request.get();

        // check response code is successful
        if (response.getStatus() != expectedStatus) {
            httpError(expectedStatus, response);
        }

    } catch (RetrofitError e) {
        httpError(expectedStatus, e.getResponse());
    }
}
 
Example 14
Source File: SecuredRestBuilder.java    From mobilecloud-15 with Apache License 2.0 4 votes vote down vote up
/**
 * Every time a method on the client interface is invoked, this method is
 * going to get called. The method checks if the client has previously obtained
 * an OAuth 2.0 bearer token. If not, the method obtains the bearer token by
 * sending a password grant request to the server. 
 * 
 * Once this method has obtained a bearer token, all future invocations will
 * automatically insert the bearer token as the "Authorization" header in 
 * outgoing HTTP requests.
 * 
 */
@Override
public void intercept(RequestFacade request) {
	// If we're not logged in, login and store the authentication token.
	if (!loggedIn) {
		try {
			// This code below programmatically builds an OAuth 2.0 password
			// grant request and sends it to the server. 
			
			// Encode the username and password into the body of the request.
			FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
			to.addField("username", username);
			to.addField("password", password);
			
			// Add the client ID and client secret to the body of the request.
			to.addField("client_id", clientId);
			to.addField("client_secret", clientSecret);
			
			// Indicate that we're using the OAuth Password Grant Flow
			// by adding grant_type=password to the body
			to.addField("grant_type", "password");
			
			// The password grant requires BASIC authentication of the client.
			// In order to do BASIC authentication, we need to concatenate the
			// client_id and client_secret values together with a colon and then
			// Base64 encode them. The final value is added to the request as
			// the "Authorization" header and the value is set to "Basic " 
			// concatenated with the Base64 client_id:client_secret value described
			// above.
			String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes());
			// Add the basic authorization header
			List<Header> headers = new ArrayList<Header>();
			headers.add(new Header("Authorization", "Basic " + base64Auth));

			// Create the actual password grant request using the data above
			Request req = new Request("POST", tokenIssuingEndpoint, headers, to);
			
			// Request the password grant.
			Response resp = client.execute(req);
			
			// Make sure the server responded with 200 OK
			if (resp.getStatus() < 200 || resp.getStatus() > 299) {
				// If not, we probably have bad credentials
				throw new SecuredRestException("Login failure: "
						+ resp.getStatus() + " - " + resp.getReason());
			} else {
				// Extract the string body from the response
		        String body = IOUtils.toString(resp.getBody().in());
				
				// Extract the access_token (bearer token) from the response so that we
		        // can add it to future requests.
				accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString();
				
				// Add the access_token to this request as the "Authorization"
				// header.
				request.addHeader("Authorization", "Bearer " + accessToken);	
				
				// Let future calls know we've already fetched the access token
				loggedIn = true;
			}
		} catch (Exception e) {
			throw new SecuredRestException(e);
		}
	}
	else {
		// Add the access_token that we previously obtained to this request as 
		// the "Authorization" header.
		request.addHeader("Authorization", "Bearer " + accessToken );
	}
}
 
Example 15
Source File: DistributedDeployer.java    From halyard with Apache License 2.0 4 votes vote down vote up
private <T extends Account> Set<Integer> disableOrcaServerGroups(
    AccountDeploymentDetails<T> details,
    SpinnakerRuntimeSettings runtimeSettings,
    DistributedService<Orca, T> orcaService,
    RunningServiceDetails runningOrcaDetails) {
  Map<Integer, List<RunningServiceDetails.Instance>> instances =
      runningOrcaDetails.getInstances();
  List<Integer> existingVersions = new ArrayList<>(instances.keySet());
  existingVersions.sort(Integer::compareTo);

  Map<String, String> disableRequest = new HashMap<>();
  Set<Integer> result = new HashSet<>();
  disableRequest.put("enabled", "false");
  List<Integer> disabledVersions = existingVersions.subList(0, existingVersions.size() - 1);
  for (Integer version : disabledVersions) {
    try {
      for (RunningServiceDetails.Instance instance : instances.get(version)) {
        log.info("Disabling instance " + instance.getId());
        Orca orca =
            orcaService.connectToInstance(
                details, runtimeSettings, orcaService.getService(), instance.getId());
        orca.setInstanceStatusEnabled(disableRequest);
      }
      result.add(version);
    } catch (RetrofitError e) {
      Response response = e.getResponse();
      if (response == null) {
        log.warn("Unexpected error disabling orca", e);
      } else if (response.getStatus() == 400
          && ((Map) e.getBodyAs(Map.class)).containsKey("discovery")) {
        log.info("Orca instance is managed by eureka");
        result.add(version);
      } else {
        log.warn("Orca version doesn't support explicit disabling of instances", e);
      }
    }
  }

  Set<Integer> unknownVersions =
      disabledVersions.stream().filter(i -> !result.contains(i)).collect(Collectors.toSet());
  if (unknownVersions.size() > 0) {
    log.warn(
        "There are existing orca server groups that cannot be explicitly disabled, we will have to wait for these to drain work");
  }

  return unknownVersions;
}
 
Example 16
Source File: DistributedDeployer.java    From halyard with Apache License 2.0 4 votes vote down vote up
private <T extends Account> void reapRoscoServerGroups(
    AccountDeploymentDetails<T> details,
    SpinnakerRuntimeSettings runtimeSettings,
    DistributedService<Rosco, T> roscoService) {
  if (runtimeSettings
      .getServiceSettings(roscoService.getService())
      .getSkipLifeCycleManagement()) {
    return;
  }

  ServiceSettings roscoSettings = runtimeSettings.getServiceSettings(roscoService.getService());
  Rosco.AllStatus allStatus;

  try {
    Rosco rosco = roscoService.connectToPrimaryService(details, runtimeSettings);
    allStatus = rosco.getAllStatus();
  } catch (RetrofitError e) {
    boolean enabled = roscoSettings.getEnabled() != null && roscoSettings.getEnabled();
    if (enabled) {
      Map<String, String> body = (Map<String, String>) e.getBodyAs(Map.class);
      String message;
      if (body != null) {
        message = body.getOrDefault("message", "no message supplied");
      } else {
        message = "no response body";
      }
      throw new HalException(
          Problem.Severity.FATAL,
          "Rosco is enabled, and no connection to rosco could be established: "
              + e
              + ": "
              + message,
          e);
    }

    Response response = e.getResponse();
    if (response == null) {
      throw new IllegalStateException("Unknown connection failure: " + e, e);
    }

    // 404 when the service couldn't be found, 503 when k8s couldn't establish a connection
    if (response.getStatus() == 404 || response.getStatus() == 503) {
      log.info("Rosco is not enabled, and there are no server groups to reap");
      return;
    } else {
      throw new HalException(
          Problem.Severity.FATAL,
          "Rosco is not enabled, but couldn't be connected to for unknown reason: " + e,
          e);
    }
  }
  RunningServiceDetails roscoDetails =
      roscoService.getRunningServiceDetails(details, runtimeSettings);

  Set<String> activeInstances = new HashSet<>();

  allStatus
      .getInstances()
      .forEach(
          (s, e) -> {
            if (e.getStatus().equals(Rosco.Status.RUNNING)) {
              String[] split = s.split("@");
              if (split.length != 2) {
                log.warn("Unsupported rosco status format");
                return;
              }

              String instanceId = split[1];
              activeInstances.add(instanceId);
            }
          });

  Map<Integer, Integer> executionsByServerGroupVersion = new HashMap<>();

  roscoDetails
      .getInstances()
      .forEach(
          (s, is) -> {
            int count =
                is.stream()
                    .reduce(
                        0, (c, i) -> c + (activeInstances.contains(i) ? 1 : 0), (a, b) -> a + b);
            executionsByServerGroupVersion.put(s, count);
          });

  // Omit the last deployed roscos from being deleted, since they are kept around for rollbacks.
  List<Integer> allRoscos = new ArrayList<>(executionsByServerGroupVersion.keySet());
  allRoscos.sort(Integer::compareTo);

  cleanupServerGroups(
      details, roscoService, roscoSettings, executionsByServerGroupVersion, allRoscos);
}
 
Example 17
Source File: ConnectivityAwareUrlClient.java    From MVPAndroidBootstrap with Apache License 2.0 4 votes vote down vote up
protected void checkResult(Response response) {
    int statusCode = response.getStatus();
    if (statusCode == 404 || statusCode == 400 || statusCode == 500 || statusCode == 403 || statusCode == 401) {
        throw RetrofitError.httpError(response.getUrl(), response, null, null);
    }
}
 
Example 18
Source File: SecuredRestBuilder.java    From mobilecloud-15 with Apache License 2.0 4 votes vote down vote up
/**
 * Every time a method on the client interface is invoked, this method is
 * going to get called. The method checks if the client has previously obtained
 * an OAuth 2.0 bearer token. If not, the method obtains the bearer token by
 * sending a password grant request to the server. 
 * 
 * Once this method has obtained a bearer token, all future invocations will
 * automatically insert the bearer token as the "Authorization" header in 
 * outgoing HTTP requests.
 * 
 */
@Override
public void intercept(RequestFacade request) {
	// If we're not logged in, login and store the authentication token.
	if (!loggedIn) {
		try {
			// This code below programmatically builds an OAuth 2.0 password
			// grant request and sends it to the server. 
			
			// Encode the username and password into the body of the request.
			FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
			to.addField("username", username);
			to.addField("password", password);
			
			// Add the client ID and client secret to the body of the request.
			to.addField("client_id", clientId);
			to.addField("client_secret", clientSecret);
			
			// Indicate that we're using the OAuth Password Grant Flow
			// by adding grant_type=password to the body
			to.addField("grant_type", "password");
			
			// The password grant requires BASIC authentication of the client.
			// In order to do BASIC authentication, we need to concatenate the
			// client_id and client_secret values together with a colon and then
			// Base64 encode them. The final value is added to the request as
			// the "Authorization" header and the value is set to "Basic " 
			// concatenated with the Base64 client_id:client_secret value described
			// above.
			String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes());
			// Add the basic authorization header
			List<Header> headers = new ArrayList<Header>();
			headers.add(new Header("Authorization", "Basic " + base64Auth));

			// Create the actual password grant request using the data above
			Request req = new Request("POST", tokenIssuingEndpoint, headers, to);
			
			// Request the password grant.
			Response resp = client.execute(req);
			
			// Make sure the server responded with 200 OK
			if (resp.getStatus() < 200 || resp.getStatus() > 299) {
				// If not, we probably have bad credentials
				throw new SecuredRestException("Login failure: "
						+ resp.getStatus() + " - " + resp.getReason());
			} else {
				// Extract the string body from the response
		        String body = IOUtils.toString(resp.getBody().in());
				
				// Extract the access_token (bearer token) from the response so that we
		        // can add it to future requests.
				accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString();
				
				// Add the access_token to this request as the "Authorization"
				// header.
				request.addHeader("Authorization", "Bearer " + accessToken);	
				
				// Let future calls know we've already fetched the access token
				loggedIn = true;
			}
		} catch (Exception e) {
			throw new SecuredRestException(e);
		}
	}
	else {
		// Add the access_token that we previously obtained to this request as 
		// the "Authorization" header.
		request.addHeader("Authorization", "Bearer " + accessToken );
	}
}
 
Example 19
Source File: APIException.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static APIException httpError(String url, Response response) {
    String message = response == null ? "" : response.getStatus() + " " + response.getReason();
    return new APIException(message, url, response, Kind.HTTP, null);
}
 
Example 20
Source File: VPNFragment.java    From android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void success(final IPService.Data data, Response response) {
    if(mActivity == null) return;

    if(response != null && response.getStatus() == 200) {
        mShowsConnected = data.connected;
        mDetectedCountry = data.country;

        if(!mShowsConnected && mCurrentVPNState.equals(VpnStatus.ConnectionStatus.LEVEL_CONNECTED)) {
            updateIPData();
            return;
        }

        String location = null;
        if (mShowsConnected) {
            mConnectedCard.setVisibility(View.VISIBLE);
        } else {
            mConnectedCard.setVisibility(View.GONE);
            try {
                Geocoder coder = new Geocoder(mActivity);
                List<Address> addressList;
                if (!data.hasCoordinates()) {
                    addressList = coder.getFromLocationName("Country: " + data.country, 1);
                } else {
                    addressList = coder.getFromLocation(data.getLat(), data.getLng(), 1);
                }
                if (addressList != null && addressList.size() > 0) {
                    Address address = addressList.get(0);
                    if (address.getLocality() == null) {
                        location = address.getCountryName();
                    } else {
                        location = String.format("%s, %s", address.getLocality(), address.getCountryCode());
                    }

                    if (address.hasLatitude() && address.hasLongitude())
                        mCurrentLocation = new LatLng(address.getLatitude(), address.getLongitude());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (location == null && data.country != null) {
            Locale locale = new Locale("", data.country);
            location = locale.getDisplayCountry();
        }

        final String finalLocation = location;

        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mIPText.setText(data.ip);
                mLocationText.setText(finalLocation);
            }
        });

        processServers();
        updateMapLocation();
    }
}