1 /* 2 * Copyright (c) 2015 The Android Open Source Project 3 * Copyright (c) 2015 Samsung LSI 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package com.android.obex; 19 20 import java.io.IOException; 21 import java.io.InputStream; 22 23 public class ObexPacket { 24 public int mHeaderId; 25 public int mLength; 26 public byte[] mPayload = null; 27 ObexPacket(int headerId, int length)28 private ObexPacket(int headerId, int length) { 29 mHeaderId = headerId; 30 mLength = length; 31 } 32 33 /** 34 * Create a complete OBEX packet by reading data from an InputStream. 35 * 36 * @param is the input stream to read from. 37 * @return the OBEX packet read. 38 * @throws IOException if an IO exception occurs during read. 39 */ read(InputStream is)40 public static ObexPacket read(InputStream is) throws IOException { 41 int headerId = is.read(); 42 return read(headerId, is); 43 } 44 45 /** 46 * Read the remainder of an OBEX packet, with a specified headerId. 47 * 48 * @param headerId the headerId already read from the stream. 49 * @param is the stream to read from, assuming 1 byte have already been read. 50 * @return the OBEX packet read. 51 */ read(int headerId, InputStream is)52 public static ObexPacket read(int headerId, InputStream is) throws IOException { 53 // Read the 2 byte length field from the stream 54 int length = is.read(); 55 length = (length << 8) + is.read(); 56 57 ObexPacket newPacket = new ObexPacket(headerId, length); 58 59 int bytesReceived; 60 byte[] temp = null; 61 if (length > 3) { 62 // First three bytes already read, compensating for this 63 temp = new byte[length - 3]; 64 bytesReceived = is.read(temp); 65 while (bytesReceived != temp.length) { 66 bytesReceived += is.read(temp, bytesReceived, temp.length - bytesReceived); 67 } 68 } 69 newPacket.mPayload = temp; 70 return newPacket; 71 } 72 } 73