001 /**
002 * GRANITE DATA SERVICES
003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 * This file is part of the Granite Data Services Platform.
006 *
007 * ***
008 *
009 * Community License: GPL 3.0
010 *
011 * This file is free software: you can redistribute it and/or modify
012 * it under the terms of the GNU General Public License as published
013 * by the Free Software Foundation, either version 3 of the License,
014 * or (at your option) any later version.
015 *
016 * This file is distributed in the hope that it will be useful, but
017 * WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
019 * GNU General Public License for more details.
020 *
021 * You should have received a copy of the GNU General Public License
022 * along with this program. If not, see <http://www.gnu.org/licenses/>.
023 *
024 * ***
025 *
026 * Available Commercial License: GraniteDS SLA 1.0
027 *
028 * This is the appropriate option if you are creating proprietary
029 * applications and you are not prepared to distribute and share the
030 * source code of your application under the GPL v3 license.
031 *
032 * Please visit http://www.granitedataservices.com/license for more
033 * details.
034 */
035 package org.granite.gravity.udp;
036
037 import java.io.IOException;
038 import java.io.OutputStream;
039
040 /**
041 * @author Franck WOLFF
042 */
043 public class UdpOutputStream extends OutputStream {
044
045 private static final int MAX_SIZE = 64 * 1024; // 64K.
046
047 private byte[] buffer = new byte[512];
048 private int size = 0;
049
050 public UdpOutputStream() {
051 }
052
053 @Override
054 public void write(int b) throws IOException {
055 if (size >= buffer.length) {
056 if (size >= MAX_SIZE)
057 throw new UdpPacketTooLargeException("Max capacity of 64K reached");
058
059 byte[] newBuffer = new byte[buffer.length << 1];
060 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
061 buffer = newBuffer;
062 }
063 buffer[size++] = (byte)b;
064 }
065
066 @Override
067 public void write(byte[] b, int off, int len) throws IOException {
068 if (off < 0 || len < 0 || off + len > b.length)
069 throw new IndexOutOfBoundsException();
070
071 if (len == 0)
072 return;
073
074 int newSize = len + size;
075 if (newSize > MAX_SIZE)
076 throw new UdpPacketTooLargeException("Max capacity of 64K reached");
077
078 if (newSize > buffer.length) {
079 int newCapacity = buffer.length << 1;
080 while (newCapacity < newSize)
081 newCapacity <<= 1;
082
083 byte[] newBuffer = new byte[newCapacity];
084 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
085 buffer = newBuffer;
086 }
087
088 System.arraycopy(b, off, buffer, size, len);
089 size = newSize;
090 }
091
092 public byte[] buffer() {
093 return buffer;
094 }
095
096 public int size() {
097 return size;
098 }
099
100 @Override
101 public void flush() {
102 }
103
104 @Override
105 public void close() {
106 }
107 }