Esempio n. 1
0
  /** Perform appropriate backoff etc. extraction. */
  public void interpretHTTPFailure(HttpResponse response) {
    // TODO: handle permanent rejection.
    long responseBackoff = (new SyncResponse(response)).totalBackoffInMilliseconds();
    if (responseBackoff > 0) {
      callback.requestBackoff(responseBackoff);
    }

    if (response.getStatusLine() != null) {
      final int statusCode = response.getStatusLine().getStatusCode();
      switch (statusCode) {
        case 400:
          SyncStorageResponse storageResponse = new SyncStorageResponse(response);
          this.interpretHTTPBadRequestBody(storageResponse);
          break;

        case 401:
          /*
           * Alert our callback we have a 401 on a cluster URL. This GlobalSession
           * will fail, but the next one will fetch a new cluster URL and will
           * distinguish between "node reassignment" and "user password changed".
           */
          callback.informUnauthorizedResponse(this, config.getClusterURL());
          break;
      }
    }
  }
Esempio n. 2
0
  private String dealWithError(HttpResponse httpResponse) throws WeiboException {

    StatusLine status = httpResponse.getStatusLine();
    int statusCode = status.getStatusCode();

    String result = "";

    if (statusCode != HttpStatus.SC_OK) {

      result = readResult(httpResponse);
      String err = null;
      int errCode = 0;
      try {
        JSONObject json = new JSONObject(result);
        err = json.getString("error");
        errCode = json.getInt("error_code");
        WeiboException exception = new WeiboException();
        exception.setError_code(errCode);
        exception.setOriError(err);
        throw exception;

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

    return result;
  }
 public void process(final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   if (response == null) {
     throw new IllegalArgumentException("HTTP response may not be null.");
   }
   int status = response.getStatusLine().getStatusCode();
   if ((status >= HttpStatus.SC_OK) && !response.containsHeader(HTTP.DATE_HEADER)) {
     String httpdate = DATE_GENERATOR.getCurrentDate();
     response.setHeader(HTTP.DATE_HEADER, httpdate);
   }
 }
Esempio n. 4
0
  private String dealWithResponse(HttpResponse httpResponse) throws WeiboException {

    StatusLine status = httpResponse.getStatusLine();
    int statusCode = status.getStatusCode();

    if (statusCode != HttpStatus.SC_OK) {
      return dealWithError(httpResponse);
    }

    return readResult(httpResponse);
  }
  public Multistatus handleResponse(HttpResponse response) throws SardineException, IOException {
    super.validateResponse(response);

    // Process the response from the server.
    HttpEntity entity = response.getEntity();
    StatusLine statusLine = response.getStatusLine();
    if (entity == null) {
      throw new SardineException(
          "No entity found in response", statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    return this.getMultistatus(entity.getContent());
  }
 @Override
 public void handleHttpResponse(final HttpResponse response) {
   final int status = response.getStatusLine().getStatusCode();
   switch (status) {
     case 200:
     case 201:
       Log.d(LOGTAG, "Telemetry upload success.");
       break;
     default:
       Log.w(LOGTAG, "Telemetry upload failure. HTTP status: " + status);
   }
 }
  @SuppressWarnings("unchecked")
  public ClientResponse execute(ClientRequest request) throws Exception {
    String uri = request.getUri();
    final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
    try {
      loadHttpMethod(request, httpMethod);

      final HttpResponse res = httpClient.execute(httpMethod, httpContext);

      final BaseClientResponse response = new BaseClientResponse(null, this);
      BaseClientResponseStreamFactory sf =
          new BaseClientResponseStreamFactory() {
            InputStream stream;

            public InputStream getInputStream() throws IOException {
              if (stream == null) {
                HttpEntity entity = res.getEntity();
                if (entity == null) return null;
                stream = new SelfExpandingBufferredInputStream(entity.getContent());
              }
              return stream;
            }

            public void performReleaseConnection() {
              // Apache Client 4 is stupid, You have to get the InputStream and close it if there is
              // an entity
              // otherwise the connection is never released. There is, of course, no close() method
              // on response
              // to make this easier.
              try {
                if (stream != null) {
                  stream.close();
                } else {
                  InputStream is = getInputStream();
                  if (is != null) {
                    is.close();
                  }
                }
              } catch (Exception ignore) {
              }
            }
          };
      response.setStreamFactory(sf);
      response.setAttributes(request.getAttributes());
      response.setStatus(res.getStatusLine().getStatusCode());
      response.setHeaders(extractHeaders(res));
      response.setProviderFactory(request.getProviderFactory());
      return response;
    } finally {
      cleanUpAfterExecute(httpMethod);
    }
  }
Esempio n. 8
0
  public static StatusCode logout() {
    HttpResponse logoutResponse =
        Network.getRequest(
            "https://www.geocaching.com/login/default.aspx?RESET=Y&redir=http%3a%2f%2fwww.geocaching.com%2fdefault.aspx%3f");
    String logoutData = Network.getResponseData(logoutResponse);
    if (logoutResponse != null
        && logoutResponse.getStatusLine().getStatusCode() == 503
        && BaseUtils.matches(logoutData, GCConstants.PATTERN_MAINTENANCE)) {
      return StatusCode.MAINTENANCE;
    }

    Cookies.clearCookies();
    Settings.setCookieStore(null);
    return StatusCode.NO_ERROR;
  }
Esempio n. 9
0
 protected SilkHttpResponse performRequest(final HttpUriRequest request) throws SilkHttpException {
   if (mHeaders.size() > 0) {
     for (SilkHttpHeader header : mHeaders) request.setHeader(header.getName(), header.getValue());
   }
   HttpResponse response;
   try {
     response = mClient.execute(request);
   } catch (Exception e) {
     reset();
     throw new SilkHttpException(e);
   }
   int status = response.getStatusLine().getStatusCode();
   if (status != 200) {
     reset();
     throw new SilkHttpException(response);
   }
   reset();
   return new SilkHttpResponse(response);
 }
  // Interface to AsyncHttpRequest
  void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;
    try {
      HttpEntity entity = null;
      HttpEntity temp = response.getEntity();
      if (temp != null) {
        entity = new BufferedHttpEntity(temp);
        responseBody = EntityUtils.toString(entity, "UTF-8");
      }
    } catch (IOException e) {
      sendFailureMessage(e, (String) null);
    }

    if (status.getStatusCode() >= 300) {
      sendFailureMessage(
          new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
          responseBody);
    } else {
      sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
  }
Esempio n. 11
0
  /**
   * Download or refresh the copy of <code>url</code> in <code>file</code>.
   *
   * @param url the url of the document
   * @param file the file to save the document in
   * @return <code>true</code> if the existing file was up-to-date, <code>false</code> otherwise
   */
  private boolean downloadOrRefreshCopy(final String url, final File file) {
    final String absoluteURL = makeAbsoluteURL(url);

    if (absoluteURL != null) {
      try {
        final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file);
        if (httpResponse != null) {
          final int statusCode = httpResponse.getStatusLine().getStatusCode();
          if (statusCode == 200) {
            LocalStorage.saveEntityToFile(httpResponse, file);
          } else if (statusCode == 304) {
            if (!file.setLastModified(System.currentTimeMillis())) {
              makeFreshCopy(file);
            }
            return true;
          }
        }
      } catch (final Exception e) {
        Log.e("HtmlImage.downloadOrRefreshCopy", e);
      }
    }
    return false;
  }
Esempio n. 12
0
  private static StatusCode login(boolean retry) {
    final ImmutablePair<String, String> login = Settings.getLogin();

    if (login == null || StringUtils.isEmpty(login.left) || StringUtils.isEmpty(login.right)) {
      Login.setActualStatus(cgeoapplication.getInstance().getString(R.string.err_login));
      Log.e("Login.login: No login information stored");
      return StatusCode.NO_LOGIN_INFO_STORED;
    }

    Login.setActualStatus(
        cgeoapplication.getInstance().getString(R.string.init_login_popup_working));
    HttpResponse loginResponse =
        Network.getRequest("https://www.geocaching.com/login/default.aspx");
    String loginData = Network.getResponseData(loginResponse);
    if (loginResponse != null
        && loginResponse.getStatusLine().getStatusCode() == 503
        && BaseUtils.matches(loginData, GCConstants.PATTERN_MAINTENANCE)) {
      return StatusCode.MAINTENANCE;
    }

    if (StringUtils.isBlank(loginData)) {
      Log.e("Login.login: Failed to retrieve login page (1st)");
      return StatusCode.CONNECTION_FAILED; // no loginpage
    }

    if (Login.getLoginStatus(loginData)) {
      Log.i(
          "Already logged in Geocaching.com as "
              + login.left
              + " ("
              + Settings.getMemberStatus()
              + ')');
      Login.switchToEnglish(loginData);
      return StatusCode.NO_ERROR; // logged in
    }

    Cookies.clearCookies();
    Settings.setCookieStore(null);

    final Parameters params =
        new Parameters(
            "__EVENTTARGET", "",
            "__EVENTARGUMENT", "",
            "ctl00$ContentBody$tbUsername", login.left,
            "ctl00$ContentBody$tbPassword", login.right,
            "ctl00$ContentBody$cbRememberMe", "on",
            "ctl00$ContentBody$btnSignIn", "Login");
    final String[] viewstates = Login.getViewstates(loginData);
    if (isEmpty(viewstates)) {
      Log.e("Login.login: Failed to find viewstates");
      return StatusCode.LOGIN_PARSE_ERROR; // no viewstates
    }
    Login.putViewstates(params, viewstates);

    loginResponse = Network.postRequest("https://www.geocaching.com/login/default.aspx", params);
    loginData = Network.getResponseData(loginResponse);

    if (StringUtils.isBlank(loginData)) {
      Log.e("Login.login: Failed to retrieve login page (2nd)");
      // FIXME: should it be CONNECTION_FAILED to match the first attempt?
      return StatusCode.COMMUNICATION_ERROR; // no login page
    }

    if (Login.getLoginStatus(loginData)) {
      Log.i(
          "Successfully logged in Geocaching.com as "
              + login.left
              + " ("
              + Settings.getMemberStatus()
              + ')');

      Login.switchToEnglish(loginData);
      Settings.setCookieStore(Cookies.dumpCookieStore());

      return StatusCode.NO_ERROR; // logged in
    }

    if (loginData.contains("Your username/password combination does not match.")) {
      Log.i(
          "Failed to log in Geocaching.com as "
              + login.left
              + " because of wrong username/password");
      return StatusCode.WRONG_LOGIN_DATA; // wrong login
    }

    Log.i("Failed to log in Geocaching.com as " + login.left + " for some unknown reason");
    if (retry) {
      Login.switchToEnglish(loginData);
      return login(false);
    }

    return StatusCode.UNKNOWN_ERROR; // can't login
  }