1/*
2 * Copyright (C) 2014 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.bluetooth.client.map;
18
19import android.util.Log;
20
21
22import android.bluetooth.client.map.BluetoothMasClient.CharsetType;
23import android.bluetooth.client.map.utils.ObexAppParameters;
24
25import java.io.ByteArrayOutputStream;
26import java.io.IOException;
27import java.io.InputStream;
28
29import javax.obex.ClientSession;
30import javax.obex.HeaderSet;
31import javax.obex.ResponseCodes;
32
33final class BluetoothMasRequestGetMessage extends BluetoothMasRequest {
34
35    private static final String TAG = "BluetoothMasRequestGetMessage";
36
37    private static final String TYPE = "x-bt/message";
38
39    private BluetoothMapBmessage mBmessage;
40
41    public BluetoothMasRequestGetMessage(String handle, CharsetType charset, boolean attachment) {
42
43        mHeaderSet.setHeader(HeaderSet.NAME, handle);
44
45        mHeaderSet.setHeader(HeaderSet.TYPE, TYPE);
46
47        ObexAppParameters oap = new ObexAppParameters();
48
49        oap.add(OAP_TAGID_CHARSET, CharsetType.UTF_8.equals(charset) ? CHARSET_UTF8
50                : CHARSET_NATIVE);
51
52        oap.add(OAP_TAGID_ATTACHMENT, attachment ? ATTACHMENT_ON : ATTACHMENT_OFF);
53
54        oap.addToHeaderSet(mHeaderSet);
55    }
56
57    @Override
58    protected void readResponse(InputStream stream) {
59
60        ByteArrayOutputStream baos = new ByteArrayOutputStream();
61        byte[] buf = new byte[1024];
62
63        try {
64            int len;
65            while ((len = stream.read(buf)) != -1) {
66                baos.write(buf, 0, len);
67            }
68        } catch (IOException e) {
69            Log.e(TAG, "I/O exception while reading response", e);
70        }
71
72        String bmsg = baos.toString();
73
74        mBmessage = BluetoothMapBmessageParser.createBmessage(bmsg);
75
76        if (mBmessage == null) {
77            mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
78        }
79    }
80
81    public BluetoothMapBmessage getMessage() {
82        return mBmessage;
83    }
84
85    @Override
86    public void execute(ClientSession session) throws IOException {
87        executeGet(session);
88    }
89}
90