summaryrefslogtreecommitdiffstats
path: root/packages/StatementService/src/com/android/statementservice/retriever/URLFetcher.java
blob: 225e26c06db26e68d1f47d085a816295ee77b59c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.statementservice.retriever;

import android.util.Log;

import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Helper class for fetching HTTP or HTTPS URL.
 *
 * Visible for testing.
 *
 * @hide
 */
public class URLFetcher {
    private static final String TAG = URLFetcher.class.getSimpleName();

    private static final long DO_NOT_CACHE_RESULT = 0L;
    private static final int INPUT_BUFFER_SIZE_IN_BYTES = 1024;

    /**
     * Fetches the specified url and returns the content and ttl.
     *
     * @throws IOException if it can't retrieve the content due to a network problem.
     * @throws AssociationServiceException if the URL scheme is not http or https or the content
     * length exceeds {code fileSizeLimit}.
     */
    public WebContent getWebContentFromUrl(URL url, long fileSizeLimit, int connectionTimeoutMillis)
            throws AssociationServiceException, IOException {
        final String scheme = url.getProtocol().toLowerCase(Locale.US);
        if (!scheme.equals("http") && !scheme.equals("https")) {
            throw new IllegalArgumentException("The url protocol should be on http or https.");
        }

        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(connectionTimeoutMillis);
            connection.setReadTimeout(connectionTimeoutMillis);
            connection.setUseCaches(true);
            connection.setInstanceFollowRedirects(false);
            connection.addRequestProperty("Cache-Control", "max-stale=60");

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "The responses code is not 200 but "  + connection.getResponseCode());
                return new WebContent("", DO_NOT_CACHE_RESULT);
            }

            if (connection.getContentLength() > fileSizeLimit) {
                Log.e(TAG, "The content size of the url is larger than "  + fileSizeLimit);
                return new WebContent("", DO_NOT_CACHE_RESULT);
            }

            Long expireTimeMillis = getExpirationTimeMillisFromHTTPHeader(
                    connection.getHeaderFields());

            return new WebContent(inputStreamToString(
                    connection.getInputStream(), connection.getContentLength(), fileSizeLimit),
                expireTimeMillis);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * Visible for testing.
     * @hide
     */
    public static String inputStreamToString(InputStream inputStream, int length, long sizeLimit)
            throws IOException, AssociationServiceException {
        if (length < 0) {
            length = 0;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        byte[] buffer = new byte[INPUT_BUFFER_SIZE_IN_BYTES];
        int len = 0;
        while ((len = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
            if (baos.size() > sizeLimit) {
                throw new AssociationServiceException("The content size of the url is larger than "
                        + sizeLimit);
            }
        }
        return baos.toString("UTF-8");
    }

    /**
     * Parses the HTTP headers to compute the ttl.
     *
     * @param headers a map that map the header key to the header values. Can be null.
     * @return the ttl in millisecond or null if the ttl is not specified in the header.
     */
    private Long getExpirationTimeMillisFromHTTPHeader(Map<String, List<String>> headers) {
        if (headers == null) {
            return null;
        }
        Map<String, String> joinedHeaders = joinHttpHeaders(headers);

        NetworkResponse response = new NetworkResponse(null, joinedHeaders);
        Cache.Entry cachePolicy = HttpHeaderParser.parseCacheHeaders(response);

        if (cachePolicy == null) {
            // Cache is disabled, set the expire time to 0.
            return DO_NOT_CACHE_RESULT;
        } else if (cachePolicy.ttl == 0) {
            // Cache policy is not specified, set the expire time to 0.
            return DO_NOT_CACHE_RESULT;
        } else {
            // cachePolicy.ttl is actually the expire timestamp in millisecond.
            return cachePolicy.ttl;
        }
    }

    /**
     * Converts an HTTP header map of the format provided by {@linkHttpUrlConnection} to a map of
     * the format accepted by {@link HttpHeaderParser}. It does this by joining all the entries for
     * a given header key with ", ".
     */
    private Map<String, String> joinHttpHeaders(Map<String, List<String>> headers) {
        Map<String, String> joinedHeaders = new HashMap<String, String>();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            List<String> values = entry.getValue();
            if (values.size() == 1) {
                joinedHeaders.put(entry.getKey(), values.get(0));
            } else {
                joinedHeaders.put(entry.getKey(), Utils.joinStrings(", ", values));
            }
        }
        return joinedHeaders;
    }
}