Java Code Examples for io.netty.util.internal.StringUtil

The following examples show how to use io.netty.util.internal.StringUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: NettyChat   Source File: MsgTimeoutTimerManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从发送超时管理器中移除消息,并停止定时器
 *
 * @param msgId
 */
public void remove(String msgId) {
    if (StringUtil.isNullOrEmpty(msgId)) {
        return;
    }

    MsgTimeoutTimer timer = mMsgTimeoutMap.remove(msgId);
    MessageProtobuf.Msg msg = null;
    if (timer != null) {
        msg = timer.getMsg();
        timer.cancel();
        timer = null;
    }

    System.out.println("从发送消息管理器移除消息,message=" + msg);
}
 
Example 2
Source Project: netty-4.1.22   Source File: NioSctpChannel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected final Object filterOutboundMessage(Object msg) throws Exception {
    if (msg instanceof SctpMessage) {
        SctpMessage m = (SctpMessage) msg;
        ByteBuf buf = m.content();
        if (buf.isDirect() && buf.nioBufferCount() == 1) {
            return m;
        }

        return new SctpMessage(m.protocolIdentifier(), m.streamIdentifier(), m.isUnordered(),
                               newDirectBuffer(m, buf));
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) +
            " (expected: " + StringUtil.simpleClassName(SctpMessage.class));
}
 
Example 3
Source Project: armeria   Source File: ArmeriaHttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Filter the {@link HttpHeaderNames#TE} header according to the
 * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
 *
 * @param entry the entry whose name is {@link HttpHeaderNames#TE}.
 * @param out the resulting HTTP/2 headers.
 */
private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
                                           HttpHeadersBuilder out) {
    if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) {
        if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()),
                                                HttpHeaderValues.TRAILERS)) {
            out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
        }
    } else {
        final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue());
        for (CharSequence teValue : teValues) {
            if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue),
                                                    HttpHeaderValues.TRAILERS)) {
                out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString());
                break;
            }
        }
    }
}
 
Example 4
Source Project: netty-4.1.22   Source File: DefaultDnsRawRecord.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    final StringBuilder buf = new StringBuilder(64).append(StringUtil.simpleClassName(this)).append('(');
    final DnsRecordType type = type();
    if (type != DnsRecordType.OPT) {
        buf.append(name().isEmpty()? "<root>" : name())
           .append(' ')
           .append(timeToLive())
           .append(' ');

        DnsMessageUtil.appendRecordClass(buf, dnsClass())
                      .append(' ')
                      .append(type.name());
    } else {
        buf.append("OPT flags:")
           .append(timeToLive())
           .append(" udp:")
           .append(dnsClass());
    }

    buf.append(' ')
       .append(content().readableBytes())
       .append("B)");

    return buf.toString();
}
 
Example 5
Source Project: netty-4.1.22   Source File: DefaultDnsQuestion.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(64);

    buf.append(StringUtil.simpleClassName(this))
       .append('(')
       .append(name())
       .append(' ');

    DnsMessageUtil.appendRecordClass(buf, dnsClass())
                  .append(' ')
                  .append(type().name())
                  .append(')');

    return buf.toString();
}
 
Example 6
Source Project: netty-4.1.22   Source File: AbstractDnsRecord.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(64);

    buf.append(StringUtil.simpleClassName(this))
       .append('(')
       .append(name())
       .append(' ')
       .append(timeToLive())
       .append(' ');

    DnsMessageUtil.appendRecordClass(buf, dnsClass())
                  .append(' ')
                  .append(type().name())
                  .append(')');

    return buf.toString();
}
 
Example 7
Source Project: netty-4.1.22   Source File: LocalChannelRegistry.java    License: Apache License 2.0 6 votes vote down vote up
static LocalAddress register(
        Channel channel, LocalAddress oldLocalAddress, SocketAddress localAddress) {
    if (oldLocalAddress != null) {
        throw new ChannelException("already bound");
    }
    if (!(localAddress instanceof LocalAddress)) {
        throw new ChannelException("unsupported address type: " + StringUtil.simpleClassName(localAddress));
    }

    LocalAddress addr = (LocalAddress) localAddress;
    if (LocalAddress.ANY.equals(addr)) {
        addr = new LocalAddress(channel);
    }

    Channel boundChannel = boundChannels.putIfAbsent(addr, channel);
    if (boundChannel != null) {
        throw new ChannelException("address already in use by: " + boundChannel);
    }
    return addr;
}
 
