Java Code Examples for java.nio.ByteBuffer.clear()

The following are Jave code examples for showing how to use clear() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: fuck_zookeeper   File: LENonTerminateTest.java   View Source Code Vote up 6 votes
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
Example 2
Project: EatDubbo   File: AbstractChannelBufferTest.java   View Source Code Vote up 6 votes
@Test
public void getDirectByteBufferState() {
    ByteBuffer dst = ByteBuffer.allocateDirect(4);
    dst.position(1);
    dst.limit(3);

    buffer.setByte(0, (byte) 1);
    buffer.setByte(1, (byte) 2);
    buffer.setByte(2, (byte) 3);
    buffer.setByte(3, (byte) 4);
    buffer.getBytes(1, dst);

    assertEquals(3, dst.position());
    assertEquals(3, dst.limit());

    dst.clear();
    assertEquals(0, dst.get(0));
    assertEquals(2, dst.get(1));
    assertEquals(3, dst.get(2));
    assertEquals(0, dst.get(3));
}
 
Example 3
Project: URTorrent   File: PeerWireConnection.java   View Source Code Vote up 6 votes
/**
	 * Sends handshake to remote peer.
	 * 
	 * @throws IOException
	 *             if an error occurs when writing to this connection's
	 *             {@link #java.nio.channels.SocketChannel}.
	 */
	public synchronized void sendHandshake() throws IOException {
//		System.out.println("WE have: " + PeerWireManager.allConnections.size() + " peers");
//		System.out.println("Are we blocking: " + clientSocketChannel.isBlocking());
//		System.out.println("Are we connected: " + clientSocketChannel.isConnected());
		ByteBuffer toSend = ByteBuffer.allocate(49 + PSTRLEN);
		toSend.clear();
		toSend.put(PSTRLEN);
		toSend.put(PSTR);
		toSend.putLong(0L);
		toSend.put(MetaInfo.INFO_HASH);
		toSend.put(MetaInfo.PEER_ID);
		toSend.flip();
		int huh = 0;
		while (toSend.hasRemaining()) {
			huh += clientSocketChannel.write(toSend);
		}
	//	System.out.println(huh);
		sentHandshake = true;
	}
 
Example 4
Project: RegexPerf   File: StringToBytes.java   View Source Code Vote up 6 votes
@Benchmark
public byte[] byCharsetEncoder_US_ASCII() {
    try {
        CharsetEncoder encoder = asciiencode.get();
        CharBuffer buffer  = charbuffergenerator.get();
        buffer.clear();
        buffer.append(STR);
        buffer.flip();

        ByteBuffer outbuffer = bytebuffergenerator.get();
        outbuffer.clear();

        CoderResult result = encoder.encode(buffer, outbuffer, false);
        if (result.isError()) {
            result.throwException();
        }
        byte[] b = new byte[STR.length()];
        outbuffer.flip();
        outbuffer.get(b);
        return b;
    } catch (CharacterCodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Project: mux2fs   File: MirrorFs.java   View Source Code Vote up 6 votes
protected int readFromFileChannel(Consumer<byte[]> buf, long offset, int size, FileChannel fileChannel) {
	if (fileChannel == null) {
		return -ErrorCodes.EBADF();
	}
	ByteBuffer byteBuffer = threadBuffer.get();
	byteBuffer.clear();
	byteBuffer.limit(size);
	return tryCatch.apply(() -> {
		int bytesRead = fileChannel.read(byteBuffer, offset); // Read into native memory
		if (bytesRead <= 0) { // EOF
			return SUCCESS;
		}
		byte[] intermediate = new byte[bytesRead]; // This copies native memory into JVM
		byteBuffer.rewind();
		byteBuffer.get(intermediate);
		buf.accept(intermediate); // And then back =(
		return bytesRead;
	});
}
 
Example 6
Project: monarch   File: ChunkedMessage.java   View Source Code Vote up 5 votes
/**
 * Populates the header with information received via socket
 */
public void readHeader() throws IOException {
  if (this.socket != null) {
    final ByteBuffer cb = getCommBuffer();
    synchronized (cb) {
      fetchHeader();
      final int type = cb.getInt();
      final int numParts = cb.getInt();
      final int txid = cb.getInt();
      cb.clear();
      if (!MessageType.validate(type)) {
        throw new IOException(
            LocalizedStrings.ChunkedMessage_INVALID_MESSAGE_TYPE_0_WHILE_READING_HEADER
                .toLocalizedString(Integer.valueOf(type)));
      }

      // Set the header and payload fields only after receiving all the
      // socket data, providing better message consistency in the face
      // of exceptional conditions (e.g. IO problems, timeouts etc.)
      this.msgType = type;
      this.numberOfParts = numParts; // Already set in setPayloadFields via setNumberOfParts
      this.transactionId = txid;
    }
  } else {
    throw new IOException(LocalizedStrings.ChunkedMessage_DEAD_CONNECTION.toLocalizedString());
  }
}
 
Example 7
Project: feeyo-redisproxy   File: ByteBufferPagePool.java   View Source Code Vote up 5 votes
@Override
  public void recycle(ByteBuffer theBuf) {
  	
    	if(theBuf !=null && (!(theBuf instanceof DirectBuffer) )){
  		theBuf.clear();
  		return;
       }

    	final long size = theBuf.capacity();
boolean recycled = false;
DirectBuffer thisNavBuf = (DirectBuffer) theBuf;
int chunkCount = theBuf.capacity() / chunkSize;
DirectBuffer parentBuf = (DirectBuffer) thisNavBuf.attachment();
int startChunk = (int) ((thisNavBuf.address() - parentBuf.address()) / chunkSize);
for (int i = 0; i < allPages.length; i++) {
	if ((recycled = allPages[i].recycleBuffer((ByteBuffer) parentBuf, startChunk,chunkCount) == true)) {
		break;
	}
}

final long threadId = Thread.currentThread().getId();
if (memoryUsage.containsKey(threadId)) {
	memoryUsage.put(threadId, memoryUsage.get(threadId) - size);
}

if (recycled == false) {
	LOGGER.warn("warning , not recycled buffer " + theBuf);
}

sharedOptsCount++;	
  }
 
Example 8
Project: stardict   File: InputStreamDictionaryIndexReader.java   View Source Code Vote up 5 votes
@Override
public void eachItem(final ImmutableDictionaryInfo info, final Consumer<DictionaryIndexItem> consumer) throws IOException {
	// The length of "word_str" should be less than 256.
	final ByteBuffer buf = ByteBuffer.allocate(256);

	int counter = 0;
	// index item format: word_str(256bytes) \0 word_data_offset(32/64bit)
	// word_data_size(32bit)
	while (null != info.getWordCount() && counter < info.getWordCount()) {
		byte b;
		try {
			b = this.in.readByte();
		} catch (EOFException ex) {
			break;
		}
		if (0 == b) {
			// get word_str
			buf.flip();
			final byte[] bytes = new byte[buf.limit()];
			buf.get(bytes);
			final String word = new String(bytes, Charset.forName("UTF-8"));
			buf.clear();

			// get offset
			final Long offset = Integer.valueOf(64).equals(info.getIdxOffsetBits()) ? this.in.readLong()
					: (long) this.in.readInt();

			// get size
			final Integer size = this.in.readInt();

			consumer.accept(new DictionaryIndexItem(word, offset, size));
			counter++;
		} else {
			buf.put(b);
		}
	}
}
 
Example 9
Project: Progetto-C   File: TextureImpl.java   View Source Code Vote up 5 votes
/**
* @see org.newdawn.slick.opengl.Texture#getTextureData()
*/
  public byte[] getTextureData() {
  	ByteBuffer buffer = BufferUtils.createByteBuffer((hasAlpha() ? 4 : 3) * texWidth * texHeight);
  	bind();
  	GL.glGetTexImage(SGL.GL_TEXTURE_2D, 0, hasAlpha() ? SGL.GL_RGBA : SGL.GL_RGB, SGL.GL_UNSIGNED_BYTE, 
  					   buffer);
  	byte[] data = new byte[buffer.limit()];
  	buffer.get(data);
  	buffer.clear();
  	
  	return data;
  }
 
Example 10
Project: Liteframework   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Decodes the specified URL as per RFC 3986, i.e. transforms
 * percent-encoded octets to characters by decoding with the UTF-8 character
 * set. This function is primarily intended for usage with
 * {@link java.net.URL} which unfortunately does not enforce proper URLs. As
 * such, this method will leniently accept invalid characters or malformed
 * percent-encoded octets and simply pass them literally through to the
 * result string. Except for rare edge cases, this will make unencoded URLs
 * pass through unaltered.
 *
 * @param url The URL to decode, may be {@code null}.
 * @return The decoded URL or {@code null} if the input was
 * {@code null}.
 */
static String decodeUrl(String url) {
    String decoded = url;
    if (url != null && url.indexOf('%') >= 0) {
        int n = url.length();
        StringBuffer buffer = new StringBuffer();
        ByteBuffer bytes = ByteBuffer.allocate(n);
        for (int i = 0; i < n; ) {
            if (url.charAt(i) == '%') {
                try {
                    do {
                        byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
                        bytes.put(octet);
                        i += 3;
                    } while (i < n && url.charAt(i) == '%');
                    continue;
                } catch (RuntimeException e) {
                    // malformed percent-encoded octet, fall through and
                    // append characters literally
                } finally {
                    if (bytes.position() > 0) {
                        bytes.flip();
                        buffer.append(UTF8.decode(bytes).toString());
                        bytes.clear();
                    }
                }
            }
            buffer.append(url.charAt(i++));
        }
        decoded = buffer.toString();
    }
    return decoded;
}
 
Example 11
Project: stardict   File: DictionarySynonymsIndexReader.java   View Source Code Vote up 5 votes
/**
 * 
 * Read StarDict .syn file.
 * 
 * @param info
 *            dictionary meta data
 * @param in
 *            index file content in a ByteBuffer
 * 
 * @return synonyms index data
 */
public DictionarySynonymsIndex read(final ImmutableDictionaryInfo info, final ByteBuffer in) {
	// The length of "synonym_word" should be less than 256.
	final ByteBuffer buffer = ByteBuffer.allocate(256);

	int counter = 0;
	final DictionarySynonymsIndex index = new DictionarySynonymsIndex(info.getSynWordCount());
	// index item format: synonym_word(256bytes) \0
	// original_word_index(32/64bit)
	while (in.remaining() > 0 && (null != info.getSynWordCount() && counter < info.getSynWordCount())) {
		final byte b = in.get();
		if (0 == b) {
			// get synonym_word
			buffer.flip();
			final byte[] bytes = new byte[buffer.limit()];
			buffer.get(bytes);
			final String word = new String(bytes, Charset.forName("UTF-8"));
			buffer.clear();

			// get index
			final Integer offset = in.getInt();

			index.addItem(new DictionarySynonymsIndexItem(word, offset));
			counter++;
		} else {
			buffer.put(b);
		}
	}

	return index;
}
 
Example 12
Project: URTorrent   File: PeerWirePiece.java   View Source Code Vote up 5 votes
public byte[] computeHash() throws IOException, NoSuchAlgorithmException {
	final int CHUNK_SIZE = 8192;
	try (FileLock lock = pieceChannel.lock()) {
		ByteBuffer buf = ByteBuffer.allocateDirect(CHUNK_SIZE);
		buf.clear();
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		while (pieceChannel.read(buf) != -1) {
			buf.flip();
			md.update(buf);
			buf.clear();
		}
		return md.digest();
	}
	
}
 
Example 13
Project: openjdk-jdk10   File: Sender.java   View Source Code Vote up 5 votes
public void run() {
    SocketAddress sa = null;


    try {
        ByteBuffer bb = ByteBuffer.allocateDirect(12);
        bb.clear();
        // Get the one valid datagram
        dc.configureBlocking(false);
        while (sa == null) {
            sa = dc.receive(bb);
            if (sa != null && clientISA != null && !clientISA.equals(sa)) {
                log.println("Ignore a possible stray diagram from " + sa);
                sa = null;
            }
        }
        showBuffer("Received:", bb);
        sa = null;
        for (int i=0; i<100; i++) {
            bb.clear();
            sa = dc.receive(bb);
            if (sa != null)
                throw new RuntimeException("Test failed");
        }
        dc.close();
    } catch (Exception ex) {
        e = ex;
    }
}
 
Example 14
Project: PlusGram   File: NalUnitUtil.java   View Source Code Vote up 5 votes
/**
 * Discards data from the buffer up to the first SPS, where {@code data.position()} is interpreted
 * as the length of the buffer.
 * <p>
 * When the method returns, {@code data.position()} will contain the new length of the buffer. If
 * the buffer is not empty it is guaranteed to start with an SPS.
 *
 * @param data Buffer containing start code delimited NAL units.
 */
public static void discardToSps(ByteBuffer data) {
  int length = data.position();
  int consecutiveZeros = 0;
  int offset = 0;
  while (offset + 1 < length) {
    int value = data.get(offset) & 0xFF;
    if (consecutiveZeros == 3) {
      if (value == 1 && (data.get(offset + 1) & 0x1F) == NAL_UNIT_TYPE_SPS) {
        // Copy from this NAL unit onwards to the start of the buffer.
        ByteBuffer offsetData = data.duplicate();
        offsetData.position(offset - 3);
        offsetData.limit(length);
        data.position(0);
        data.put(offsetData);
        return;
      }
    } else if (value == 0) {
      consecutiveZeros++;
    }
    if (value != 0) {
      consecutiveZeros = 0;
    }
    offset++;
  }
  // Empty the buffer if the SPS NAL unit was not found.
  data.clear();
}
 
Example 15
Project: hadoop   File: TestSnappyCompressorDecompressor.java   View Source Code Vote up 5 votes
private void compressDecompressLoop(int rawDataSize) throws IOException {
  byte[] rawData = BytesGenerator.get(rawDataSize);    
  byte[] compressedResult = new byte[rawDataSize+20];
  int directBufferSize = Math.max(rawDataSize*2, 64*1024);    
  SnappyCompressor compressor = new SnappyCompressor(directBufferSize);
  compressor.setInput(rawData, 0, rawDataSize);
  int compressedSize = compressor.compress(compressedResult, 0, compressedResult.length);
  SnappyDirectDecompressor decompressor = new SnappyDirectDecompressor();
 
  ByteBuffer inBuf = ByteBuffer.allocateDirect(compressedSize);
  ByteBuffer outBuf = ByteBuffer.allocateDirect(rawDataSize);

  inBuf.put(compressedResult, 0, compressedSize);
  inBuf.flip();    

  ByteBuffer expected = ByteBuffer.wrap(rawData);
  
  outBuf.clear();
  while(!decompressor.finished()) {
    decompressor.decompress(inBuf, outBuf);
    if (outBuf.remaining() == 0) {
      outBuf.flip();
      while (outBuf.remaining() > 0) {        
        assertEquals(expected.get(), outBuf.get());
      }
      outBuf.clear();
    }
  }
  outBuf.flip();
  while (outBuf.remaining() > 0) {        
    assertEquals(expected.get(), outBuf.get());
  }
  outBuf.clear();
  
  assertEquals(0, expected.remaining());
}
 
Example 16
Project: neoscada   File: DataFileAccessorImpl.java   View Source Code Vote up 5 votes
public boolean forwardVisitAll ( final EntryVisitor visitor ) throws IOException
{
    final long position = this.channel.position ();

    try
    {
        this.channel.position ( HEADER_SIZE );

        final ByteBuffer buffer = ByteBuffer.allocate ( ENTRY_SIZE );

        while ( safeRead ( buffer ) == ENTRY_SIZE )
        {
            buffer.flip ();

            final double value = buffer.getDouble ();
            final long timestamp = buffer.getLong ();
            final byte flags = buffer.get ();

            logger.debug ( "Visit value - flag: {}", flags );

            final boolean cont = visitor.visitEntry ( timestamp, value, flags );
            if ( !cont )
            {
                logger.debug ( "Stopping visit by request on visitor" );
                return false;
            }

            buffer.clear ();
        }
    }
    finally
    {
        this.channel.position ( position );
        logger.debug ( "Returned to position: {}", position );
    }

    return true; // continue reading
}
 
Example 17
Project: ZooKeeper   File: Request.java   View Source Code Vote up 4 votes
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("sessionid:0x").append(Long.toHexString(sessionId))
        .append(" type:").append(op2String(type))
        .append(" cxid:0x").append(Long.toHexString(cxid))
        .append(" zxid:0x").append(Long.toHexString(hdr == null ?
                -2 : hdr.getZxid()))
        .append(" txntype:").append(hdr == null ?
                "unknown" : "" + hdr.getType());

    // best effort to print the path assoc with this request
    String path = "n/a";
    if (type != OpCode.createSession
            && type != OpCode.setWatches
            && type != OpCode.closeSession
            && request != null
            && request.remaining() >= 4)
    {
        try {
            // make sure we don't mess with request itself
            ByteBuffer rbuf = request.asReadOnlyBuffer();
            rbuf.clear();
            int pathLen = rbuf.getInt();
            // sanity check
            if (pathLen >= 0
                    && pathLen < 4096
                    && rbuf.remaining() >= pathLen)
            {
                byte b[] = new byte[pathLen];
                rbuf.get(b);
                path = new String(b);
            }
        } catch (Exception e) {
            // ignore - can't find the path, will output "n/a" instead
        }
    }
    sb.append(" reqpath:").append(path);

    return sb.toString();
}
 
Example 18
Project: openjdk-jdk10   File: Branch.java   View Source Code Vote up 4 votes
void doTest(SocketAddress peerAddress) {
    SctpMultiChannel channel = null;
    ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
    MessageInfo info = MessageInfo.createOutgoing(null, 0);

    try {
        channel = SctpMultiChannel.open();

        /* setup an association implicitly by sending a small message */
        int streamNumber = 0;
        debug("sending to " + peerAddress + " on stream number: " + streamNumber);
        info = MessageInfo.createOutgoing(peerAddress, streamNumber);
        buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buffer.flip();
        int position = buffer.position();
        int remaining = buffer.remaining();

        debug("sending small message: " + buffer);
        int sent = channel.send(buffer, info);

        check(sent == remaining, "sent should be equal to remaining");
        check(buffer.position() == (position + sent),
                "buffers position should have been incremented by sent");

        /* Receive the COMM_UP */
        buffer.clear();
        BranchNotificationHandler handler = new BranchNotificationHandler();
        info = channel.receive(buffer, null, handler);
        check(handler.receivedCommUp(), "COMM_UP no received");
        Set<Association> associations = channel.associations();
        check(!associations.isEmpty(),"There should be some associations");
        Association bassoc = associations.iterator().next();

        /* TEST 1: branch */
        SctpChannel bchannel = channel.branch(bassoc);

        check(!bchannel.getAllLocalAddresses().isEmpty(),
                               "branched channel should be bound");
        check(!bchannel.getRemoteAddresses().isEmpty(),
                               "branched channel should be connected");
        check(channel.associations().isEmpty(),
              "there should be no associations since the only one was branched off");

        buffer.clear();
        info = bchannel.receive(buffer, null, null);
        buffer.flip();
        check(info != null, "info is null");
        check(info.streamNumber() == streamNumber,
                "message not sent on the correct stream");
        check(info.bytes() == Util.SMALL_MESSAGE.getBytes("ISO-8859-1").
              length, "bytes received not equal to message length");
        check(info.bytes() == buffer.remaining(), "bytes != remaining");
        check(Util.compare(buffer, Util.SMALL_MESSAGE),
          "received message not the same as sent message");

    } catch (IOException ioe) {
        unexpected(ioe);
    } finally {
        clientFinishedLatch.countDown();
        try { serverFinishedLatch.await(10L, TimeUnit.SECONDS); }
        catch (InterruptedException ie) { unexpected(ie); }
        if (channel != null) {
            try { channel.close(); }
            catch (IOException e) { unexpected (e);}
        }
    }
}
 
Example 19
Project: openjdk-jdk10   File: OutOfBand.java   View Source Code Vote up 4 votes
static void test(Socket s, boolean urgentExpected,
                 int bytesBefore, int bytesAfter,
                 Selector sel)
    throws IOException
{
    // send data
    int bytesExpected = 0;
    if (bytesBefore > 0) {
        s.getOutputStream().write(new byte[bytesBefore]);
        bytesExpected += bytesBefore;
    }
    s.sendUrgentData(0xff);
    if (urgentExpected)
        bytesExpected++;
    if (bytesAfter > 0) {
        s.getOutputStream().write(new byte[bytesAfter]);
        bytesExpected += bytesAfter;
    }

    // receive data, checking for spurious wakeups and reads
    int spuriousWakeups = 0;
    int spuriousReads = 0;
    int bytesRead = 0;
    ByteBuffer bb = ByteBuffer.allocate(100);
    for (;;) {
        int n = sel.select(2000);
        if (n == 0) {
            if (bytesRead == bytesExpected) {
                System.out.format("Selector wakeups %d\tSpurious reads %d%n",
                        spuriousWakeups, spuriousReads);
                return;
            }
            if (++spuriousWakeups >= 3)
                throw new RuntimeException("Selector appears to be spinning" +
                    " or data not received");
            continue;
        }
        if (n > 1)
            throw new RuntimeException("More than one key selected????");
        SelectionKey key = sel.selectedKeys().iterator().next();
        bb.clear();
        n = ((SocketChannel)key.channel()).read(bb);
        if (n == 0) {
            if (++spuriousReads >=3)
                throw new RuntimeException("Too many spurious reads");
        } else {
            bytesRead += n;
            if (bytesRead > bytesExpected)
                throw new RuntimeException("Received more than expected");
        }
        sel.selectedKeys().clear();
    }
}
 
Example 20
Project: tomcat7   File: WsWebSocketContainer.java   View Source Code Vote up 4 votes
/**
 * Process response, blocking until HTTP response has been fully received.
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws DeploymentException
 * @throws TimeoutException
 */
private HttpResponse processResponse(ByteBuffer response,
        AsyncChannelWrapper channel, long timeout) throws InterruptedException,
        ExecutionException, DeploymentException, EOFException,
        TimeoutException {

    Map<String,List<String>> headers = new CaseInsensitiveKeyMap<List<String>>();

    int status = 0;
    boolean readStatus = false;
    boolean readHeaders = false;
    String line = null;
    while (!readHeaders) {
        // On entering loop buffer will be empty and at the start of a new
        // loop the buffer will have been fully read.
        response.clear();
        // Blocking read
        Future<Integer> read = channel.read(response);
        Integer bytesRead = read.get(timeout, TimeUnit.MILLISECONDS);
        if (bytesRead.intValue() == -1) {
            throw new EOFException();
        }
        response.flip();
        while (response.hasRemaining() && !readHeaders) {
            if (line == null) {
                line = readLine(response);
            } else {
                line += readLine(response);
            }
            if ("\r\n".equals(line)) {
                readHeaders = true;
            } else if (line.endsWith("\r\n")) {
                if (readStatus) {
                    parseHeaders(line, headers);
                } else {
                    status = parseStatus(line);
                    readStatus = true;
                }
                line = null;
            }
        }
    }

    return new HttpResponse(status, new WsHandshakeResponse(headers));
}