// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * This contains a reader that accesses data using the HttpRequest
 * facility, and thus works only in the web browser.
 */

library http_request_data_reader;

import 'dart:async';
import 'dart:html';
import 'intl_helpers.dart';

class HTTPRequestDataReader implements LocaleDataReader {

  /** The base url from which we read the data. */
  String url;
  HTTPRequestDataReader(this.url);

  Future read(String locale) {
    // TODO(alanknight): Remove this once it's not necessary for Chrome.
    // Without it, the tests will be flaky on Chrome. Issue 11834.
    var someNumber = new DateTime.now().millisecondsSinceEpoch;
    return HttpRequest.getString('$url$locale.json?cacheBlocker=$someNumber');
  }
}

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * This contains a reader that accesses data using the HttpRequest
 * facility, and thus works only in the web browser.
 */

library http_request_data_reader;

import 'dart:async';
import 'dart:html';
import 'intl_helpers.dart';

class HTTPRequestDataReader implements LocaleDataReader {

  /** The base url from which we read the data. */
  String url;
  HTTPRequestDataReader(this.url);

  Future read(String locale) {
    // TODO(alanknight): Remove this once it's not necessary for Chrome.
    // Without it, the tests will be flaky on Chrome. Issue 11834.
    var someNumber = new DateTime.now().millisecondsSinceEpoch;
    var request = new HttpRequest();
    request.timeout = 5000;
    return _getString('$url$locale.json?cacheBlocker=$someNumber', request)
      .then((r) => r.responseText);
  }
  
  /// Read a string with the given request. This is a stripped down copy
  /// of HttpRequest getString, but was the simplest way I could find to 
  /// issue a request with a timeout.
  Future<HttpRequest> _getString(String url, HttpRequest xhr) {
    var completer = new Completer<HttpRequest>();
    xhr.open('GET', url, async: true);
    xhr.onLoad.listen((e) {
      // Note: file:// URIs have status of 0.
      if ((xhr.status >= 200 && xhr.status < 300) ||
          xhr.status == 0 || xhr.status == 304) {
        completer.complete(xhr);
      } else {
        completer.completeError(e);
      }
    });

    xhr.onError.listen(completer.completeError);
    xhr.send();

    return completer.future;
  }
}

Add a timeout on HttpRequestDataReader
Add a timeout on HttpRequestDataReader

BUG=
R=efortuna@google.com

Review URL: https://codereview.chromium.org//347963004

git-svn-id: a8f079e7cfc3a289d8496d7b88aabbd5c45a3053@37711 260f80e4-7a28-3924-810f-c04153c831b5