Example 8
Source Project: netty-4.1.22   Source File: Base64Test.java    License: Apache License 2.0 6 votes vote down vote up
private static void testEncodeDecode(int size, ByteOrder order) {
    byte[] bytes = new byte[size];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);

    ByteBuf src = Unpooled.wrappedBuffer(bytes).order(order);
    ByteBuf encoded = Base64.encode(src);
    ByteBuf decoded = Base64.decode(encoded);
    ByteBuf expectedBuf = Unpooled.wrappedBuffer(bytes);
    try {
        assertEquals(StringUtil.NEWLINE + "expected: " + ByteBufUtil.hexDump(expectedBuf) +
                     StringUtil.NEWLINE + "actual--: " + ByteBufUtil.hexDump(decoded), expectedBuf, decoded);
    } finally {
        src.release();
        encoded.release();
        decoded.release();
        expectedBuf.release();
    }
}
 
Example 9
Source Project: pdown-core   Source File: URLHttpDownBootstrapBuilder.java    License: MIT License 6 votes vote down vote up
@Override
public HttpDownBootstrap build() {
  try {
    HttpRequestInfo request = HttpDownUtil.buildRequest(method, url, heads, body);
    request(request);
    if (getLoopGroup() == null) {
      loopGroup(new NioEventLoopGroup(1));
    }
    HttpResponseInfo response = HttpDownUtil.getHttpResponseInfo(request, null, getProxyConfig(), getLoopGroup());
    if (getResponse() == null) {
      response(response);
    } else {
      if (StringUtil.isNullOrEmpty(getResponse().getFileName())) {
        getResponse().setFileName(response.getFileName());
      }
      getResponse().setSupportRange(response.isSupportRange());
      getResponse().setTotalSize(response.getTotalSize());
    }
  } catch (Exception e) {
    if (getLoopGroup() != null) {
      getLoopGroup().shutdownGracefully();
    }
    throw new BootstrapBuildException("build URLHttpDownBootstrap error", e);
  }
  return super.build();
}
 
Example 10
Source Project: netty4.0.27Learn   Source File: DefaultSpdySynReplyFrame.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder()
        .append(StringUtil.simpleClassName(this))
        .append("(last: ")
        .append(isLast())
        .append(')')
        .append(StringUtil.NEWLINE)
        .append("--> Stream-ID = ")
        .append(streamId())
        .append(StringUtil.NEWLINE)
        .append("--> Headers:")
        .append(StringUtil.NEWLINE);
    appendHeaders(buf);

    // Remove the last newline.
    buf.setLength(buf.length() - StringUtil.NEWLINE.length());
    return buf.toString();
}
 
Example 11
private static byte[][] toFingerprintArray(Iterable<String> fingerprints) {
    if (fingerprints == null) {
        throw new NullPointerException("fingerprints");
    }

    List<byte[]> list = new ArrayList<byte[]>();
    for (String f: fingerprints) {
        if (f == null) {
            break;
        }

        if (!FINGERPRINT_PATTERN.matcher(f).matches()) {
            throw new IllegalArgumentException("malformed fingerprint: " + f);
        }
        f = FINGERPRINT_STRIP_PATTERN.matcher(f).replaceAll("");
        if (f.length() != SHA1_HEX_LEN) {
            throw new IllegalArgumentException("malformed fingerprint: " + f + " (expected: SHA1)");
        }

        list.add(StringUtil.decodeHexDump(f));
    }

    return list.toArray(new byte[list.size()][]);
}
 
Example 12
Source Project: netty-4.1.22   Source File: DefaultSocks4CommandResponse.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(96);
    buf.append(StringUtil.simpleClassName(this));

    DecoderResult decoderResult = decoderResult();
    if (!decoderResult.isSuccess()) {
        buf.append("(decoderResult: ");
        buf.append(decoderResult);
        buf.append(", dstAddr: ");
    } else {
        buf.append("(dstAddr: ");
    }
    buf.append(dstAddr());
    buf.append(", dstPort: ");
    buf.append(dstPort());
    buf.append(')');

    return buf.toString();
}
 
Example 13
Source Project: netty4.0.27Learn   Source File: AutobahnServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format(
                "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame)));
    }

    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise());
    } else if (frame instanceof TextWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof ContinuationWebSocketFrame) {
        ctx.write(frame, ctx.voidPromise());
    } else if (frame instanceof PongWebSocketFrame) {
        frame.release();
        // Ignore
    } else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                .getName()));
    }
}
 
Example 14
@Override
public @Nullable PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement psiElement) {
    if (!(object instanceof String)) {
        return null;
    }

    String fqn = getCallToFormatFunc(psiElement);
    if (StringUtil.isNullOrEmpty(fqn)) {
        return null;
    }

    String tokenText = (String)object;

    if ("%%".equals(tokenText)) {
        tokenText = "%";
    }
    else if (!"%".equals(tokenText)) {
        tokenText = StringUtils.strip((String)object, "%");
    }
    String functionName = StringUtils.strip(fqn, "\\");
    return new FormatTokenDocElement(psiManager, psiElement.getLanguage(), tokenText, functionName);
}
 
Example 15
Source Project: netty-4.1.22   Source File: DefaultThreadFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static String toPoolName(Class<?> poolType) {
    if (poolType == null) {
        throw new NullPointerException("poolType");
    }

    String poolName = StringUtil.simpleClassName(poolType);
    switch (poolName.length()) {
        case 0:
            return "unknown";
        case 1:
            return poolName.toLowerCase(Locale.US);
        default:
            if (Character.isUpperCase(poolName.charAt(0)) && Character.isLowerCase(poolName.charAt(1))) {
                return Character.toLowerCase(poolName.charAt(0)) + poolName.substring(1);
            } else {
                return poolName;
            }
    }
}
 
Example 16
Source Project: netty-4.1.22   Source File: DefaultSpdySynReplyFrame.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder()
        .append(StringUtil.simpleClassName(this))
        .append("(last: ")
        .append(isLast())
        .append(')')
        .append(StringUtil.NEWLINE)
        .append("--> Stream-ID = ")
        .append(streamId())
        .append(StringUtil.NEWLINE)
        .append("--> Headers:")
        .append(StringUtil.NEWLINE);
    appendHeaders(buf);

    // Remove the last newline.
    buf.setLength(buf.length() - StringUtil.NEWLINE.length());
    return buf.toString();
}
 
Example 17
Source Project: netty-4.1.22   Source File: DefaultSpdyDataFrame.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder()
        .append(StringUtil.simpleClassName(this))
        .append("(last: ")
        .append(isLast())
        .append(')')
        .append(StringUtil.NEWLINE)
        .append("--> Stream-ID = ")
        .append(streamId())
        .append(StringUtil.NEWLINE)
        .append("--> Size = ");
    if (refCnt() == 0) {
        buf.append("(freed)");
    } else {
        buf.append(content().readableBytes());
    }
    return buf.toString();
}
 
Example 18
Source Project: netty-http2   Source File: DefaultHttpPriorityFrame.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder();
    buf.append(StringUtil.simpleClassName(this));
    buf.append(StringUtil.NEWLINE);
    buf.append("--> Stream-ID = ");
    buf.append(getStreamId());
    buf.append(StringUtil.NEWLINE);
    buf.append("--> Dependency = ");
    buf.append(getDependency());
    buf.append(" (exclusive: ");
    buf.append(isExclusive());
    buf.append(", weight: ");
    buf.append(getWeight());
    buf.append(')');
    return buf.toString();
}
 
Example 19
Source Project: netty-4.1.22   Source File: ReadOnlyByteBufferBuf.java    License: Apache License 2.0 5 votes vote down vote up
ReadOnlyByteBufferBuf(ByteBufAllocator allocator, ByteBuffer buffer) {
    super(buffer.remaining());
    if (!buffer.isReadOnly()) {
        throw new IllegalArgumentException("must be a readonly buffer: " + StringUtil.simpleClassName(buffer));
    }

    this.allocator = allocator;
    this.buffer = buffer.slice().order(ByteOrder.BIG_ENDIAN);
    writerIndex(this.buffer.limit());
}
 
Example 20
Source Project: netty4.0.27Learn   Source File: DefaultSpdySettingsFrame.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder()
        .append(StringUtil.simpleClassName(this))
        .append(StringUtil.NEWLINE);
    appendSettings(buf);

    buf.setLength(buf.length() - StringUtil.NEWLINE.length());
    return buf.toString();
}
 
