/** * 获取一个接口的实现类 * @param defineClass * @param lookup 指定名称的实现类 * @return */ public Class<?> getImplClass(Class<?> defineClass, String lookup) { if (StringUtil.isNullOrEmpty(lookup)) { return null; } Collection<SessionBean> beans = serviceimplmap.get(defineClass.getName()); if (CollectionUtil.isNotEmpty(beans)) { Iterator<SessionBean> beanite = beans.iterator(); while (beanite.hasNext()) { SessionBean bean = beanite.next(); if (lookup.toLowerCase().equals(bean.getLookup().toLowerCase())) { return bean.getImplClass().getCls(); } } } return null; }
private void doLeaveRoom(Channel channel, LeaveRoomMessage leaveRoom) { UserInfo userInfo = NetoChannelUtil.getUserInfo(channel); if (userInfo == null || StringUtil.isNullOrEmpty(userInfo.getUserId())) { throw new NotFoundUserInfoException(Constants.StatusCode.NOT_FOUND_USERINFO, "Not Found User Info"); } String inputId = leaveRoom.getUserId(); String sessionId = userInfo.getUserId(); if (userInfo.getAccessLevel() > Constants.AccessLevel.ADMIN) { globalChannelGroup.stream().filter(c -> c != null && leaveRoom.getUserId().equals(NetoChannelUtil.getUserInfo(c).getUserId())) .forEach(c -> { leaveRoom(c); leaveRoom.setStatusCode(Constants.StatusCode.OK); channel.writeAndFlush(leaveRoom); }); } else if (sessionId.equals(inputId)) { leaveRoom(channel); leaveRoom.setStatusCode(Constants.StatusCode.OK); sendMessage(channel, leaveRoom); } else { throw new BadAccessException(Constants.StatusCode.FAIL, "bad access!"); } }
private String createNodeKey(String... nodes) { if (nodes == null || StringUtil.isNullOrEmpty(nodes[0])) { return ""; } final StringBuilder sb = new StringBuilder(); for (int i = 0, len = nodes.length; i < len; i++) { if (i > 0) { sb.append(":"); } sb.append(nodes[i]); } return sb.toString(); }
private ByteBuf getEncodedTargetAddress(ByteBufAllocator allocator, boolean resolve) throws ProxyConnectException { InetSocketAddress remoteAddress = destinationAddress(); SocksAddressType remoteAddressType; String remoteHost; if (!resolve || remoteAddress.isUnresolved()) { remoteAddressType = SocksAddressType.DOMAIN; remoteHost = remoteAddress.getHostString(); } else { remoteHost = remoteAddress.getAddress().getHostAddress(); if (NetUtil.isValidIpV4Address(remoteHost)) { remoteAddressType = SocksAddressType.IPv4; } else if (NetUtil.isValidIpV6Address(remoteHost)) { remoteAddressType = SocksAddressType.IPv6; } else { throw new ProxyConnectException("unknown address type: " + StringUtil.simpleClassName(remoteHost)); } } int remotePort = remoteAddress.getPort(); SocksCmdRequest request = new SocksCmdRequest(SocksCmdType.UNKNOWN, remoteAddressType, remoteHost, remotePort); return SSocksAddressEncoder.INSTANCE.encode(allocator, request); }
@SuppressWarnings("unchecked") @Override public void execute(ShardingContext shardingContext) { List<MessageEntity> findList = this.messageEntityMapper.queryTransactionNotComplete(); log.info("查询没有完成的事务消息(查询1分钟之前的)记录数:{}",findList); if(findList.isEmpty()){ return; } try { for(MessageEntity entity : findList){ Message message = new Message(); message.setMessageId(entity.getMessageId()); message.setBody(entity.getBody()); message.setDestination(entity.getDestination()); if(!StringUtil.isNullOrEmpty(entity.getProperties())){ message.setProperties(JSON.parseObject(entity.getProperties(), Map.class)); } RemotingCommand request = RemotingCommand.buildRequestCmd(message, RequestCode.SEND_MESSAGE, MessageCode.TRANSACTION_CHECK_MESSAGE); request.setGroup(entity.getGroup()); sentToClient(request); } } catch (Exception e) { log.error("回查发送异常:{}",e); } }
public static void checkMessage(Message msg,DefaultMQProducer defaultMQProducer) throws MQClientException { if (null == msg) { throw new MQClientException(1,"the message is null"); } if (null == msg.getBody()) { throw new MQClientException(2,"the message body is null"); } if (0 == msg.getBody().length) { throw new MQClientException(3,"the message body length is zero"); } if (msg.getBody().length > defaultMQProducer.getMaxMessageSize()) { throw new MQClientException(4,"the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize()); } if(StringUtil.isNullOrEmpty(msg.getMessageId())){ msg.setMessageId(UUID.randomUUID().toString()); } }
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; } } }
public String toString() { StringBuilder buf = new StringBuilder(); buf.append(directArenas.length); buf.append(" direct arena(s):"); buf.append(StringUtil.NEWLINE); for (PoolArena<ByteBuffer> a : directArenas) { buf.append(a); } buf.append("Large buffers outstanding: "); buf.append(this.hugeBufferCount.get()); buf.append(" totaling "); buf.append(this.hugeBufferSize.get()); buf.append(" bytes."); buf.append('\n'); buf.append("Normal buffers outstanding: "); buf.append(this.normalBufferCount.get()); buf.append(" totaling "); buf.append(this.normalBufferSize.get()); buf.append(" bytes."); return buf.toString(); }
@Test public void calculateProcessingTime_ShouldSetProcessingTimeInAllUnitsAndHumanReadableString() throws InterruptedException { assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInMillis()).isEqualTo(0); assertThat(baseSyncStatistics.getLatestBatchHumanReadableProcessingTime()).isEqualTo(StringUtil.EMPTY_STRING); final int waitingTimeInMillis = 100; Thread.sleep(waitingTimeInMillis); baseSyncStatistics.calculateProcessingTime(); assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInDays()).isGreaterThanOrEqualTo(0); assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInHours()).isGreaterThanOrEqualTo(0); assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInMinutes()).isGreaterThanOrEqualTo(0); assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInSeconds()) .isGreaterThanOrEqualTo(waitingTimeInMillis / 1000); assertThat(baseSyncStatistics.getLatestBatchProcessingTimeInMillis()) .isGreaterThanOrEqualTo(waitingTimeInMillis); final long remainingMillis = baseSyncStatistics.getLatestBatchProcessingTimeInMillis() - TimeUnit.SECONDS.toMillis(baseSyncStatistics.getLatestBatchProcessingTimeInSeconds()); assertThat(baseSyncStatistics.getLatestBatchHumanReadableProcessingTime()) .contains(format(", %dms", remainingMillis)); }
@Override protected Object filterOutboundMessage(Object msg) { if (msg instanceof UkcpPacket) { UkcpPacket p = (UkcpPacket) msg; ByteBuf content = p.content(); if (isSingleDirectBuffer(content)) { return p; } content.retain(); // newDirectBuffer method call release method of content UkcpPacket np = UkcpPacket.newInstance(newDirectBuffer(content), p.remoteAddress()); p.release(); return np; } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); }
private void checkParams(String cluster, String ipAddress, Integer port, List<SeedMember> seedMembers) throws Exception { String f = "[%s] is required!"; String who = null; if (StringUtil.isNullOrEmpty(cluster)) { who = "cluster"; } else if (StringUtil.isNullOrEmpty(ipAddress)) { who = "ip"; } else if (StringUtil.isNullOrEmpty(String.valueOf(port))) { who = "port"; } else if (seedMembers == null || seedMembers.isEmpty()) { who = "seed member"; } if (who != null) { throw new IllegalArgumentException(String.format(f, who)); } }
private long[] parseRange(String range, long availableLength) throws IllegalArgumentException { if (StringUtil.isNullOrEmpty(range)) { return null; } Matcher m = RANGE_HEADER.matcher(range); if (!m.matches()) { throw new IllegalArgumentException("Unsupported range: %s" + range); } long[] result = new long[2]; result[0] = Long.parseLong(m.group(1)); String sed = m.group(2); result[1] = StringUtil.isNullOrEmpty(sed) ? availableLength - 1 : Long.parseLong(sed); if (result[0] > result[1] || result[1] >= availableLength) { throw new IllegalArgumentException("Unsupported range: %s" + range); } return result; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String version = requestContext.getHeaderString(HEADER_VERSION); if (StringUtil.isNullOrEmpty(version)) { return; } URI requestUri = requestContext.getUriInfo().getRequestUri(); try { URI newUri = new URI(requestUri.getScheme(), requestUri.getAuthority(), "/" + version + requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment()); requestContext.setRequestUri(newUri); } catch (URISyntaxException e) { String info = String.format("requestContext.setRequestUri error: version[%s]=>requestUri[%s]", version, requestUri); log.error(info, e); } }
EventHub(String name, String grpcURL, ExecutorService executorService, Properties properties) throws InvalidArgumentException { Exception e = checkGrpcUrl(grpcURL); if (e != null) { throw new InvalidArgumentException("Bad event hub url.", e); } if (StringUtil.isNullOrEmpty(name)) { throw new InvalidArgumentException("Invalid name for eventHub"); } this.url = grpcURL; this.name = name; this.executorService = executorService; this.properties = properties == null ? null : (Properties) properties.clone(); //keep our own copy. }
public static Properties parseGrpcUrl(String url) { if (StringUtil.isNullOrEmpty(url)) { throw new RuntimeException("URL cannot be null or empty"); } Properties props = new Properties(); Pattern p = Pattern.compile("([^:]+)[:]//([^:]+)[:]([0-9]+)", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(url); if (m.matches()) { props.setProperty("protocol", m.group(1)); props.setProperty("host", m.group(2)); props.setProperty("port", m.group(3)); String protocol = props.getProperty("protocol"); if (!"grpc".equals(protocol) && !"grpcs".equals(protocol)) { throw new RuntimeException(String.format("Invalid protocol expected grpc or grpcs and found %s.", protocol)); } } else { throw new RuntimeException("URL must be of the format protocol://host:port"); } // TODO: allow all possible formats of the URL return props; }
Peer(String name, String grpcURL, Properties properties) throws InvalidArgumentException { Exception e = checkGrpcUrl(grpcURL); if (e != null) { throw new InvalidArgumentException("Bad peer url.", e); } if (StringUtil.isNullOrEmpty(name)) { throw new InvalidArgumentException("Invalid name for peer"); } this.url = grpcURL; this.name = name; this.properties = properties == null ? null : (Properties) properties.clone(); //keep our own copy. }
/** * starts Field Agent module * * @throws Exception */ public void start() throws Exception { if (StringUtil.isNullOrEmpty(Configuration.getInstanceId()) || StringUtil.isNullOrEmpty(Configuration.getAccessToken())) StatusReporter.setFieldAgentStatus().setContollerStatus(ControllerStatus.NOT_PROVISIONED); elementManager = ElementManager.getInstance(); orchestrator = new Orchestrator(); boolean isConnected = ping(); getFabricConfig(); if (!notProvisioned()) { loadRegistries(!isConnected); loadElementsList(!isConnected); loadElementsConfig(!isConnected); loadRoutes(!isConnected); } new Thread(pingController, "FieldAgent : Ping").start(); new Thread(getChangesList, "FieldAgent : GetChangesList").start(); new Thread(postStatus, "FieldAgent : PostStaus").start(); }
@Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(directArenas.length); buf.append(" direct arena(s):"); buf.append(StringUtil.NEWLINE); for (PoolArena<ByteBuffer> a : directArenas) { buf.append(a); } buf.append("Large buffers outstanding: "); buf.append(hugeBufferCount.get()); buf.append(" totaling "); buf.append(hugeBufferSize.get()); buf.append(" bytes."); buf.append('\n'); buf.append("Normal buffers outstanding: "); buf.append(normalBufferCount.get()); buf.append(" totaling "); buf.append(normalBufferSize.get()); buf.append(" bytes."); return buf.toString(); }
/** * 最终回调 * * @param callback * 回调执行 */ void finalCallback(int errorCode, HttpResponse response, String content) { String responseText = ""; if (!clearResource()) return; if (response != null) { responseText = response.toString(); responseText = responseText .substring(responseText.indexOf(StringUtil.NEWLINE) + StringUtil.NEWLINE.length()); } this.response = new NHttpResponse(responseText, content, response != null ? response.getStatus().code() : 0, errorCode); NHttpRequestCallback cb = requestConfig.callback(); if (cb != null) try { cb.callback(errorCode, response, content); } catch (Throwable e) { log.error("NettyHttpRequest::Callback. ", e); } requestMission.missionFinish(); }
/** * Constructor specifying the destination web socket location * * @param version * the protocol version * @param uri * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be * sent to this URL. * @param subprotocols * CSV of supported protocols. Null if sub protocols not supported. * @param maxFramePayloadLength * Maximum length of a frame's payload */ protected WebSocketServerHandshaker( WebSocketVersion version, String uri, String subprotocols, int maxFramePayloadLength) { this.version = version; this.uri = uri; if (subprotocols != null) { String[] subprotocolArray = StringUtil.split(subprotocols, ','); for (int i = 0; i < subprotocolArray.length; i++) { subprotocolArray[i] = subprotocolArray[i].trim(); } this.subprotocols = subprotocolArray; } else { this.subprotocols = EmptyArrays.EMPTY_STRINGS; } this.maxFramePayloadLength = maxFramePayloadLength; }
/** * Selects the first matching supported sub protocol * * @param requestedSubprotocols * CSV of protocols to be supported. e.g. "chat, superchat" * @return First matching supported sub protocol. Null if not found. */ protected String selectSubprotocol(String requestedSubprotocols) { if (requestedSubprotocols == null || subprotocols.length == 0) { return null; } String[] requestedSubprotocolArray = StringUtil.split(requestedSubprotocols, ','); for (String p: requestedSubprotocolArray) { String requestedSubprotocol = p.trim(); for (String supportedSubprotocol: subprotocols) { if (SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol) || requestedSubprotocol.equals(supportedSubprotocol)) { selectedSubprotocol = requestedSubprotocol; return requestedSubprotocol; } } } // No match found return null; }
@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(); }
@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(); }
protected void run() throws Throwable { List<TestsuitePermutation.BootstrapFactory<T>> combos = newFactories(); for (ByteBufAllocator allocator: newAllocators()) { int i = 0; for (TestsuitePermutation.BootstrapFactory<T> e: combos) { cb = e.newInstance(); configure(cb, allocator); logger.info(String.format( "Running: %s %d of %d with %s", testName.getMethodName(), ++ i, combos.size(), StringUtil.simpleClassName(allocator))); try { Method m = getClass().getDeclaredMethod( TestUtils.testMethodName(testName), clazz); m.invoke(this, cb); } catch (InvocationTargetException ex) { throw ex.getCause(); } } } }
protected void run() throws Throwable { List<TestsuitePermutation.BootstrapComboFactory<SB, CB>> combos = newFactories(); for (ByteBufAllocator allocator: newAllocators()) { int i = 0; for (TestsuitePermutation.BootstrapComboFactory<SB, CB> e: combos) { sb = e.newServerInstance(); cb = e.newClientInstance(); configure(sb, cb, allocator); logger.info(String.format( "Running: %s %d of %d (%s + %s) with %s", testName.getMethodName(), ++ i, combos.size(), sb, cb, StringUtil.simpleClassName(allocator))); try { Method m = getClass().getMethod( TestUtils.testMethodName(testName), sbClazz, cbClazz); m.invoke(this, sb, cb); } catch (InvocationTargetException ex) { throw ex.getCause(); } } } }
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 protected Object filterOutboundMessage(Object msg) { if (msg instanceof DatagramPacket || msg instanceof ByteBuf) { return msg; } if (msg instanceof AddressedEnvelope) { @SuppressWarnings("unchecked") AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg; if (e.content() instanceof ByteBuf) { return msg; } } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); }
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; }
@Override protected final Object filterOutboundMessage(Object msg) { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; if (buf.isDirect()) { return msg; } return newDirectBuffer(buf); } if (msg instanceof FileRegion) { return msg; } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); }
@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(), newDirectBuffer(m, buf)); } throw new UnsupportedOperationException( "unsupported message type: " + StringUtil.simpleClassName(msg) + " (expected: " + StringUtil.simpleClassName(SctpMessage.class)); }
@Override public String toString() { if (head == null) { return "none"; } StringBuilder buf = new StringBuilder(); for (PoolChunk<T> cur = head;;) { buf.append(cur); cur = cur.next; if (cur == null) { break; } buf.append(StringUtil.NEWLINE); } return buf.toString(); }
@Override public String toString() { if (refCnt() == 0) { return StringUtil.simpleClassName(this) + "(freed)"; } StringBuilder buf = new StringBuilder() .append(StringUtil.simpleClassName(this)) .append("(ridx: ").append(readerIndex) .append(", widx: ").append(writerIndex) .append(", cap: ").append(capacity()); if (maxCapacity != Integer.MAX_VALUE) { buf.append('/').append(maxCapacity); } ByteBuf unwrapped = unwrap(); if (unwrapped != null) { buf.append(", unwrapped: ").append(unwrapped); } buf.append(')'); return buf.toString(); }
private 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; } } }
protected StringBuilder toStringBuilder() { StringBuilder buf = new StringBuilder(64) .append(StringUtil.simpleClassName(this)) .append('@') .append(Integer.toHexString(hashCode())); Object result = this.result; if (result == SUCCESS) { buf.append("(success)"); } else if (result == UNCANCELLABLE) { buf.append("(uncancellable)"); } else if (result instanceof CauseHolder) { buf.append("(failure(") .append(((CauseHolder) result).cause) .append(')'); } else { buf.append("(incomplete)"); } return buf; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String version = requestContext.getHeaderString("version"); if (StringUtil.isNullOrEmpty(version)) { return; } URI requestUri = requestContext.getUriInfo().getRequestUri(); try { URI newUri = new URI(requestUri.getScheme(), requestUri.getAuthority(), "/" + version + requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment()); requestContext.setRequestUri(newUri); } catch (URISyntaxException e) { log.error("requestContext.setRequestUri error:{}=>{}", version, requestUri); } }
/** * 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 An entry whose name is {@link HttpHeaderNames#TE}. * @param out the resulting HTTP/2 headers. */ private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry, HttpHeaders 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 { 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; } } } }
/** * Finds and creates Parser instances from the specified Class. * * @param clazz The Class to find the Parser instance within. * @param path The path to the Parsers source file. * @return The created Parser instance. * @throws NoSuchMethodException If there was no constructor found for the specified parameters. * @throws InvocationTargetException If the Parsers constructor throws an exception. * @throws IllegalAccessException If the Parsers constructor object is enforcing Java language access control and * the underlying constructor is inaccessible. * @throws InstantiationException If the Parser is an abstract class. */ private Parser<?, ?> find(Class<Parser<?, ?>> clazz, String path) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { Class<?>[] params = constructor.getParameterTypes(); switch (params.length) { case 1: Class<?> parameter = path == null ? context.getClass() : path.getClass(); Object argument = path == null ? context : path; return clazz.getConstructor(parameter).newInstance(argument); case 2: return clazz.getConstructor(String.class, ServerContext.class).newInstance(path, context); } } String className = StringUtil.simpleClassName(clazz); throw new NoSuchMethodException("Unable to find suitable constructor, only " + className + "(String), " + className + "(ServerContext) or " + className + "(String, ServerContext) are permitted."); }
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())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }