michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0:
michael@0: package org.mozilla.gecko.sync.net;
michael@0:
michael@0: import java.io.BufferedReader;
michael@0: import java.io.IOException;
michael@0: import java.io.InputStream;
michael@0: import java.io.InputStreamReader;
michael@0: import java.io.Reader;
michael@0: import java.util.Scanner;
michael@0:
michael@0: import org.json.simple.parser.ParseException;
michael@0: import org.mozilla.gecko.background.common.log.Logger;
michael@0: import org.mozilla.gecko.sync.ExtendedJSONObject;
michael@0: import org.mozilla.gecko.sync.NonObjectJSONException;
michael@0: import org.mozilla.gecko.sync.Utils;
michael@0:
michael@0: import ch.boye.httpclientandroidlib.Header;
michael@0: import ch.boye.httpclientandroidlib.HttpEntity;
michael@0: import ch.boye.httpclientandroidlib.HttpResponse;
michael@0: import ch.boye.httpclientandroidlib.impl.cookie.DateParseException;
michael@0: import ch.boye.httpclientandroidlib.impl.cookie.DateUtils;
michael@0:
michael@0: public class SyncResponse {
michael@0: private static final String HEADER_RETRY_AFTER = "retry-after";
michael@0: private static final String LOG_TAG = "SyncResponse";
michael@0:
michael@0: protected HttpResponse response;
michael@0:
michael@0: public SyncResponse() {
michael@0: super();
michael@0: }
michael@0:
michael@0: public SyncResponse(HttpResponse res) {
michael@0: response = res;
michael@0: }
michael@0:
michael@0: public HttpResponse httpResponse() {
michael@0: return this.response;
michael@0: }
michael@0:
michael@0: public int getStatusCode() {
michael@0: return this.response.getStatusLine().getStatusCode();
michael@0: }
michael@0:
michael@0: public boolean wasSuccessful() {
michael@0: return this.getStatusCode() == 200;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Fetch the content type of the HTTP response body.
michael@0: *
michael@0: * @return a Header
instance, or null
if there was
michael@0: * no body or no valid Content-Type.
michael@0: */
michael@0: public Header getContentType() {
michael@0: HttpEntity entity = this.response.getEntity();
michael@0: if (entity == null) {
michael@0: return null;
michael@0: }
michael@0: return entity.getContentType();
michael@0: }
michael@0:
michael@0: private String body = null;
michael@0: public String body() throws IllegalStateException, IOException {
michael@0: if (body != null) {
michael@0: return body;
michael@0: }
michael@0: InputStreamReader is = new InputStreamReader(this.response.getEntity().getContent());
michael@0: // Oh, Java, you are so evil.
michael@0: body = new Scanner(is).useDelimiter("\\A").next();
michael@0: return body;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Return the body as a non-null ExtendedJSONObject
.
michael@0: *
michael@0: * @return A non-null ExtendedJSONObject
.
michael@0: *
michael@0: * @throws IllegalStateException
michael@0: * @throws IOException
michael@0: * @throws ParseException
michael@0: * @throws NonObjectJSONException
michael@0: */
michael@0: public ExtendedJSONObject jsonObjectBody() throws IllegalStateException,
michael@0: IOException, ParseException,
michael@0: NonObjectJSONException {
michael@0: if (body != null) {
michael@0: // Do it from the cached String.
michael@0: return ExtendedJSONObject.parseJSONObject(body);
michael@0: }
michael@0:
michael@0: HttpEntity entity = this.response.getEntity();
michael@0: if (entity == null) {
michael@0: throw new IOException("no entity");
michael@0: }
michael@0:
michael@0: InputStream content = entity.getContent();
michael@0: try {
michael@0: Reader in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
michael@0: return ExtendedJSONObject.parseJSONObject(in);
michael@0: } finally {
michael@0: content.close();
michael@0: }
michael@0: }
michael@0:
michael@0: private boolean hasHeader(String h) {
michael@0: return this.response.containsHeader(h);
michael@0: }
michael@0:
michael@0: private static boolean missingHeader(String value) {
michael@0: return value == null ||
michael@0: value.trim().length() == 0;
michael@0: }
michael@0:
michael@0: private int getIntegerHeader(String h) throws NumberFormatException {
michael@0: if (this.hasHeader(h)) {
michael@0: Header header = this.response.getFirstHeader(h);
michael@0: String value = header.getValue();
michael@0: if (missingHeader(value)) {
michael@0: Logger.warn(LOG_TAG, h + " header present but empty.");
michael@0: return -1;
michael@0: }
michael@0: return Integer.parseInt(value, 10);
michael@0: }
michael@0: return -1;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @return A number of seconds, or -1 if the 'Retry-After' header was not present.
michael@0: */
michael@0: public int retryAfterInSeconds() throws NumberFormatException {
michael@0: if (!this.hasHeader(HEADER_RETRY_AFTER)) {
michael@0: return -1;
michael@0: }
michael@0:
michael@0: Header header = this.response.getFirstHeader(HEADER_RETRY_AFTER);
michael@0: String retryAfter = header.getValue();
michael@0: if (missingHeader(retryAfter)) {
michael@0: Logger.warn(LOG_TAG, "Retry-After header present but empty.");
michael@0: return -1;
michael@0: }
michael@0:
michael@0: try {
michael@0: return Integer.parseInt(retryAfter, 10);
michael@0: } catch (NumberFormatException e) {
michael@0: // Fall through to try date format.
michael@0: }
michael@0:
michael@0: try {
michael@0: final long then = DateUtils.parseDate(retryAfter).getTime();
michael@0: final long now = System.currentTimeMillis();
michael@0: return (int)((then - now) / 1000); // Convert milliseconds to seconds.
michael@0: } catch (DateParseException e) {
michael@0: Logger.warn(LOG_TAG, "Retry-After header neither integer nor date: " + retryAfter);
michael@0: return -1;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * @return A number of seconds, or -1 if the 'X-Backoff' header was not
michael@0: * present.
michael@0: */
michael@0: public int backoffInSeconds() throws NumberFormatException {
michael@0: return this.getIntegerHeader("x-backoff");
michael@0: }
michael@0:
michael@0: /**
michael@0: * @return A number of seconds, or -1 if the 'X-Weave-Backoff' header was not
michael@0: * present.
michael@0: */
michael@0: public int weaveBackoffInSeconds() throws NumberFormatException {
michael@0: return this.getIntegerHeader("x-weave-backoff");
michael@0: }
michael@0:
michael@0: /**
michael@0: * Extract a number of seconds, or -1 if none of the specified headers were present.
michael@0: *
michael@0: * @param includeRetryAfter
michael@0: * if true
, the Retry-After header is excluded. This is
michael@0: * useful for processing non-error responses where a Retry-After
michael@0: * header would be unexpected.
michael@0: * @return the maximum of the three possible backoff headers, in seconds.
michael@0: */
michael@0: public int totalBackoffInSeconds(boolean includeRetryAfter) {
michael@0: int retryAfterInSeconds = -1;
michael@0: if (includeRetryAfter) {
michael@0: try {
michael@0: retryAfterInSeconds = retryAfterInSeconds();
michael@0: } catch (NumberFormatException e) {
michael@0: }
michael@0: }
michael@0:
michael@0: int weaveBackoffInSeconds = -1;
michael@0: try {
michael@0: weaveBackoffInSeconds = weaveBackoffInSeconds();
michael@0: } catch (NumberFormatException e) {
michael@0: }
michael@0:
michael@0: int backoffInSeconds = -1;
michael@0: try {
michael@0: backoffInSeconds = backoffInSeconds();
michael@0: } catch (NumberFormatException e) {
michael@0: }
michael@0:
michael@0: int totalBackoff = Math.max(retryAfterInSeconds, Math.max(backoffInSeconds, weaveBackoffInSeconds));
michael@0: if (totalBackoff < 0) {
michael@0: return -1;
michael@0: } else {
michael@0: return totalBackoff;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * @return A number of milliseconds, or -1 if neither the 'Retry-After',
michael@0: * 'X-Backoff', or 'X-Weave-Backoff' header were present.
michael@0: */
michael@0: public long totalBackoffInMilliseconds() {
michael@0: long totalBackoff = totalBackoffInSeconds(true);
michael@0: if (totalBackoff < 0) {
michael@0: return -1;
michael@0: } else {
michael@0: return 1000 * totalBackoff;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * The timestamp returned from a Sync server is a decimal number of seconds,
michael@0: * e.g., 1323393518.04.
michael@0: *
michael@0: * We want milliseconds since epoch.
michael@0: *
michael@0: * @return milliseconds since the epoch, as a long, or -1 if the header
michael@0: * was missing or invalid.
michael@0: */
michael@0: public long normalizedWeaveTimestamp() {
michael@0: String h = "x-weave-timestamp";
michael@0: if (!this.hasHeader(h)) {
michael@0: return -1;
michael@0: }
michael@0:
michael@0: return Utils.decimalSecondsToMilliseconds(this.response.getFirstHeader(h).getValue());
michael@0: }
michael@0:
michael@0: public int weaveRecords() throws NumberFormatException {
michael@0: return this.getIntegerHeader("x-weave-records");
michael@0: }
michael@0:
michael@0: public int weaveQuotaRemaining() throws NumberFormatException {
michael@0: return this.getIntegerHeader("x-weave-quota-remaining");
michael@0: }
michael@0:
michael@0: public String weaveAlert() {
michael@0: if (this.hasHeader("x-weave-alert")) {
michael@0: return this.response.getFirstHeader("x-weave-alert").getValue();
michael@0: }
michael@0: return null;
michael@0: }
michael@0: }