Example 21
Source Project: netty-4.1.22   Source File: PoolArena.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized String toString() {
    StringBuilder buf = new StringBuilder()
        .append("Chunk(s) at 0~25%:")
        .append(StringUtil.NEWLINE)
        .append(qInit)
        .append(StringUtil.NEWLINE)
        .append("Chunk(s) at 0~50%:")
        .append(StringUtil.NEWLINE)
        .append(q000)
        .append(StringUtil.NEWLINE)
        .append("Chunk(s) at 25~75%:")
        .append(StringUtil.NEWLINE)
        .append(q025)
        .append(StringUtil.NEWLINE)
        .append("Chunk(s) at 50~100%:")
        .append(StringUtil.NEWLINE)
        .append(q050)
        .append(StringUtil.NEWLINE)
        .append("Chunk(s) at 75~100%:")
        .append(StringUtil.NEWLINE)
        .append(q075)
        .append(StringUtil.NEWLINE)
        .append("Chunk(s) at 100%:")
        .append(StringUtil.NEWLINE)
        .append(q100)
        .append(StringUtil.NEWLINE)
        .append("tiny subpages:");
    appendPoolSubPages(buf, tinySubpagePools);
    buf.append(StringUtil.NEWLINE)
       .append("small subpages:");
    appendPoolSubPages(buf, smallSubpagePools);
    buf.append(StringUtil.NEWLINE);

    return buf.toString();
}
 
Example 22
Source Project: elephant   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void checkConfig() throws MQClientException {
      if (StringUtil.isNullOrEmpty(this.defaultMQProducer.getProducerGroup())) {
          throw new MQClientException("producerGroup is null", null);
      }
      if(StringUtil.isNullOrEmpty(this.defaultMQProducer.getProducerGroup())){
      	throw new MQClientException("register center is null", null);
      }
      synchronized (this.mqProducerFactory) {
      	if(this.mqProducerFactory.getProducerMap().get(this.defaultMQProducer.getProducerGroup()) != null){
      		throw new MQClientException("Group can not be the same!", null);
      	}
      	this.mqProducerFactory.getProducerMap().put(this.defaultMQProducer.getProducerGroup(), this);
}
      
  }
 
Example 23
Source Project: alcor   Source File: PortController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a port, and call the interfaces of each micro-service according to the
 * configuration of the port to create various required resources for the port.
 * If any exception occurs in the added process, we need to roll back
 * the resource allocated from each micro-service.
 * @param projectId Project the port belongs to
 * @param portWebJson Port configuration
 * @return PortWebJson
 * @throws Exception Various exceptions that may occur during the create process
 */
@PostMapping({"/project/{project_id}/ports", "v4/{project_id}/ports"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public PortWebJson createPort(@PathVariable("project_id") String projectId,
                                     @RequestBody PortWebJson portWebJson) throws Exception {
    PortEntity portEntity = portWebJson.getPortEntity();
    if (StringUtil.isNullOrEmpty(portEntity.getVpcId())) {
        throw new NetworkIdRequired();
    }

    checkPort(portEntity);

    return portService.createPort(projectId, portWebJson);
}
 
Example 24
Source Project: netty-4.1.22   Source File: Http2ChannelDuplexHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link Http2FrameStream} object.
 *
 * <p>This method is <em>thread-safe</em>.
 */
public final Http2FrameStream newStream() {
    Http2FrameCodec codec = frameCodec;
    if (codec == null) {
        throw new IllegalStateException(StringUtil.simpleClassName(Http2FrameCodec.class) + " not found." +
                " Has the handler been added to a pipeline?");
    }
    return codec.newStream();
}
 
Example 25
Source Project: netty4.0.27Learn   Source File: ReplayingDecoderBuffer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return StringUtil.simpleClassName(this) + '(' +
           "ridx=" +
           readerIndex() +
           ", " +
           "widx=" +
           writerIndex() +
           ')';
}
 
Example 26
Source Project: piggymetrics   Source File: ValidateTokenFilter.java    License: MIT License 5 votes vote down vote up
@Override
public Object run() throws ZuulException {
	RequestContext requestContext = RequestContext.getCurrentContext();

	String token = requestContext.getRequest().getHeader("Authorization");
	if (StringUtil.isNullOrEmpty(token)) {
		throw new ZuulException("no token found", HttpStatus.SC_UNAUTHORIZED, "no token found");
	}

	token = token.replace("Bearer ", ""); // remove prefix

	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", "Basic " + config.getBase64Credentials());

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	map.add("token", token);
	map.add("token_type_hint", "access_token");

	HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

	String url = config.getTokenIntrospectEndpoint();
	@SuppressWarnings("unchecked")
	Map<String, Object> resultMap = restTemplate.postForEntity(url, request, Map.class)
			.getBody();

	Boolean active = (Boolean) resultMap.get("active");

	if (active == null || !active) {
		throw new ZuulException("token inactive", HttpStatus.SC_UNAUTHORIZED, "token inactive");
	}

	String username = (String) resultMap.get("username");
	if (StringUtil.isNullOrEmpty(username)) {
		throw new ZuulException("username empty", HttpStatus.SC_UNAUTHORIZED, "username empty");
	}

	requestContext.addZuulRequestHeader("X-S2G-USERNAME", username);

	return null;
}
 
Example 27
Source Project: teaching   Source File: YouBianCodeUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String[] cutYouBianCode(String code){
	if(code==null || StringUtil.isNullOrEmpty(code)){
		return null;
	}else{
		//获取标准长度为numLength+1,截取的数量为code.length/numLength+1
		int c = code.length()/(numLength+1);
		String[] cutcode = new String[c];
		for(int i =0 ; i <c;i++){
			cutcode[i] = code.substring(0,(i+1)*(numLength+1));
		}
		return cutcode;
	}
	
}
 
Example 28
Source Project: netty4.0.27Learn   Source File: AbstractOioByteChannel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    for (;;) {
        Object msg = in.current();
        if (msg == null) {
            // nothing left to write
            break;
        }
        if (msg instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf) msg;
            int readableBytes = buf.readableBytes();
            while (readableBytes > 0) {
                doWriteBytes(buf);
                int newReadableBytes = buf.readableBytes();
                in.progress(readableBytes - newReadableBytes);
                readableBytes = newReadableBytes;
            }
            in.remove();
        } else if (msg instanceof FileRegion) {
            FileRegion region = (FileRegion) msg;
            long transfered = region.transfered();
            doWriteFileRegion(region);
            in.progress(region.transfered() - transfered);
            in.remove();
        } else {
            in.remove(new UnsupportedOperationException(
                    "unsupported message type: " + StringUtil.simpleClassName(msg)));
        }
    }
}
 
Example 29
Source Project: netty-4.1.22   Source File: HttpPostRequestDecoder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check from the request ContentType if this request is a Multipart request. 检查请求内容类型是否该请求是多部分请求。
 * @return an array of String if multipartDataBoundary exists with the multipartDataBoundary
 * as first element, charset if any as second (missing if not set), else null
 */
protected static String[] getMultipartDataBoundary(String contentType) {
    // Check if Post using "multipart/form-data; boundary=--89421926422648 [; charset=xxx]"
    String[] headerContentType = splitHeaderContentType(contentType);
    final String multiPartHeader = HttpHeaderValues.MULTIPART_FORM_DATA.toString();
    if (headerContentType[0].regionMatches(true, 0, multiPartHeader, 0 , multiPartHeader.length())) {
        int mrank;
        int crank;
        final String boundaryHeader = HttpHeaderValues.BOUNDARY.toString();
        if (headerContentType[1].regionMatches(true, 0, boundaryHeader, 0, boundaryHeader.length())) {
            mrank = 1;
            crank = 2;
        } else if (headerContentType[2].regionMatches(true, 0, boundaryHeader, 0, boundaryHeader.length())) {
            mrank = 2;
            crank = 1;
        } else {
            return null;
        }
        String boundary = StringUtil.substringAfter(headerContentType[mrank], '=');
        if (boundary == null) {
            throw new ErrorDataDecoderException("Needs a boundary value");
        }
        if (boundary.charAt(0) == '"') {
            String bound = boundary.trim();
            int index = bound.length() - 1;
            if (bound.charAt(index) == '"') {
                boundary = bound.substring(1, index);
            }
        }
        final String charsetHeader = HttpHeaderValues.CHARSET.toString();
        if (headerContentType[crank].regionMatches(true, 0, charsetHeader, 0, charsetHeader.length())) {
            String charset = StringUtil.substringAfter(headerContentType[crank], '=');
            if (charset != null) {
                return new String[] {"--" + boundary, charset};
            }
        }
        return new String[] {"--" + boundary};
    }
    return null;
}
 
Example 30
Source Project: netty-4.1.22   Source File: HpackDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
private void decode(String encoded) throws Http2Exception {
    byte[] b = StringUtil.decodeHexDump(encoded);
    ByteBuf in = Unpooled.wrappedBuffer(b);
    try {
        hpackDecoder.decode(0, in, mockHeaders, true);
    } finally {
        in.release();
    }
}