类io.netty.util.internal.StringUtil源码实例Demo

下面列出了怎么用io.netty.util.internal.StringUtil的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: NettyChat   文件: MsgTimeoutTimerManager.java
/**
 * 从发送超时管理器中移除消息,并停止定时器
 *
 * @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);
}
 
源代码2 项目: netty-4.1.22   文件: NioSctpChannel.java
@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));
}
 
源代码3 项目: armeria   文件: ArmeriaHttpUtil.java
/**
 * 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;
            }
        }
    }
}
 
源代码4 项目: netty-4.1.22   文件: DefaultDnsRawRecord.java
@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();
}
 
源代码5 项目: netty-4.1.22   文件: DefaultDnsQuestion.java
@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();
}
 
源代码6 项目: netty-4.1.22   文件: AbstractDnsRecord.java
@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();
}
 
源代码7 项目: netty-4.1.22   文件: LocalChannelRegistry.java
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;
}
 
源代码8 项目: netty-4.1.22   文件: Base64Test.java
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();
    }
}
 
源代码9 项目: pdown-core   文件: URLHttpDownBootstrapBuilder.java
@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();
}
 
@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();
}
 
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()][]);
}
 
@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();
}
 
源代码13 项目: netty4.0.27Learn   文件: AutobahnServerHandler.java
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()));
    }
}
 
@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);
}
 
源代码15 项目: netty-4.1.22   文件: DefaultThreadFactory.java
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;
            }
    }
}
 
源代码16 项目: netty-4.1.22   文件: DefaultSpdySynReplyFrame.java
@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();
}
 
源代码17 项目: netty-4.1.22   文件: DefaultSpdyDataFrame.java
@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();
}
 
源代码18 项目: netty-http2   文件: DefaultHttpPriorityFrame.java
@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();
}
 
源代码19 项目: netty-4.1.22   文件: ReadOnlyByteBufferBuf.java
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());
}
 
@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();
}
 
源代码21 项目: netty-4.1.22   文件: PoolArena.java
@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();
}
 
源代码22 项目: elephant   文件: DefaultMQProducerImpl.java
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);
}
      
  }
 
源代码23 项目: alcor   文件: PortController.java
/**
 * 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);
}
 
源代码24 项目: netty-4.1.22   文件: Http2ChannelDuplexHandler.java
/**
 * 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();
}
 
源代码25 项目: netty4.0.27Learn   文件: ReplayingDecoderBuffer.java
@Override
public String toString() {
    return StringUtil.simpleClassName(this) + '(' +
           "ridx=" +
           readerIndex() +
           ", " +
           "widx=" +
           writerIndex() +
           ')';
}
 
源代码26 项目: piggymetrics   文件: ValidateTokenFilter.java
@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;
}
 
源代码27 项目: teaching   文件: YouBianCodeUtil.java
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;
	}
	
}
 
源代码28 项目: netty4.0.27Learn   文件: AbstractOioByteChannel.java
@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)));
        }
    }
}
 
源代码29 项目: netty-4.1.22   文件: HttpPostRequestDecoder.java
/**
 * 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;
}
 
源代码30 项目: netty-4.1.22   文件: HpackDecoderTest.java
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();
    }
}
 
 类所在包
 同包方法