Commit 62729979 authored by Conley Owens's avatar Conley Owens Committed by Commit Bot

physicalweb: Remove Physical Web Service

This change removes all references to the Physical Web Service.

BUG=826540

Change-Id: I75a85182798073648dc0f5356b4373dddb54a662
Reviewed-on: https://chromium-review.googlesource.com/1040353Reviewed-by: default avatarMatt Reynolds <mattreynolds@chromium.org>
Reviewed-by: default avatarTommy Nyquist <nyquist@chromium.org>
Reviewed-by: default avatarCait Phillips <caitkp@chromium.org>
Commit-Queue: Conley Owens <cco3@chromium.org>
Cr-Commit-Position: refs/heads/master@{#557584}
parent 35bab68a
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
/**
* A class that represents an HTTP request for an image.
* The response is a Bitmap.
*/
class BitmapHttpRequest extends HttpRequest<Bitmap> {
/**
* Construct a bitmap HTTP request.
* @param url The url to make this HTTP request to.
* @param userAgent The string to set as the User-Agent request header.
* @param acceptLanguage The string to set as the Accept-Language request header.
* @param callback The callback run when the HTTP response is received.
* The callback can be called with a null bitmap if the image
* couldn't be decoded.
* @throws MalformedURLException on invalid url
*/
public BitmapHttpRequest(String url, String userAgent, String acceptLanguage,
RequestCallback callback)
throws MalformedURLException {
super(url, userAgent, acceptLanguage, callback);
}
/**
* The callback that gets run after the request is made.
*/
public interface RequestCallback extends HttpRequest.HttpRequestCallback<Bitmap> {}
/**
* Helper method to make an HTTP request.
* @param urlConnection The HTTP connection.
*/
@Override
public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException {}
/**
* Helper method to read an HTTP response.
* @param is The InputStream.
* @return The decoded image.
*/
@Override
protected Bitmap readInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
byte[] bitmapData = os.toByteArray();
return BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
}
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import org.chromium.base.ThreadUtils;
import org.chromium.chrome.browser.UrlConstants;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* This class represents an HTTP request.
* This is to be used as a base class for more specific request classes.
* @param <T> The type representing the request payload.
*/
abstract class HttpRequest<T> implements Runnable {
// HTTP request header field names
private static final String USER_AGENT_HEADER_NAME = "User-Agent";
private static final String ACCEPT_LANGUAGE_HEADER_NAME = "Accept-Language";
private final URL mUrl;
private final String mUserAgent;
private final String mAcceptLanguage;
private final HttpRequestCallback<T> mCallback;
/**
* Construct a Request object.
* @param url The URL to make an HTTP request to.
* @param userAgent The string to set as the User-Agent request header.
* @param acceptLanguage The string to set as the Accept-Language request header.
* @param callback The callback run when the HTTP response is received.
* The callback will be run on the main thread.
* @throws MalformedURLException on invalid url
*/
public HttpRequest(String url, String userAgent, String acceptLanguage,
HttpRequestCallback<T> callback)
throws MalformedURLException {
mUrl = new URL(url);
mUserAgent = userAgent;
mAcceptLanguage = acceptLanguage;
if (!mUrl.getProtocol().equals(UrlConstants.HTTP_SCHEME)
&& !mUrl.getProtocol().equals(UrlConstants.HTTPS_SCHEME)) {
throw new MalformedURLException("This is not a http or https URL: " + url);
}
mCallback = callback;
}
/**
* The callback that gets run after the request is made.
*/
public interface HttpRequestCallback<T> {
/**
* The callback run on a valid response.
* @param result The result object.
*/
void onResponse(T result);
/**
* The callback run on an Exception.
* @param httpResponseCode The HTTP response code. This will be 0 if no
* response was received.
* @param e The encountered Exception.
*/
void onError(int httpResponseCode, Exception e);
}
/**
* Make the HTTP request and parse the HTTP response.
*/
@Override
public void run() {
// Setup some values
HttpURLConnection urlConnection = null;
T result = null;
InputStream inputStream = null;
int responseCode = 0;
IOException ioException = null;
// Make the request
try {
urlConnection = (HttpURLConnection) mUrl.openConnection();
urlConnection.setRequestProperty(USER_AGENT_HEADER_NAME, mUserAgent);
urlConnection.setRequestProperty(ACCEPT_LANGUAGE_HEADER_NAME, mAcceptLanguage);
writeToUrlConnection(urlConnection);
responseCode = urlConnection.getResponseCode();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
result = readInputStream(inputStream);
} catch (IOException e) {
ioException = e;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// Invoke the callback on the main thread.
final Exception finalException = ioException;
final T finalResult = result;
final int finalResponseCode = responseCode;
ThreadUtils.postOnUiThread(new Runnable() {
@Override
public void run() {
if (finalException == null) {
mCallback.onResponse(finalResult);
} else {
mCallback.onError(finalResponseCode, finalException);
}
}
});
}
/**
* Helper method to make an HTTP request.
* @param urlConnection The HTTP connection.
* @throws IOException on error
*/
protected abstract void writeToUrlConnection(HttpURLConnection urlConnection)
throws IOException;
/**
* Helper method to read an HTTP response.
* @param is The InputStream.
* @return An object representing the HTTP response.
* @throws IOException on error
*/
protected abstract T readInputStream(InputStream is) throws IOException;
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import org.json.JSONException;
import org.json.JSONObject;
import org.chromium.base.ApiCompatibilityUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
/**
* A class that represents an HTTP request for a JSON object.
* Both the request payload and the response are JSON objects.
*/
class JsonObjectHttpRequest extends HttpRequest<JSONObject> {
private final JSONObject mJsonObject;
/**
* Construct a JSON object request.
* @param url The url to make this HTTP request to.
* @param userAgent The string to set as the User-Agent request header.
* @param acceptLanguage The string to set as the Accept-Language request header.
* @param jsonObject The JSON payload.
* @param callback The callback run when the HTTP response is received.
* @throws MalformedURLException on invalid url
*/
public JsonObjectHttpRequest(String url, String userAgent, String acceptLanguage,
JSONObject jsonObject, RequestCallback callback)
throws MalformedURLException {
super(url, userAgent, acceptLanguage, callback);
mJsonObject = jsonObject;
}
/**
* The callback that gets run after the request is made.
*/
public interface RequestCallback extends HttpRequest.HttpRequestCallback<JSONObject> {}
/**
* Helper method to make an HTTP request.
* @param urlConnection The HTTP connection.
*/
@Override
public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
OutputStream os = urlConnection.getOutputStream();
os.write(ApiCompatibilityUtils.getBytesUtf8(mJsonObject.toString()));
os.close();
}
/**
* Helper method to read an HTTP response.
* @param is The InputStream.
* @return An object representing the HTTP response.
*/
@Override
protected JSONObject readInputStream(InputStream is) throws IOException {
String jsonString = readStreamToString(is);
JSONObject jsonObject;
try {
return new JSONObject(jsonString);
} catch (JSONException error) {
throw new IOException(error.toString());
}
}
private static String readStreamToString(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return os.toString("UTF-8");
}
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import android.graphics.Bitmap;
import java.util.Collection;
/**
* This class sends requests to the Physical Web Service.
*/
interface PwsClient {
/**
* Callback that is run after the PWS sends a response to a resolve-scan request.
*/
interface ResolveScanCallback {
/**
* Handle newly returned PwsResults.
* @param pwsResults The results returned by the PWS.
*/
public void onPwsResults(Collection<PwsResult> pwsResults);
}
/**
* Callback that is run after receiving the response to an icon fetch request.
*/
interface FetchIconCallback {
/**
* Handle newly returned favicon Bitmaps.
* @param iconUrl The favicon URL.
* @param iconBitmap The icon image data.
*/
public void onIconReceived(String iconUrl, Bitmap iconBitmap);
}
/**
* Send an HTTP request to the PWS to resolve a set of URLs.
* @param broadcastUrls The URLs to resolve.
* @param resolveScanCallback The callback to be run when the response is received.
*/
void resolve(Collection<UrlInfo> broadcastUrls, ResolveScanCallback resolveScanCallback);
/**
* Send an HTTP request to fetch a favicon.
* @param iconUrl The URL of the favicon.
* @param fetchIconCallback The callback to be run when the icon is received.
*/
void fetchIcon(String iconUrl, FetchIconCallback fetchIconCallback);
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import org.chromium.base.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
/**
* A result from the Physical Web Server.
*
* This represents metadata about a URL retrieved from from a PWS response. It does not
* necessarily represent one response as a single PWS response may include metadata about multiple
* URLs.
*/
class PwsResult {
private static final String TAG = "PhysicalWeb";
private static final String PAGE_INFO_KEY = "pageInfo";
private static final String REQUEST_URL_KEY = "scannedUrl";
private static final String SITE_URL_KEY = "resolvedUrl";
private static final String ICON_KEY = "icon";
private static final String TITLE_KEY = "title";
private static final String DESCRIPTION_KEY = "description";
private static final String GROUP_ID_KEY = "groupId";
/**
* The URL that was set in the request to the PWS.
*/
public final String requestUrl;
/**
* The destination URL that the requestUrl redirects to.
*/
public final String siteUrl;
/**
* The URL for the destination's favicon.
*/
public final String iconUrl;
/**
* The title of the web page.
*/
public final String title;
/**
* The description of the webpage.
*/
public final String description;
/**
* The group id as determined by the PWS.
* This value is useful for associating multiple URLs that refer to similar content in the same
* bucket.
*/
public final String groupId;
/**
* Construct a PwsResult.
*/
PwsResult(String requestUrl, String siteUrl, String iconUrl, String title, String description,
String groupId) {
this.requestUrl = requestUrl;
this.siteUrl = siteUrl;
this.iconUrl = iconUrl;
this.title = title;
this.description = description;
String groupIdToSet = groupId;
if (groupId == null) {
try {
groupIdToSet = new URL(siteUrl).getHost() + title;
} catch (MalformedURLException e) {
Log.e(TAG, "PwsResult created with a malformed URL", e);
groupIdToSet = siteUrl + title;
}
}
this.groupId = groupIdToSet;
}
/**
* Creates a JSON object that represents this data structure.
* @return a JSON serialization of this data structure.
* @throws JSONException if the values cannot be deserialized.
*/
public JSONObject jsonSerialize() throws JSONException {
return new JSONObject()
.put(REQUEST_URL_KEY, requestUrl)
.put(SITE_URL_KEY, siteUrl)
.put(PAGE_INFO_KEY, new JSONObject()
.put(ICON_KEY, iconUrl)
.put(TITLE_KEY, title)
.put(DESCRIPTION_KEY, description)
.put(GROUP_ID_KEY, groupId));
}
/**
* Populates a PwsResult with data from a given JSON object.
* @param jsonObject a serialized PwsResult.
* @return The PwsResult represented by the serialized object.
* @throws JSONException if the values cannot be serialized.
*/
public static PwsResult jsonDeserialize(JSONObject jsonObject) throws JSONException {
JSONObject pageInfo = jsonObject.getJSONObject(PAGE_INFO_KEY);
return new PwsResult(
jsonObject.getString(REQUEST_URL_KEY),
jsonObject.getString(SITE_URL_KEY),
pageInfo.optString(ICON_KEY, null),
pageInfo.optString(TITLE_KEY, ""),
pageInfo.optString(DESCRIPTION_KEY, null),
pageInfo.optString(GROUP_ID_KEY, null));
}
}
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
/**
* This class represents a scanned URL and information associated with that URL.
*/
class UrlInfo {
private static final String URL_KEY = "url";
private static final String DISTANCE_KEY = "distance";
private static final String FIRST_SEEN_TIMESTAMP_KEY = "first_seen_timestamp";
private static final String DEVICE_ADDRESS_KEY = "device_address";
private static final String HAS_BEEN_DISPLAYED_KEY = "has_been_displayed";
private final String mUrl;
private final long mFirstSeenTimestamp;
private double mDistance;
private String mDeviceAddress;
private boolean mHasBeenDisplayed;
public UrlInfo(String url, double distance, long firstSeenTimestamp) {
mUrl = url;
mDistance = distance;
mFirstSeenTimestamp = firstSeenTimestamp;
mDeviceAddress = null;
mHasBeenDisplayed = false;
}
/**
* Constructs a simple UrlInfo with only a URL.
*/
public UrlInfo(String url) {
this(url, -1.0, System.currentTimeMillis());
}
/**
* Gets the URL represented by this object.
* @param The URL.
*/
public String getUrl() {
return mUrl;
}
/**
* Sets the distance of the URL from the scanner in meters.
* @param distance The estimated distance of the URL from the scanner in meters.
*/
public UrlInfo setDistance(double distance) {
mDistance = distance;
return this;
}
/**
* Gets the distance of the URL from the scanner in meters.
* @return The estimated distance of the URL from the scanner in meters.
*/
public double getDistance() {
return mDistance;
}
/**
* Gets the timestamp of when the URL was first scanned.
* This timestamp is recorded using System.currentTimeMillis().
* @return The first seen timestamp.
*/
public long getFirstSeenTimestamp() {
return mFirstSeenTimestamp;
}
/**
* Sets the device address for the BLE beacon that last emitted this URL.
* @param deviceAddress the new device address, matching the
* BluetoothAdapter.checkBluetoothAddress format.
*/
public UrlInfo setDeviceAddress(String deviceAddress) {
mDeviceAddress = deviceAddress;
return this;
}
/**
* Gets the device address for the BLE beacon that last emitted this URL.
* @return The device address.
*/
public String getDeviceAddress() {
return mDeviceAddress;
}
/**
* Marks this URL as having been displayed to the user.
*/
public UrlInfo setHasBeenDisplayed() {
mHasBeenDisplayed = true;
return this;
}
/**
* Tells if we've displayed this URL.
* @return Whether we've displayed this URL.
*/
public boolean hasBeenDisplayed() {
return mHasBeenDisplayed;
}
/**
* Creates a JSON object that represents this data structure.
* @return a JSON serialization of this data structure.
* @throws JSONException if the values cannot be deserialized.
*/
public JSONObject jsonSerialize() throws JSONException {
return new JSONObject()
.put(URL_KEY, mUrl)
.put(DISTANCE_KEY, mDistance)
.put(FIRST_SEEN_TIMESTAMP_KEY, mFirstSeenTimestamp)
.put(DEVICE_ADDRESS_KEY, mDeviceAddress)
.put(HAS_BEEN_DISPLAYED_KEY, mHasBeenDisplayed);
}
/**
* Populates a UrlInfo with data from a given JSON object.
* @param jsonObject a serialized UrlInfo.
* @return The UrlInfo represented by the serialized object.
* @throws JSONException if the values cannot be serialized.
*/
public static UrlInfo jsonDeserialize(JSONObject jsonObject) throws JSONException {
UrlInfo urlInfo = new UrlInfo(jsonObject.getString(URL_KEY),
jsonObject.getDouble(DISTANCE_KEY), jsonObject.getLong(FIRST_SEEN_TIMESTAMP_KEY))
.setDeviceAddress(jsonObject.optString(DEVICE_ADDRESS_KEY));
if (jsonObject.optBoolean(HAS_BEEN_DISPLAYED_KEY, false)) {
urlInfo.setHasBeenDisplayed();
}
return urlInfo;
}
/**
* Represents the UrlInfo as a String.
*/
@Override
public String toString() {
return String.format(Locale.getDefault(), "%s %f %d %b", mUrl, mDistance,
mFirstSeenTimestamp, mHasBeenDisplayed);
}
}
......@@ -939,7 +939,6 @@ chrome_java_sources = [
"java/src/org/chromium/chrome/browser/permissions/PermissionDialogDelegate.java",
"java/src/org/chromium/chrome/browser/permissions/PermissionDialogView.java",
"java/src/org/chromium/chrome/browser/permissions/PermissionUmaUtil.java",
"java/src/org/chromium/chrome/browser/physicalweb/BitmapHttpRequest.java",
"java/src/org/chromium/chrome/browser/photo_picker/BitmapScalerTask.java",
"java/src/org/chromium/chrome/browser/photo_picker/BitmapUtils.java",
"java/src/org/chromium/chrome/browser/photo_picker/DecoderService.java",
......@@ -953,14 +952,8 @@ chrome_java_sources = [
"java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapView.java",
"java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java",
"java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java",
"java/src/org/chromium/chrome/browser/physicalweb/HttpRequest.java",
"java/src/org/chromium/chrome/browser/physicalweb/JsonObjectHttpRequest.java",
"java/src/org/chromium/chrome/browser/physicalweb/PhysicalWeb.java",
"java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebUma.java",
"java/src/org/chromium/chrome/browser/physicalweb/PwsClient.java",
"java/src/org/chromium/chrome/browser/physicalweb/PwsClientImpl.java",
"java/src/org/chromium/chrome/browser/physicalweb/PwsResult.java",
"java/src/org/chromium/chrome/browser/physicalweb/UrlInfo.java",
"java/src/org/chromium/chrome/browser/physicalweb/Utils.java",
"java/src/org/chromium/chrome/browser/policy/PolicyAuditor.java",
"java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java",
......@@ -1751,7 +1744,6 @@ chrome_test_java_sources = [
"javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageIntegrationTest.java",
"javatests/src/org/chromium/chrome/browser/partnercustomizations/PartnerHomepageUnitTest.java",
"javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java",
"javatests/src/org/chromium/chrome/browser/physicalweb/MockPwsClient.java",
"javatests/src/org/chromium/chrome/browser/policy/CombinedPolicyProviderTest.java",
"javatests/src/org/chromium/chrome/browser/payments/AndroidPaymentAppFinderTest.java",
"javatests/src/org/chromium/chrome/browser/payments/CurrencyFormatterTest.java",
......@@ -2068,9 +2060,6 @@ chrome_junit_test_java_sources = [
"junit/src/org/chromium/chrome/browser/payments/AutofillContactTest.java",
"junit/src/org/chromium/chrome/browser/payments/AutofillContactUnitTest.java",
"junit/src/org/chromium/chrome/browser/payments/PaymentManifestVerifierTest.java",
"junit/src/org/chromium/chrome/browser/physicalweb/PwsClientImplTest.java",
"junit/src/org/chromium/chrome/browser/physicalweb/PwsResultTest.java",
"junit/src/org/chromium/chrome/browser/physicalweb/UrlInfoTest.java",
"junit/src/org/chromium/chrome/browser/preferences/privacy/PrivacyPreferencesManagerTest.java",
"junit/src/org/chromium/chrome/browser/preferences/password/DialogManagerTest.java",
"junit/src/org/chromium/chrome/browser/preferences/password/EnsureAsyncPostingRule.java",
......
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.content.res.Resources;
import android.text.TextUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowResources;
import org.chromium.base.LocaleUtils;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.chrome.R;
import java.util.Locale;
/**
* Tests for {@link PwsClientImpl}.
*/
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class PwsClientImplTest {
private static final String ACCEPT_LANGUAGES = "en-US,en";
PwsClientImpl mPwsClientImpl;
/**
* Robolectric shadow to mock out calls to {@link Resources#getString}.
*/
@Implements(Resources.class)
public static class AcceptLanguageShadowResources extends ShadowResources {
public static final Resources sResources = mock(Resources.class);
@Implementation
public CharSequence getText(int id) {
return sResources.getText(id);
}
}
@Before
public void setUp() throws Exception {
mPwsClientImpl = new PwsClientImpl();
}
@Test
public void testUserAgentNonEmpty() {
assertFalse(TextUtils.isEmpty(mPwsClientImpl.getUserAgent()));
}
@Test
@Config(shadows = AcceptLanguageShadowResources.class)
public void testLanguageTagIsIncludedInAcceptLanguageHeader() {
when(AcceptLanguageShadowResources.sResources.getText(R.string.accept_languages))
.thenReturn(ACCEPT_LANGUAGES);
String defaultLocaleString = LocaleUtils.getDefaultLocaleString();
String[] languageTags = defaultLocaleString.split(",");
// Ensure Accept-Language contains the full language tag.
String acceptLanguage = mPwsClientImpl.updateAcceptLanguage();
for (String tag : languageTags) {
assertTrue(acceptLanguage.contains(tag));
// Ensure Accept-Language also contains the language code by itself.
String languageCode;
if (tag.length() == 2 || tag.length() == 3) {
languageCode = tag;
} else if (tag.charAt(2) == '-') {
languageCode = tag.substring(0, 2);
} else { // length of the language code is 3.
languageCode = tag.substring(0, 3);
}
assertTrue(acceptLanguage.startsWith(languageCode + ",")
|| acceptLanguage.contains(languageCode + ";")
|| acceptLanguage.equals(languageCode));
}
}
@Test
public void testLanguageTagIsPrepended() {
Locale locale = new Locale("en", "GB");
String defaultLocale = LocaleUtils.toLanguageTag(locale);
String languageList = "fr-CA,fr-FR,fr";
// Should prepend the language tag "en-GB" as well as the language code "en".
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(defaultLocale, languageList);
assertEquals("en-GB,en,fr-CA,fr-FR,fr", languageListWithTag);
}
@Test
public void testLanguageOnlyTagIsPrepended() {
Locale locale = new Locale("mas");
String defaultLocale = LocaleUtils.toLanguageTag(locale);
String languageList = "fr-CA,fr-FR,fr";
// Should prepend the language code only language tag "aaa".
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(defaultLocale, languageList);
assertEquals("mas,fr-CA,fr-FR,fr", languageListWithTag);
}
@Test
public void testSpecialLengthCountryCodeIsPrepended() {
Locale locale = new Locale("es", "005");
String defaultLocale = LocaleUtils.toLanguageTag(locale);
String languageList = "fr-CA,fr-FR,fr";
// Should prepend the language tag "aa-AAA" as well as the language code "aa".
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(defaultLocale, languageList);
assertEquals("es-005,es,fr-CA,fr-FR,fr", languageListWithTag);
}
@Test
public void testMultipleLanguageTagIsPrepended() {
String locale = "jp-JP,is-IS";
String languageList = "en-US,en";
// Should prepend the language tag "aa-AA" as well as the language code "aa".
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(locale, languageList);
assertEquals("jp-JP,jp,is-IS,is,en-US,en", languageListWithTag);
// Make sure the language code is only inserted after the last languageTag that
// contains that language.
locale = "jp-JP,fr-CA,fr-FR";
languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(locale, languageList);
assertEquals("jp-JP,jp,fr-CA,fr-FR,fr,en-US,en", languageListWithTag);
}
@Test
public void testLanguageTagIsPrependedWhenListContainsLanguageCode() {
Locale locale = new Locale("fr", "FR");
String defaultLocale = LocaleUtils.toLanguageTag(locale);
String languageList = "fr-CA,fr";
// Should prepend the language tag "xx-XX" but not the language code "xx" as it's already
// included at the end of the list.
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(defaultLocale, languageList);
assertEquals("fr-FR,fr-CA,fr", languageListWithTag);
}
@Test
public void testLanguageTagNotPrependedWhenUnnecessary() {
Locale locale = new Locale("fr", "CA");
String defaultLocale = LocaleUtils.toLanguageTag(locale);
String languageList = "fr-CA,fr-FR,fr";
// Language list should be unmodified since the tag is already present.
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(defaultLocale, languageList);
assertEquals(languageList, languageListWithTag);
}
@Test
public void testMultiLanguageTagNotPrependedWhenUnnecessary() {
String locale = "fr-FR,is-IS";
String languageList = "fr-FR,is-IS,fr,is";
// Language list should be unmodified since the tag is already present. However, the order
// changes because a language-code-only language tag is acceptable now.
String languageListWithTag =
PwsClientImpl.prependToAcceptLanguagesIfNecessary(locale, languageList);
assertEquals(languageList, languageListWithTag);
}
@Test
public void testAcceptLanguageQvalues() {
String languageList = "en-US,en-GB,en,jp-JP,jp";
// Should insert q-values for each item except the first which implicitly has q=1.0.
String acceptLanguage = PwsClientImpl.generateAcceptLanguageHeader(languageList);
assertEquals("en-US,en-GB;q=0.8,en;q=0.6,jp-JP;q=0.4,jp;q=0.2", acceptLanguage);
// When there are six or more items, the q-value should not go below 0.2.
languageList = "mas,es,en,jp,ch,fr";
acceptLanguage = PwsClientImpl.generateAcceptLanguageHeader(languageList);
assertEquals("mas,es;q=0.8,en;q=0.6,jp;q=0.4,ch;q=0.2,fr;q=0.2", acceptLanguage);
}
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import static org.junit.Assert.assertEquals;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
/**
* Tests for {@link PwsResult}.
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class PwsResultTest {
PwsResult mReferencePwsResult = null;
JSONObject mReferenceJsonObject = null;
@Before
public void setUp() throws Exception {
mReferencePwsResult = new PwsResult("https://shorturl.com", "https://longurl.com",
"https://longurl.com/favicon.ico", "This is a page", "Pages are the best",
"group1");
// Because we can't print JSON sorted by keys, the order is important here.
mReferenceJsonObject = new JSONObject("{"
+ " \"scannedUrl\": \"https://shorturl.com\","
+ " \"resolvedUrl\": \"https://longurl.com\","
+ " \"pageInfo\": {"
+ " \"icon\": \"https://longurl.com/favicon.ico\","
+ " \"title\": \"This is a page\","
+ " \"description\": \"Pages are the best\","
+ " \"groupId\": \"group1\""
+ " }"
+ "}");
}
@Test
public void testJsonSerializeWorks() throws JSONException {
assertEquals(
mReferenceJsonObject.toString(), mReferencePwsResult.jsonSerialize().toString());
}
@Test
public void testJsonDeserializeWorks() throws JSONException {
PwsResult pwsResult = PwsResult.jsonDeserialize(mReferenceJsonObject);
assertEquals(mReferencePwsResult.requestUrl, pwsResult.requestUrl);
assertEquals(mReferencePwsResult.siteUrl, pwsResult.siteUrl);
assertEquals(mReferencePwsResult.iconUrl, pwsResult.iconUrl);
assertEquals(mReferencePwsResult.title, pwsResult.title);
assertEquals(mReferencePwsResult.description, pwsResult.description);
assertEquals(mReferencePwsResult.groupId, pwsResult.groupId);
}
}
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.physicalweb;
import static org.junit.Assert.assertEquals;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
/**
* Tests for {@link UrlInfo}.
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class UrlInfoTest {
private static final String URL = "https://example.com";
private static final double EPSILON = .001;
UrlInfo mReferenceUrlInfo = null;
JSONObject mReferenceJsonObject = null;
@Before
public void setUp() throws JSONException {
mReferenceUrlInfo = new UrlInfo(URL, 99.5, 42)
.setHasBeenDisplayed()
.setDeviceAddress("00:11:22:33:AA:BB");
// Because we can't print JSON sorted by keys, the order is important here.
mReferenceJsonObject = new JSONObject("{"
+ " \"url\": \"" + URL + "\","
+ " \"distance\": 99.5,"
+ " \"first_seen_timestamp\": 42,"
+ " \"device_address\": \"00:11:22:33:AA:BB\","
+ " \"has_been_displayed\": true"
+ "}");
}
@Test
public void testJsonSerializeWorks() throws JSONException {
assertEquals(mReferenceJsonObject.toString(), mReferenceUrlInfo.jsonSerialize().toString());
}
@Test
public void testJsonDeserializeWorks() throws JSONException {
UrlInfo urlInfo = UrlInfo.jsonDeserialize(mReferenceJsonObject);
assertEquals(mReferenceUrlInfo.getUrl(), urlInfo.getUrl());
assertEquals(mReferenceUrlInfo.getDistance(), urlInfo.getDistance(), EPSILON);
assertEquals(mReferenceUrlInfo.getFirstSeenTimestamp(), urlInfo.getFirstSeenTimestamp());
assertEquals(mReferenceUrlInfo.getDeviceAddress(), urlInfo.getDeviceAddress());
assertEquals(mReferenceUrlInfo.hasBeenDisplayed(), urlInfo.hasBeenDisplayed());
}
}
......@@ -250,7 +250,7 @@
<messages fallback_to_english="true">
<!-- The default value for HTTP Accept-Language header. -->
<message name="IDS_ACCEPT_LANGUAGES" use_name_for_id="true" formatter_data="android_java">
<message name="IDS_ACCEPT_LANGUAGES" use_name_for_id="true">
en-US,en
</message>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment