|
| 1 | +/* |
| 2 | + * Copyright 2024-2024 the original author or authors. |
| 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 | + * https://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 | + |
| 17 | +package org.springframework.messaging.simp.stomp; |
| 18 | + |
| 19 | +import java.util.ArrayList; |
| 20 | +import java.util.Arrays; |
| 21 | +import java.util.List; |
| 22 | +import java.util.Map; |
| 23 | + |
| 24 | +import org.springframework.util.Assert; |
| 25 | + |
| 26 | +/** |
| 27 | + * An extension of {@link org.springframework.messaging.simp.stomp.StompEncoder} |
| 28 | + * that splits the STOMP message to multiple incomplete STOMP frames |
| 29 | + * when the encoded bytes length exceeds {@link SplittingStompEncoder#bufferSizeLimit}. |
| 30 | + * |
| 31 | + * @author Injae Kim |
| 32 | + * @since 6.2 |
| 33 | + * @see StompEncoder |
| 34 | + */ |
| 35 | +public class SplittingStompEncoder { |
| 36 | + |
| 37 | + private final StompEncoder encoder; |
| 38 | + |
| 39 | + private final int bufferSizeLimit; |
| 40 | + |
| 41 | + public SplittingStompEncoder(StompEncoder encoder, int bufferSizeLimit) { |
| 42 | + Assert.notNull(encoder, "StompEncoder is required"); |
| 43 | + Assert.isTrue(bufferSizeLimit > 0, "Buffer size limit must be greater than 0"); |
| 44 | + this.encoder = encoder; |
| 45 | + this.bufferSizeLimit = bufferSizeLimit; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Encodes the given payload and headers into a list of one or more {@code byte[]}s. |
| 50 | + * @param headers the headers |
| 51 | + * @param payload the payload |
| 52 | + * @return the list of one or more encoded messages |
| 53 | + */ |
| 54 | + public List<byte[]> encode(Map<String, Object> headers, byte[] payload) { |
| 55 | + byte[] result = this.encoder.encode(headers, payload); |
| 56 | + int length = result.length; |
| 57 | + |
| 58 | + if (length <= this.bufferSizeLimit) { |
| 59 | + return List.of(result); |
| 60 | + } |
| 61 | + |
| 62 | + List<byte[]> frames = new ArrayList<>(); |
| 63 | + for (int i = 0; i < length; i += this.bufferSizeLimit) { |
| 64 | + frames.add(Arrays.copyOfRange(result, i, Math.min(i + this.bufferSizeLimit, length))); |
| 65 | + } |
| 66 | + return frames; |
| 67 | + } |
| 68 | +} |
0 commit comments