1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.webkit;
18
19import android.net.http.EventHandler;
20
21import com.android.internal.R;
22
23import java.io.ByteArrayInputStream;
24
25import org.apache.harmony.luni.util.Base64;
26
27/**
28 * This class is a concrete implementation of StreamLoader that uses the
29 * content supplied as a URL as the source for the stream. The mimetype
30 * optionally provided in the URL is extracted and inserted into the HTTP
31 * response headers.
32 */
33class DataLoader extends StreamLoader {
34
35    /**
36     * Constructor uses the dataURL as the source for an InputStream
37     * @param dataUrl data: URL string optionally containing a mimetype
38     * @param loadListener LoadListener to pass the content to
39     */
40    DataLoader(String dataUrl, LoadListener loadListener) {
41        super(loadListener);
42
43        String url = dataUrl.substring("data:".length());
44        byte[] data = null;
45        int commaIndex = url.indexOf(',');
46        if (commaIndex != -1) {
47            String contentType = url.substring(0, commaIndex);
48            data = url.substring(commaIndex + 1).getBytes();
49            loadListener.parseContentTypeHeader(contentType);
50            if ("base64".equals(loadListener.transferEncoding())) {
51                data = Base64.decode(data);
52            }
53        } else {
54            data = url.getBytes();
55        }
56        if (data != null) {
57            mDataStream = new ByteArrayInputStream(data);
58            mContentLength = data.length;
59        }
60    }
61
62    @Override
63    protected boolean setupStreamAndSendStatus() {
64        if (mDataStream != null) {
65            mLoadListener.status(1, 1, 200, "OK");
66            return true;
67        } else {
68            mLoadListener.error(EventHandler.ERROR,
69                    mContext.getString(R.string.httpError));
70            return false;
71        }
72    }
73
74    @Override
75    protected void buildHeaders(android.net.http.Headers h) {
76    }
77}
78