1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package org.chromium.mojo.bindings;
6
7import java.nio.ByteBuffer;
8import java.nio.ByteOrder;
9
10/**
11 * Represents a {@link Message} which contains a {@link MessageHeader}. Deals with parsing the
12 * {@link MessageHeader} for a message.
13 */
14public class ServiceMessage extends Message {
15
16    private final MessageHeader mHeader;
17    private Message mPayload;
18
19    /**
20     * Reinterpret the given |message| as a message with the given |header|. The |message| must
21     * contain the |header| as the start of its raw data.
22     */
23    public ServiceMessage(Message baseMessage, MessageHeader header) {
24        super(baseMessage.getData(), baseMessage.getHandles());
25        assert header.equals(new org.chromium.mojo.bindings.MessageHeader(baseMessage));
26        this.mHeader = header;
27    }
28
29    /**
30     * Reinterpret the given |message| as a message with a header. The |message| must contain a
31     * header as the start of it's raw data, which will be parsed by this constructor.
32     */
33    ServiceMessage(Message baseMessage) {
34        this(baseMessage, new org.chromium.mojo.bindings.MessageHeader(baseMessage));
35    }
36
37    /**
38     * @see Message#asServiceMessage()
39     */
40    @Override
41    public ServiceMessage asServiceMessage() {
42        return this;
43    }
44
45    /**
46     * Returns the header of the given message. This will throw a {@link DeserializationException}
47     * if the start of the message is not a valid header.
48     */
49    public MessageHeader getHeader() {
50        return mHeader;
51    }
52
53    /**
54     * Returns the payload of the message.
55     */
56    public Message getPayload() {
57        if (mPayload == null) {
58            ByteBuffer truncatedBuffer =
59                    ((ByteBuffer) getData().position(getHeader().getSize())).slice();
60            truncatedBuffer.order(ByteOrder.LITTLE_ENDIAN);
61            mPayload = new Message(truncatedBuffer, getHandles());
62        }
63        return mPayload;
64    }
65
66    /**
67     * Set the request identifier on the message.
68     */
69    void setRequestId(long requestId) {
70        mHeader.setRequestId(getData(), requestId);
71    }
72
73}
74