proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
normanmaurer_netty-in-action
netty-in-action/chapter11/src/main/java/nia/chapter11/WebSocketServerInitializer.java
WebSocketServerInitializer
initChannel
class WebSocketServerInitializer extends ChannelInitializer<Channel> { @Override protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>} public static final class TextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override public void ...
ch.pipeline().addLast( new HttpServerCodec(), new HttpObjectAggregator(65536), new WebSocketServerProtocolHandler("/websocket"), new TextFrameHandler(), new BinaryFrameHandler(), new ContinuationFrameHandler());
248
71
319
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter12/src/main/java/nia/chapter12/ChatServer.java
ChatServer
destroy
class ChatServer { private final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); private final EventLoopGroup group = new NioEventLoopGroup(); private Channel channel; public ChannelFuture start(InetSocketAddress address) { ServerBootstrap bootstrap...
if (channel != null) { channel.close(); } channelGroup.close(); group.shutdownGracefully();
364
39
403
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter12/src/main/java/nia/chapter12/ChatServerInitializer.java
ChatServerInitializer
initChannel
class ChatServerInitializer extends ChannelInitializer<Channel> { private final ChannelGroup group; public ChatServerInitializer(ChannelGroup group) { this.group = group; } @Override protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>} }
ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(64 * 1024)); pipeline.addLast(new HttpRequestHandler("/ws")); pipeline.addLast(new WebSocketServerPro...
79
110
189
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter12/src/main/java/nia/chapter12/HttpRequestHandler.java
HttpRequestHandler
channelRead0
class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private final String wsUri; private static final File INDEX; static { URL location = HttpRequestHandler.class .getProtectionDomain() .getCodeSource().getLocation(); try { St...
if (wsUri.equalsIgnoreCase(request.getUri())) { ctx.fireChannelRead(request.retain()); } else { if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } RandomAccessFile file = new RandomAccessFile(INDEX, "r"); ...
337
370
707
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter12/src/main/java/nia/chapter12/SecureChatServer.java
SecureChatServer
main
class SecureChatServer extends ChatServer { private final SslContext context; public SecureChatServer(SslContext context) { this.context = context; } @Override protected ChannelInitializer<Channel> createInitializer( ChannelGroup group) { return new SecureChatServerInitiali...
if (args.length != 1) { System.err.println("Please give port as argument"); System.exit(1); } int port = Integer.parseInt(args[0]); SelfSignedCertificate cert = new SelfSignedCertificate(); SslContext context = SslContext.newServerContext( ...
117
186
303
<methods>public non-sealed void <init>() ,public void destroy() ,public static void main(java.lang.String[]) throws java.lang.Exception,public ChannelFuture start(java.net.InetSocketAddress) <variables>private Channel channel,private final ChannelGroup channelGroup,private final EventLoopGroup group
normanmaurer_netty-in-action
netty-in-action/chapter12/src/main/java/nia/chapter12/TextWebSocketFrameHandler.java
TextWebSocketFrameHandler
userEventTriggered
class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private final ChannelGroup group; public TextWebSocketFrameHandler(ChannelGroup group) { this.group = group; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object ev...
if (evt == WebSocketServerProtocolHandler .ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.pipeline().remove(HttpRequestHandler.class); group.writeAndFlush(new TextWebSocketFrame( "Client " + ctx.channel() + " joined")); group.add(ctx.cha...
145
112
257
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter13/src/main/java/nia/chapter13/LogEventBroadcaster.java
LogEventBroadcaster
run
class LogEventBroadcaster { private final EventLoopGroup group; private final Bootstrap bootstrap; private final File file; public LogEventBroadcaster(InetSocketAddress address, File file) { group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(group).cha...
Channel ch = bootstrap.bind(0).sync().channel(); long pointer = 0; for (;;) { long len = file.length(); if (len < pointer) { // file was reset pointer = len; } else if (len > pointer) { // Content was added ...
315
224
539
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter13/src/main/java/nia/chapter13/LogEventDecoder.java
LogEventDecoder
decode
class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket> { @Override protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>} }
ByteBuf data = datagramPacket.content(); int idx = data.indexOf(0, data.readableBytes(), LogEvent.SEPARATOR); String filename = data.slice(0, idx) .toString(CharsetUtil.UTF_8); String logMsg = data.slice(idx + 1, data.readableBytes()).toString(Charset...
72
140
212
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter13/src/main/java/nia/chapter13/LogEventEncoder.java
LogEventEncoder
encode
class LogEventEncoder extends MessageToMessageEncoder<LogEvent> { private final InetSocketAddress remoteAddress; public LogEventEncoder(InetSocketAddress remoteAddress) { this.remoteAddress = remoteAddress; } @Override protected void encode(ChannelHandlerContext channelHandlerContext, ...
byte[] file = logEvent.getLogfile().getBytes(CharsetUtil.UTF_8); byte[] msg = logEvent.getMsg().getBytes(CharsetUtil.UTF_8); ByteBuf buf = channelHandlerContext.alloc() .buffer(file.length + msg.length + 1); buf.writeBytes(file); buf.writeByte(LogEvent.SEPARATOR); ...
106
126
232
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter13/src/main/java/nia/chapter13/LogEventHandler.java
LogEventHandler
channelRead0
class LogEventHandler extends SimpleChannelInboundHandler<LogEvent> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void channelRead0(ChannelHandlerContext ct...
StringBuilder builder = new StringBuilder(); builder.append(event.getReceivedTimestamp()); builder.append(" ["); builder.append(event.getSource().toString()); builder.append("] ["); builder.append(event.getLogfile()); builder.append("] : "); builder.appen...
104
100
204
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter13/src/main/java/nia/chapter13/LogEventMonitor.java
LogEventMonitor
main
class LogEventMonitor { private final EventLoopGroup group; private final Bootstrap bootstrap; public LogEventMonitor(InetSocketAddress address) { group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioDatagramChannel.class) ...
if (args.length != 1) { throw new IllegalArgumentException( "Usage: LogEventMonitor <port>"); } LogEventMonitor monitor = new LogEventMonitor( new InetSocketAddress(Integer.parseInt(args[0]))); try { Channel channel = monitor.bind(); ...
264
116
380
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter2/Client/src/main/java/nia/chapter2/echoclient/EchoClient.java
EchoClient
start
class EchoClient { private final String host; private final int port; public EchoClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception {<FILL_FUNCTION_BODY>} public static void main(String[] args) throws ...
EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>()...
193
169
362
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter2/Server/src/main/java/nia/chapter2/echoserver/EchoServer.java
EchoServer
start
class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: " + EchoServer.class.getSimpleName() + " <port>"...
final EchoServerHandler serverHandler = new EchoServerHandler(); EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetS...
157
216
373
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter2/Server/src/main/java/nia/chapter2/echoserver/EchoServerHandler.java
EchoServerHandler
channelRead
class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) {<FILL_FUNCTION_BODY>} @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.EMPTY_BUF...
ByteBuf in = (ByteBuf) msg; System.out.println( "Server received: " + in.toString(CharsetUtil.UTF_8)); ctx.write(in);
150
51
201
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter4/src/main/java/nia/chapter4/ChannelOperationExamples.java
ChannelOperationExamples
writingToChannel
class ChannelOperationExamples { private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel(); /** * Listing 4.5 Writing to a Channel */ public static void writingToChannel() {<FILL_FUNCTION_BODY>} /** * Listing 4.6 Using a Channel from many threads */ public sta...
Channel channel = CHANNEL_FROM_SOMEWHERE; // Get the channel reference from somewhere ByteBuf buf = Unpooled.copiedBuffer("your data", CharsetUtil.UTF_8); ChannelFuture cf = channel.writeAndFlush(buf); cf.addListener(new ChannelFutureListener() { @Override public...
259
151
410
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter4/src/main/java/nia/chapter4/NettyNioServer.java
NettyNioServer
server
class NettyNioServer { public void server(int port) throws Exception {<FILL_FUNCTION_BODY>} }
final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"))); NioEventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group).channel...
34
289
323
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter4/src/main/java/nia/chapter4/NettyOioServer.java
NettyOioServer
server
class NettyOioServer { public void server(int port) throws Exception {<FILL_FUNCTION_BODY>} }
final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"))); EventLoopGroup group = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(OioSe...
36
278
314
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter4/src/main/java/nia/chapter4/PlainNioServer.java
PlainNioServer
serve
class PlainNioServer { public void serve(int port) throws IOException {<FILL_FUNCTION_BODY>} }
ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); ss.bind(address); Selector selector = Selector.open(); serve...
34
471
505
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter4/src/main/java/nia/chapter4/PlainOioServer.java
PlainOioServer
serve
class PlainOioServer { public void serve(int port) throws IOException {<FILL_FUNCTION_BODY>} }
final ServerSocket socket = new ServerSocket(port); try { for(;;) { final Socket clientSocket = socket.accept(); System.out.println( "Accepted connection from " + clientSocket); new Thread(new Runnable() { ...
34
228
262
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter6/src/main/java/nia/chapter6/ChannelFutures.java
ChannelFutures
addingChannelFutureListener
class ChannelFutures { private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel(); private static final ByteBuf SOME_MSG_FROM_SOMEWHERE = Unpooled.buffer(1024); /** * Listing 6.13 Adding a ChannelFutureListener to a ChannelFuture * */ public static void addingChannelFutureLi...
Channel channel = CHANNEL_FROM_SOMEWHERE; // get reference to pipeline; ByteBuf someMessage = SOME_MSG_FROM_SOMEWHERE; // get reference to pipeline; //... io.netty.channel.ChannelFuture future = channel.write(someMessage); future.addListener(new ChannelFutureListener() { ...
111
147
258
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter6/src/main/java/nia/chapter6/ModifyChannelPipeline.java
ModifyChannelPipeline
modifyPipeline
class ModifyChannelPipeline { private static final ChannelPipeline CHANNEL_PIPELINE_FROM_SOMEWHERE = DUMMY_INSTANCE; /** * Listing 6.5 Modify the ChannelPipeline * */ public static void modifyPipeline() {<FILL_FUNCTION_BODY>} private static final class FirstHandler extends ChannelHan...
ChannelPipeline pipeline = CHANNEL_PIPELINE_FROM_SOMEWHERE; // get reference to pipeline; FirstHandler firstHandler = new FirstHandler(); pipeline.addLast("handler1", firstHandler); pipeline.addFirst("handler2", new SecondHandler()); pipeline.addLast("handler3", new ThirdHandler...
166
124
290
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter6/src/main/java/nia/chapter6/OutboundExceptionHandler.java
OutboundExceptionHandler
write
class OutboundExceptionHandler extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {<FILL_FUNCTION_BODY>} }
promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) { if (!f.isSuccess()) { f.cause().printStackTrace(); f.channel().close(); } } });
52
69
121
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter6/src/main/java/nia/chapter6/UnsharableHandler.java
UnsharableHandler
channelRead
class UnsharableHandler extends ChannelInboundHandlerAdapter { private int count; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) {<FILL_FUNCTION_BODY>} }
count++; System.out.println("inboundBufferUpdated(...) called the " + count + " time"); ctx.fireChannelRead(msg);
54
43
97
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter6/src/main/java/nia/chapter6/WriteHandlers.java
WriteHandlers
writeViaChannelPipeline
class WriteHandlers { private static final ChannelHandlerContext CHANNEL_HANDLER_CONTEXT_FROM_SOMEWHERE = DUMMY_INSTANCE; private static final ChannelPipeline CHANNEL_PIPELINE_FROM_SOMEWHERE = DummyChannelPipeline.DUMMY_INSTANCE; /** * Listing 6.6 Accessing the Channel from a ChannelHandlerContext ...
ChannelHandlerContext ctx = CHANNEL_HANDLER_CONTEXT_FROM_SOMEWHERE; //get reference form somewhere ChannelPipeline pipeline = ctx.pipeline(); //get reference form somewhere pipeline.write(Unpooled.copiedBuffer("Netty in Action", CharsetUtil.UTF_8));
341
81
422
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter7/src/main/java/nia/chapter7/EventLoopExamples.java
EventLoopExamples
blockUntilEventsReady
class EventLoopExamples { /** * Listing 7.1 Executing tasks in an event loop * */ public static void executeTaskInEventLoop() { boolean terminated = true; //... while (!terminated) { List<Runnable> readyEvents = blockUntilEventsReady(); for (Runnable ev:...
return Collections.<Runnable>singletonList(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } });...
138
78
216
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter7/src/main/java/nia/chapter7/ScheduleExamples.java
ScheduleExamples
scheduleViaEventLoop
class ScheduleExamples { private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel(); /** * Listing 7.2 Scheduling a task with a ScheduledExecutorService * */ public static void schedule() { ScheduledExecutorService executor = Executors.newScheduledThreadP...
Channel ch = CHANNEL_FROM_SOMEWHERE; // get reference from somewhere ScheduledFuture<?> future = ch.eventLoop().schedule( new Runnable() { @Override public void run() { System.out.println("60 seconds later"); } }, 60, TimeUnit.SECO...
542
92
634
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapClient.java
BootstrapClient
operationComplete
class BootstrapClient { public static void main(String args[]) { BootstrapClient client = new BootstrapClient(); client.bootstrap(); } /** * Listing 8.1 Bootstrapping a client * */ public void bootstrap() { EventLoopGroup group = new NioEventLoopGroup(); Bootst...
if (channelFuture.isSuccess()) { System.out.println("Connection established"); } else { System.err.println("Connection attempt failed"); channelFuture.cause().printStackTrace(); }
267
56
323
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapClientWithOptionsAndAttrs.java
BootstrapClientWithOptionsAndAttrs
bootstrap
class BootstrapClientWithOptionsAndAttrs { /** * Listing 8.7 Using attributes * */ public void bootstrap() {<FILL_FUNCTION_BODY>} }
final AttributeKey<Integer> id = AttributeKey.newInstance("ID"); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .handler( new SimpleChannelInboundHandler<ByteBuf>() { @O...
52
284
336
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapDatagramChannel.java
BootstrapDatagramChannel
bootstrap
class BootstrapDatagramChannel { /** * Listing 8.8 Using Bootstrap with DatagramChannel */ public void bootstrap() {<FILL_FUNCTION_BODY>} }
Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new OioEventLoopGroup()).channel( OioDatagramChannel.class).handler( new SimpleChannelInboundHandler<DatagramPacket>() { @Override public void channelRead0(ChannelHandlerContext ctx, ...
53
215
268
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapServer.java
BootstrapServer
bootstrap
class BootstrapServer { /** * Listing 8.4 Bootstrapping a server * */ public void bootstrap() {<FILL_FUNCTION_BODY>} }
NioEventLoopGroup group = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protec...
50
234
284
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapSharingEventLoopGroup.java
BootstrapSharingEventLoopGroup
channelRead0
class BootstrapSharingEventLoopGroup { /** * Listing 8.5 Bootstrapping a server * */ public void bootstrap() { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) .channel(NioServerSocketChannel.class) ...
if (connectFuture.isDone()) { // do something with the data }
435
25
460
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/BootstrapWithInitializer.java
BootstrapWithInitializer
bootstrap
class BootstrapWithInitializer { /** * Listing 8.6 Bootstrapping and using ChannelInitializer * */ public void bootstrap() throws InterruptedException {<FILL_FUNCTION_BODY>} final class ChannelInitializerImpl extends ChannelInitializer<Channel> { @Override protected void initChan...
ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializerImpl()); ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080)); ...
144
90
234
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/GracefulShutdown.java
GracefulShutdown
bootstrap
class GracefulShutdown { public static void main(String args[]) { GracefulShutdown client = new GracefulShutdown(); client.bootstrap(); } /** * Listing 8.9 Graceful shutdown */ public void bootstrap() {<FILL_FUNCTION_BODY>} }
EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) //... .handler( new SimpleChannelInboundHandler<ByteBuf>() { @Override ...
83
194
277
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter8/src/main/java/nia/chapter8/InvalidBootstrapClient.java
InvalidBootstrapClient
bootstrap
class InvalidBootstrapClient { public static void main(String args[]) { InvalidBootstrapClient client = new InvalidBootstrapClient(); client.bootstrap(); } /** * Listing 8.3 Incompatible Channel and EventLoopGroup * */ public void bootstrap() {<FILL_FUNCTION_BODY>} }
EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(OioSocketChannel.class) .handler(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0( ...
89
152
241
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter9/src/main/java/nia/chapter9/AbsIntegerEncoder.java
AbsIntegerEncoder
encode
class AbsIntegerEncoder extends MessageToMessageEncoder<ByteBuf> { @Override protected void encode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>} }
while (in.readableBytes() >= 4) { int value = Math.abs(in.readInt()); out.add(value); }
65
42
107
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter9/src/main/java/nia/chapter9/FixedLengthFrameDecoder.java
FixedLengthFrameDecoder
decode
class FixedLengthFrameDecoder extends ByteToMessageDecoder { private final int frameLength; public FixedLengthFrameDecoder(int frameLength) { if (frameLength <= 0) { throw new IllegalArgumentException( "frameLength must be a positive integer: " + frameLength); } ...
while (in.readableBytes() >= frameLength) { ByteBuf buf = in.readBytes(frameLength); out.add(buf); }
132
43
175
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/chapter9/src/main/java/nia/chapter9/FrameChunkDecoder.java
FrameChunkDecoder
decode
class FrameChunkDecoder extends ByteToMessageDecoder { private final int maxFrameSize; public FrameChunkDecoder(int maxFrameSize) { this.maxFrameSize = maxFrameSize; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception ...
int readableBytes = in.readableBytes(); if (readableBytes > maxFrameSize) { // discard the bytes in.clear(); throw new TooLongFrameException(); } ByteBuf buf = in.readBytes(readableBytes); out.add(buf);
102
77
179
<no_super_class>
normanmaurer_netty-in-action
netty-in-action/utils/src/main/java/nia/util/BogusTrustManagerFactory.java
BogusTrustManagerFactory
checkClientTrusted
class BogusTrustManagerFactory extends TrustManagerFactorySpi { private static final TrustManager DUMMY_TRUST_MANAGER = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void c...
// Always trust - it is an example. // You should do something in the real world. // You will reach here only if you enabled client certificate auth, // as described in SecureChatSslContextFactory. System.err.println("UNKNOWN CLIENT CERTIFICATE: " + chain[0]....
335
86
421
<methods>public void <init>() <variables>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/config/NeeBeeMallWebMvcConfigurer.java
NeeBeeMallWebMvcConfigurer
addInterceptors
class NeeBeeMallWebMvcConfigurer implements WebMvcConfigurer { @Autowired private AdminLoginInterceptor adminLoginInterceptor; @Autowired private NewBeeMallLoginInterceptor newBeeMallLoginInterceptor; @Autowired private NewBeeMallCartNumberInterceptor newBeeMallCartNumberInterceptor; publi...
// 添加一个拦截器,拦截以/admin为前缀的url路径(后台登陆拦截) registry.addInterceptor(adminLoginInterceptor) .addPathPatterns("/admin/**") .excludePathPatterns("/admin/login") .excludePathPatterns("/admin/dist/**") .excludePathPatterns("/admin/plugins/**"); ...
215
378
593
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/AdminController.java
AdminController
login
class AdminController { @Resource private AdminUserService adminUserService; @GetMapping({"/login"}) public String login() { return "admin/login"; } @GetMapping({"/test"}) public String test() { return "admin/test"; } @GetMapping({"", "/", "/index", "/index.html"...
if (!StringUtils.hasText(verifyCode)) { session.setAttribute("errorMsg", "验证码不能为空"); return "admin/login"; } if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) { session.setAttribute("errorMsg", "用户名或密码不能为空"); return "admin/logi...
832
333
1,165
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/NewBeeMallCarouselController.java
NewBeeMallCarouselController
delete
class NewBeeMallCarouselController { @Resource NewBeeMallCarouselService newBeeMallCarouselService; @GetMapping("/carousels") public String carouselPage(HttpServletRequest request) { request.setAttribute("path", "newbee_mall_carousel"); return "admin/newbee_mall_carousel"; } /...
if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } if (newBeeMallCarouselService.deleteBatch(ids)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("删除失败"); }
819
82
901
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/NewBeeMallGoodsCategoryController.java
NewBeeMallGoodsCategoryController
categoriesPage
class NewBeeMallGoodsCategoryController { @Resource private NewBeeMallCategoryService newBeeMallCategoryService; @GetMapping("/categories") public String categoriesPage(HttpServletRequest request, @RequestParam("categoryLevel") Byte categoryLevel, @RequestParam("parentId") Long parentId, @RequestParam...
if (categoryLevel == null || categoryLevel < 1 || categoryLevel > 3) { NewBeeMallException.fail("参数异常"); } request.setAttribute("path", "newbee_mall_category"); request.setAttribute("parentId", parentId); request.setAttribute("backParentId", backParentId); re...
1,606
113
1,719
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/NewBeeMallGoodsIndexConfigController.java
NewBeeMallGoodsIndexConfigController
update
class NewBeeMallGoodsIndexConfigController { @Resource private NewBeeMallIndexConfigService newBeeMallIndexConfigService; @GetMapping("/indexConfigs") public String indexConfigsPage(HttpServletRequest request, @RequestParam("configType") int configType) { IndexConfigTypeEnum indexConfigTypeEnu...
if (Objects.isNull(indexConfig.getConfigType()) || Objects.isNull(indexConfig.getConfigId()) || !StringUtils.hasText(indexConfig.getConfigName()) || Objects.isNull(indexConfig.getConfigRank())) { return ResultGenerator.genFailResult("参数异常!"); ...
850
158
1,008
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/NewBeeMallOrderController.java
NewBeeMallOrderController
checkDone
class NewBeeMallOrderController { @Resource private NewBeeMallOrderService newBeeMallOrderService; @GetMapping("/orders") public String ordersPage(HttpServletRequest request) { request.setAttribute("path", "orders"); return "admin/newbee_mall_order"; } /** * 列表 */ ...
if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } String result = newBeeMallOrderService.checkDone(ids); if (ServiceResultEnum.SUCCESS.getResult().equals(result)) { return ResultGenerator.genSuccessResult(); } else { retur...
991
99
1,090
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/admin/NewBeeMallUserController.java
NewBeeMallUserController
delete
class NewBeeMallUserController { @Resource private NewBeeMallUserService newBeeMallUserService; @GetMapping("/users") public String usersPage(HttpServletRequest request) { request.setAttribute("path", "users"); return "admin/newbee_mall_user"; } /** * 列表 */ @Requ...
if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } if (lockStatus != 0 && lockStatus != 1) { return ResultGenerator.genFailResult("操作非法!"); } if (newBeeMallUserService.lockUsers(ids, lockStatus)) { return ResultGenerator.ge...
328
118
446
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/common/CommonController.java
CommonController
mallKaptcha
class CommonController { @GetMapping("/common/kaptcha") public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); ...
httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/png"); ShearCaptcha shearCaptcha= CaptchaUtil.createShearCaptcha(110, 40, ...
266
175
441
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/common/ErrorPageController.java
ErrorPageController
resolveErrorView
class ErrorPageController implements ErrorViewResolver { private static ErrorPageController errorPageController; @Autowired private ErrorAttributes errorAttributes; public ErrorPageController(ErrorAttributes errorAttributes) { this.errorAttributes = errorAttributes; } public ErrorPag...
if (HttpStatus.BAD_REQUEST == status) { return new ModelAndView("error/error_400"); } else if (HttpStatus.NOT_FOUND == status) { return new ModelAndView("error/error_404"); } else { return new ModelAndView("error/error_5xx"); }
151
90
241
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/common/NewBeeMallExceptionHandler.java
NewBeeMallExceptionHandler
handleException
class NewBeeMallExceptionHandler { @ExceptionHandler(Exception.class) public Object handleException(Exception e, HttpServletRequest req) {<FILL_FUNCTION_BODY>} }
Result result = new Result(); result.setResultCode(500); //区分是否为自定义异常 if (e instanceof NewBeeMallException) { result.setMessage(e.getMessage()); } else { e.printStackTrace(); result.setMessage("未知异常"); } //检查请求是否为ajax, 如果是 ajax...
51
360
411
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/common/UploadController.java
UploadController
uploadV2
class UploadController { @Autowired private StandardServletMultipartResolver standardServletMultipartResolver; @PostMapping({"/upload/file"}) @ResponseBody public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException, IOException {...
List<MultipartFile> multipartFiles = new ArrayList<>(8); if (standardServletMultipartResolver.isMultipart(httpServletRequest)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) httpServletRequest; Iterator<String> iter = multiRequest.getFileNames(); ...
522
680
1,202
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/mall/GoodsController.java
GoodsController
detailPage
class GoodsController { @Resource private NewBeeMallGoodsService newBeeMallGoodsService; @Resource private NewBeeMallCategoryService newBeeMallCategoryService; @GetMapping({"/search", "/search.html"}) public String searchPage(@RequestParam Map<String, Object> params, HttpServletRequest request...
if (goodsId < 1) { NewBeeMallException.fail("参数异常"); } NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(goodsId); if (Constants.SELL_STATUS_UP != goods.getGoodsSellStatus()) { NewBeeMallException.fail(ServiceResultEnum.GOODS_PUT_DOWN.getResul...
591
211
802
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/mall/IndexController.java
IndexController
indexPage
class IndexController { @Resource private NewBeeMallCarouselService newBeeMallCarouselService; @Resource private NewBeeMallIndexConfigService newBeeMallIndexConfigService; @Resource private NewBeeMallCategoryService newBeeMallCategoryService; @GetMapping({"/index", "/", "/index.html"}) ...
List<NewBeeMallIndexCategoryVO> categories = newBeeMallCategoryService.getCategoriesForIndex(); if (CollectionUtils.isEmpty(categories)) { NewBeeMallException.fail("分类数据不完善"); } List<NewBeeMallIndexCarouselVO> carousels = newBeeMallCarouselService.getCarouselsForIndex(Consta...
123
414
537
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/mall/OrderController.java
OrderController
payOrder
class OrderController { @Resource private NewBeeMallShoppingCartService newBeeMallShoppingCartService; @Resource private NewBeeMallOrderService newBeeMallOrderService; @GetMapping("/orders/{orderNo}") public String orderDetailPage(HttpServletRequest request, @PathVariable("orderNo") String ord...
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY); NewBeeMallOrder newBeeMallOrder = newBeeMallOrderService.getNewBeeMallOrderByOrderNo(orderNo); //判断订单userId if (!user.getUserId().equals(newBeeMallOrder.getUserId())) { NewB...
1,522
286
1,808
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/mall/PersonalController.java
PersonalController
register
class PersonalController { @Resource private NewBeeMallUserService newBeeMallUserService; @GetMapping("/personal") public String personalPage(HttpServletRequest request, HttpSession httpSession) { request.setAttribute("path", "personal"); return "mall/per...
if (!StringUtils.hasText(loginName)) { return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult()); } if (!StringUtils.hasText(password)) { return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult()); } ...
873
337
1,210
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/controller/mall/ShoppingCartController.java
ShoppingCartController
updateNewBeeMallShoppingCartItem
class ShoppingCartController { @Resource private NewBeeMallShoppingCartService newBeeMallShoppingCartService; @GetMapping("/shop-cart") public String cartListPage(HttpServletRequest request, HttpSession httpSession) { NewBeeMallUserVO user = (NewBeeMallUserVO) ht...
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY); newBeeMallShoppingCartItem.setUserId(user.getUserId()); String updateResult = newBeeMallShoppingCartService.updateNewBeeMallCartItem(newBeeMallShoppingCartItem); //修改成功 if (Serv...
1,240
156
1,396
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/entity/IndexConfig.java
IndexConfig
toString
class IndexConfig { private Long configId; private String configName; private Byte configType; private Long goodsId; private String redirectUrl; private Integer configRank; private Byte isDeleted; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date cr...
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", configId=").append(configId); sb.append(", configName=").append(configName); sb.append(", configType=").append(co...
725
246
971
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/entity/NewBeeMallShoppingCartItem.java
NewBeeMallShoppingCartItem
toString
class NewBeeMallShoppingCartItem { private Long cartItemId; private Long userId; private Long goodsId; private Integer goodsCount; private Byte isDeleted; private Date createTime; private Date updateTime; public Long getCartItemId() { return cartItemId; } public v...
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", cartItemId=").append(cartItemId); sb.append(", userId=").append(userId); sb.append(", goodsId=").append(goodsId);...
436
182
618
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/interceptor/AdminLoginInterceptor.java
AdminLoginInterceptor
preHandle
class AdminLoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {<FILL_FUNCTION_BODY>} @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpSer...
String requestServletPath = request.getServletPath(); if (requestServletPath.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) { request.getSession().setAttribute("errorMsg", "请登陆"); response.sendRedirect(request.getContextPath() + "/admin/login"); ...
139
114
253
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/interceptor/NewBeeMallCartNumberInterceptor.java
NewBeeMallCartNumberInterceptor
preHandle
class NewBeeMallCartNumberInterceptor implements HandlerInterceptor { @Autowired private NewBeeMallShoppingCartItemMapper newBeeMallShoppingCartItemMapper; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {<FILL_FUNCTION_BODY>} ...
//购物车中的数量会更改,但是在这些接口中并没有对session中的数据做修改,这里统一处理一下 if (null != request.getSession() && null != request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY)) { //如果当前为登陆状态,就查询数据库并设置购物车中的数量值 NewBeeMallUserVO newBeeMallUserVO = (NewBeeMallUserVO) request.getSession().getAttribu...
174
226
400
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/interceptor/NewBeeMallLoginInterceptor.java
NewBeeMallLoginInterceptor
preHandle
class NewBeeMallLoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {<FILL_FUNCTION_BODY>} @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse ht...
if (null == request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY)) { response.sendRedirect(request.getContextPath() + "/login"); return false; } else { return true; }
142
65
207
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/service/impl/AdminUserServiceImpl.java
AdminUserServiceImpl
updateName
class AdminUserServiceImpl implements AdminUserService { @Resource private AdminUserMapper adminUserMapper; @Override public AdminUser login(String userName, String password) { String passwordMd5 = MD5Util.MD5Encode(password, "UTF-8"); return adminUserMapper.login(userName, passwordMd5...
AdminUser adminUser = adminUserMapper.selectByPrimaryKey(loginUserId); //当前用户非空才可以进行更改 if (adminUser != null) { //设置新名称并修改 adminUser.setLoginUserName(loginUserName); adminUser.setNickName(nickName); if (adminUserMapper.updateByPrimaryKeySelective(...
406
133
539
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/service/impl/NewBeeMallCarouselServiceImpl.java
NewBeeMallCarouselServiceImpl
saveCarousel
class NewBeeMallCarouselServiceImpl implements NewBeeMallCarouselService { @Autowired private CarouselMapper carouselMapper; @Override public PageResult getCarouselPage(PageQueryUtil pageUtil) { List<Carousel> carousels = carouselMapper.findCarouselList(pageUtil); int total = carouselM...
if (carouselMapper.insertSelective(carousel) > 0) { return ServiceResultEnum.SUCCESS.getResult(); } return ServiceResultEnum.DB_ERROR.getResult();
615
53
668
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/service/impl/NewBeeMallGoodsServiceImpl.java
NewBeeMallGoodsServiceImpl
searchNewBeeMallGoods
class NewBeeMallGoodsServiceImpl implements NewBeeMallGoodsService { @Autowired private NewBeeMallGoodsMapper goodsMapper; @Autowired private GoodsCategoryMapper goodsCategoryMapper; @Override public PageResult getNewBeeMallGoodsPage(PageQueryUtil pageUtil) { List<NewBeeMallGoods> good...
List<NewBeeMallGoods> goodsList = goodsMapper.findNewBeeMallGoodsListBySearch(pageUtil); int total = goodsMapper.getTotalNewBeeMallGoodsBySearch(pageUtil); List<NewBeeMallSearchGoodsVO> newBeeMallSearchGoodsVOS = new ArrayList<>(); if (!CollectionUtils.isEmpty(goodsList)) { ...
1,236
404
1,640
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/service/impl/NewBeeMallIndexConfigServiceImpl.java
NewBeeMallIndexConfigServiceImpl
getConfigGoodsesForIndex
class NewBeeMallIndexConfigServiceImpl implements NewBeeMallIndexConfigService { @Autowired private IndexConfigMapper indexConfigMapper; @Autowired private NewBeeMallGoodsMapper goodsMapper; @Override public PageResult getConfigsPage(PageQueryUtil pageUtil) { List<IndexConfig> indexCo...
List<NewBeeMallIndexConfigGoodsVO> newBeeMallIndexConfigGoodsVOS = new ArrayList<>(number); List<IndexConfig> indexConfigs = indexConfigMapper.findIndexConfigsByTypeAndNum(configType, number); if (!CollectionUtils.isEmpty(indexConfigs)) { //取出所有的goodsId List<Long> goodsI...
761
441
1,202
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/service/impl/NewBeeMallUserServiceImpl.java
NewBeeMallUserServiceImpl
register
class NewBeeMallUserServiceImpl implements NewBeeMallUserService { @Autowired private MallUserMapper mallUserMapper; @Override public PageResult getNewBeeMallUsersPage(PageQueryUtil pageUtil) { List<MallUser> mallUsers = mallUserMapper.findMallUserList(pageUtil); int total = mallUserMa...
if (mallUserMapper.selectByLoginName(loginName) != null) { return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult(); } MallUser registerUser = new MallUser(); registerUser.setLoginName(loginName); registerUser.setNickName(loginName); String passwordMD5 = MD...
925
174
1,099
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/BeanUtil.java
BeanUtil
copyList
class BeanUtil { public static Object copyProperties(Object source, Object target, String... ignoreProperties) { if (source == null) { return target; } BeanUtils.copyProperties(source, target, ignoreProperties); return target; } public static <T> List<T> copyLis...
List<T> targetList = new ArrayList<>(); if (sources != null) { try { for (Object source : sources) { T target = clazz.newInstance(); copyProperties(source, target); if (callback != null) { ca...
638
147
785
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/MD5Util.java
MD5Util
byteArrayToHexString
class MD5Util { private static String byteArrayToHexString(byte b[]) {<FILL_FUNCTION_BODY>} private static String byteToHexString(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } pub...
StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) resultSb.append(byteToHexString(b[i])); return resultSb.toString();
338
62
400
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/NewBeeMallUtils.java
NewBeeMallUtils
cleanString
class NewBeeMallUtils { public static URI getHost(URI uri) { URI effectiveURI = null; try { effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); } catch (Throwable var4) { effectiveURI = null; } r...
if (!StringUtils.hasText(value)) { return ""; } value = value.toLowerCase(); value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); value = value.replaceAll("'", "& #39;"); ...
127
522
649
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/NumberUtil.java
NumberUtil
isPhone
class NumberUtil { private NumberUtil() { } /** * 判断是否为11位电话号码 * * @param phone * @return */ public static boolean isPhone(String phone) {<FILL_FUNCTION_BODY>} /** * 生成指定长度的随机数 * * @param length * @return */ public static int genRandomNum(int...
Pattern pattern = Pattern.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0-8])|(18[0-9]))\\d{8}$"); Matcher matcher = pattern.matcher(phone); return matcher.matches();
295
90
385
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/PageQueryUtil.java
PageQueryUtil
toString
class PageQueryUtil extends LinkedHashMap<String, Object> { //当前页码 private int page; //每页条数 private int limit; public PageQueryUtil(Map<String, Object> params) { this.putAll(params); //分页参数 this.page = Integer.parseInt(params.get("page").toString()); this.limit = In...
return "PageUtil{" + "page=" + page + ", limit=" + limit + '}';
259
34
293
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(int, float) ,public void <init>(int, float, boolean) ,public void clear() ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lan...
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/PatternUtil.java
PatternUtil
isURL
class PatternUtil { /** * 匹配邮箱正则 */ private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); /** * 验证只包含中英文和数字的字符串 * * @param keyword * @return */ public static Boolea...
String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$"; Pattern pattern = Pattern.compile(regex); if (pattern.matcher(urlString).matches()) { return true; ...
358
186
544
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/Result.java
Result
toString
class Result<T> implements Serializable { private static final long serialVersionUID = 1L; private int resultCode; private String message; private T data; public Result() { } public Result(int resultCode, String message) { this.resultCode = resultCode; this.message = messag...
return "Result{" + "resultCode=" + resultCode + ", message='" + message + '\'' + ", data=" + data + '}';
240
47
287
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/ResultGenerator.java
ResultGenerator
genSuccessResult
class ResultGenerator { private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; private static final String DEFAULT_FAIL_MESSAGE = "FAIL"; private static final int RESULT_CODE_SUCCESS = 200; private static final int RESULT_CODE_SERVER_ERROR = 500; public static Result genSuccessResult() { ...
Result result = new Result(); result.setResultCode(RESULT_CODE_SUCCESS); result.setMessage(DEFAULT_SUCCESS_MESSAGE); result.setData(data); return result;
370
58
428
<no_super_class>
newbee-ltd_newbee-mall
newbee-mall/src/main/java/ltd/newbee/mall/util/SystemUtil.java
SystemUtil
genToken
class SystemUtil { private SystemUtil() { } /** * 登录或注册成功后,生成保持用户登录状态会话token值 * * @param src:为用户最新一次登录时的now()+user.id+random(4) * @return */ public static String genToken(String src) {<FILL_FUNCTION_BODY>} }
if (null == src || "".equals(src)) { return null; } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(src.getBytes()); String result = new BigInteger(1, md.digest()).toString(16); if (result.length() == 31) { ...
106
134
240
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/NovelApplication.java
NovelApplication
commandLineRunner
class NovelApplication { public static void main(String[] args) { SpringApplication.run(NovelApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext context) {<FILL_FUNCTION_BODY>} @Bean public SecurityFilterChain securityFilterChain(HttpSecurit...
return args -> { Map<String, CacheManager> beans = context.getBeansOfType(CacheManager.class); log.info("加载了如下缓存管理器:"); beans.forEach((k, v) -> { log.info("{}:{}", k, v.getClass().getName()); log.info("缓存:{}", v.getCacheNames()); }...
162
108
270
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/aspect/LockAspect.java
LockAspect
doAround
class LockAspect { private final RedissonClient redissonClient; private static final String KEY_PREFIX = "Lock"; private static final String KEY_SEPARATOR = "::"; @Around(value = "@annotation(io.github.xxyopen.novel.core.annotation.Lock)") @SneakyThrows public Object doAround(ProceedingJ...
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method targetMethod = methodSignature.getMethod(); Lock lock = targetMethod.getAnnotation(Lock.class); String lockKey = KEY_PREFIX + buildLockKey(lock.prefix(), targetMethod, joinPoint.getArgs()); ...
381
173
554
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/auth/AuthorAuthStrategy.java
AuthorAuthStrategy
auth
class AuthorAuthStrategy implements AuthStrategy { private final JwtUtils jwtUtils; private final UserInfoCacheManager userInfoCacheManager; private final AuthorInfoCacheManager authorInfoCacheManager; /** * 不需要进行作家权限认证的 URI */ private static final List<String> EXCLUDE_URI = List.of( ...
// 统一账号认证 Long userId = authSSO(jwtUtils, userInfoCacheManager, token); if (EXCLUDE_URI.contains(requestUri)) { // 该请求不需要进行作家权限认证 return; } // 作家权限认证 AuthorInfoDto authorInfo = authorInfoCacheManager.getAuthor(userId); if (Objects.isNull(a...
176
178
354
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/common/resp/PageRespDto.java
PageRespDto
getPages
class PageRespDto<T> { /** * 页码 */ private final long pageNum; /** * 每页大小 */ private final long pageSize; /** * 总记录数 */ private final long total; /** * 分页数据集 */ private final List<? extends T> list; /** * 该构造函数用于通用分页查询的场景 接收普通分页数据和普通集...
if (this.pageSize == 0L) { return 0L; } else { long pages = this.total / this.pageSize; if (this.total % this.pageSize != 0L) { ++pages; } return pages; }
302
76
378
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/common/util/ImgVerifyCodeUtils.java
ImgVerifyCodeUtils
drawLine
class ImgVerifyCodeUtils { /** * 随机产生只有数字的字符串 */ private final String randNumber = "0123456789"; /** * 图片宽 */ private final int width = 100; /** * 图片高 */ private final int height = 38; private final Random random = new Random(); /** * 获得字体 */ ...
int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl);
796
76
872
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/common/util/IpUtils.java
IpUtils
getRealIp
class IpUtils { private static final String UNKNOWN_IP = "unknown"; private static final String IP_SEPARATOR = ","; /** * 获取真实IP * * @return 真实IP */ public String getRealIp(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
// 这个一般是Nginx反向代理设置的参数 String ip = request.getHeader("X-Real-IP"); if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) { ...
93
293
386
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/CacheConfig.java
CacheConfig
caffeineCacheManager
class CacheConfig { /** * Caffeine 缓存管理器 */ @Bean @Primary public CacheManager caffeineCacheManager() {<FILL_FUNCTION_BODY>} /** * Redis 缓存管理器 */ @Bean public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory) { RedisCacheWriter redisCacheW...
SimpleCacheManager cacheManager = new SimpleCacheManager(); List<CaffeineCache> caches = new ArrayList<>(CacheConsts.CacheEnum.values().length); // 类型推断 var 非常适合 for 循环,JDK 10 引入,JDK 11 改进 for (var c : CacheConsts.CacheEnum.values()) { if (c.isLocal()) { Caf...
484
228
712
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/CorsConfig.java
CorsConfig
corsFilter
class CorsConfig { private final CorsProperties corsProperties; @Bean public CorsFilter corsFilter() {<FILL_FUNCTION_BODY>} }
CorsConfiguration config = new CorsConfiguration(); // 允许的域,不要写*,否则cookie就无法使用了 for (String allowOrigin : corsProperties.allowOrigins()) { config.addAllowedOrigin(allowOrigin); } // 允许的头信息 config.addAllowedHeader("*"); // 允许的请求方式 config.addAll...
49
188
237
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/EsConfig.java
EsConfig
elasticsearchRestClient
class EsConfig { /** * 解决 ElasticsearchClientConfigurations 修改默认 ObjectMapper 配置的问题 */ @Bean JacksonJsonpMapper jacksonJsonpMapper() { return new JacksonJsonpMapper(); } /** * fix `sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.ce...
restClientBuilder.setHttpClientConfigCallback((HttpAsyncClientBuilder clientBuilder) -> { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { ...
199
318
517
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/MybatisPlusConfig.java
MybatisPlusConfig
mybatisPlusInterceptor
class MybatisPlusConfig { /** * 分页插件 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>} }
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor;
61
59
120
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/WebConfig.java
WebConfig
addInterceptors
class WebConfig implements WebMvcConfigurer { private final FlowLimitInterceptor flowLimitInterceptor; private final AuthInterceptor authInterceptor; private final FileInterceptor fileInterceptor; private final TokenParseInterceptor tokenParseInterceptor; @Override public void addIntercepto...
// 流量限制拦截器 registry.addInterceptor(flowLimitInterceptor) .addPathPatterns("/**") .order(0); // 文件访问拦截 registry.addInterceptor(fileInterceptor) .addPathPatterns(SystemConfigConsts.IMAGE_UPLOAD_DIRECTORY + "**") .order(1); // 权限认证...
108
449
557
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/config/XxlJobConfig.java
XxlJobConfig
xxlJobExecutor
class XxlJobConfig { @Value("${xxl.job.admin.addresses}") private String adminAddresses; @Value("${xxl.job.accessToken}") private String accessToken; @Value("${xxl.job.executor.appname}") private String appname; @Value("${xxl.job.executor.logpath}") private String logPath; @Bean...
log.info(">>>>>>>>>>> xxl-job config init."); XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); xxlJobSpringExecutor.setAdminAddresses(adminAddresses); xxlJobSpringExecutor.setAccessToken(accessToken); xxlJobSpringExecutor.setAppname(appname); xxlJo...
149
122
271
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/filter/XssFilter.java
XssFilter
handleExcludeUrl
class XssFilter implements Filter { private final XssProperties xssProperties; @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletRespon...
if (CollectionUtils.isEmpty(xssProperties.excludes())) { return false; } String url = request.getServletPath(); for (String pattern : xssProperties.excludes()) { Pattern p = Pattern.compile("^" + pattern); Matcher m = p.matcher(url); if (m...
248
108
356
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/interceptor/AuthInterceptor.java
AuthInterceptor
preHandle
class AuthInterceptor implements HandlerInterceptor { private final Map<String, AuthStrategy> authStrategy; private final ObjectMapper objectMapper; /** * handle 执行前调用 */ @SuppressWarnings("NullableProblems") @Override public boolean preHandle(HttpServletRequest request, HttpServlet...
// 获取登录 JWT String token = request.getHeader(SystemConfigConsts.HTTP_AUTH_HEADER_NAME); // 获取请求的 URI String requestUri = request.getRequestURI(); // 根据请求的 URI 得到认证策略 String subUri = requestUri.substring(ApiRouterConsts.API_URL_PREFIX.length() + 1); String syste...
327
283
610
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/interceptor/FileInterceptor.java
FileInterceptor
preHandle
class FileInterceptor implements HandlerInterceptor { @Value("${novel.file.upload.path}") private String fileUploadPath; @SuppressWarnings("NullableProblems") @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FIL...
// 获取请求的 URI String requestUri = request.getRequestURI(); // 缓存10天 response.setDateHeader("expires", System.currentTimeMillis() + 60 * 60 * 24 * 10 * 1000); try (OutputStream out = response.getOutputStream(); InputStream input = new FileInputStream( fileUploadPath + ...
97
163
260
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/interceptor/FlowLimitInterceptor.java
FlowLimitInterceptor
preHandle
class FlowLimitInterceptor implements HandlerInterceptor { private final ObjectMapper objectMapper; /** * novel 项目所有的资源 */ private static final String NOVEL_RESOURCE = "novelResource"; static { // 接口限流规则:所有的请求,限制每秒最多只能通过 2000 个,超出限制匀速排队 List<FlowRule> rules = new ArrayList<>...
String ip = IpUtils.getRealIp(request); Entry entry = null; try { // 若需要配置例外项,则传入的参数只支持基本类型。 // EntryType 代表流量类型,其中系统规则只对 IN 类型的埋点生效 // count 大多数情况都填 1,代表统计为一次调用。 entry = SphU.entry(NOVEL_RESOURCE, EntryType.IN, 1, ip); // Your logic h...
478
318
796
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/interceptor/TokenParseInterceptor.java
TokenParseInterceptor
preHandle
class TokenParseInterceptor implements HandlerInterceptor { private final JwtUtils jwtUtils; @SuppressWarnings("NullableProblems") @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} /** ...
// 获取登录 JWT String token = request.getHeader(SystemConfigConsts.HTTP_AUTH_HEADER_NAME); if (StringUtils.hasText(token)) { // 解析 token 并保存 UserHolder.setUserId(jwtUtils.parseToken(token, SystemConfigConsts.NOVEL_FRONT_KEY)); } return HandlerInterceptor.sup...
204
116
320
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/listener/RabbitQueueListener.java
RabbitQueueListener
updateEsBook
class RabbitQueueListener { private final BookInfoMapper bookInfoMapper; private final ElasticsearchClient esClient; /** * 监听小说信息改变的 ES 更新队列,更新最新小说信息到 ES */ @RabbitListener(queues = AmqpConsts.BookChangeMq.QUEUE_ES_UPDATE) @SneakyThrows public void updateEsBook(Long bookId) {<FILL_F...
BookInfo bookInfo = bookInfoMapper.selectById(bookId); IndexResponse response = esClient.index(i -> i .index(EsConsts.BookIndex.INDEX_NAME) .id(bookInfo.getId().toString()) .document(EsBookDto.build(bookInfo)) ); log.info("Indexed with version " + res...
125
97
222
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/task/BookToEsTask.java
BookToEsTask
saveToEs
class BookToEsTask { private final BookInfoMapper bookInfoMapper; private final ElasticsearchClient elasticsearchClient; /** * 每月凌晨做一次全量数据同步 */ @SneakyThrows @XxlJob("saveToEsJobHandler") public ReturnT<String> saveToEs() {<FILL_FUNCTION_BODY>} }
try { QueryWrapper<BookInfo> queryWrapper = new QueryWrapper<>(); List<BookInfo> bookInfos; long maxId = 0; for (; ; ) { queryWrapper.clear(); queryWrapper .orderByAsc(DatabaseConsts.CommonColumnEnum.ID.getName...
104
449
553
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/util/JwtUtils.java
JwtUtils
parseToken
class JwtUtils { /** * 注入JWT加密密钥 */ @Value("${novel.jwt.secret}") private String secret; /** * 定义系统标识头常量 */ private static final String HEADER_SYSTEM_KEY = "systemKeyHeader"; /** * 根据用户ID生成JWT * * @param uid 用户ID * @param systemKey 系统标识 * @re...
Jws<Claims> claimsJws; try { claimsJws = Jwts.parserBuilder() .setSigningKey(Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8))) .build() .parseClaimsJws(token); // OK, we can trust this JWT // 判断该 JWT 是否属于指定系统...
311
205
516
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/core/wrapper/XssHttpServletRequestWrapper.java
XssHttpServletRequestWrapper
getParameterValues
class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { private static final Map<String, String> REPLACE_RULE = new HashMap<>(); static { REPLACE_RULE.put("<", "&lt;"); REPLACE_RULE.put(">", "&gt;"); } public XssHttpServletRequestWrapper(HttpServletRequest request) { ...
String[] values = super.getParameterValues(name); if (values != null) { int length = values.length; String[] escapeValues = new String[length]; for (int i = 0; i < length; i++) { escapeValues[i] = values[i]; int index = i; ...
140
142
282
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/AuthorCode.java
AuthorCode
toString
class AuthorCode implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 邀请码 */ private String inviteCode; /** * 有效时间 */ private LocalDateTime validityTime; ...
return "AuthorCode{" + "id=" + id + ", inviteCode=" + inviteCode + ", validityTime=" + validityTime + ", isUsed=" + isUsed + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
484
80
564
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/AuthorIncome.java
AuthorIncome
toString
class AuthorIncome implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 作家ID */ private Long authorId; /** * 小说ID */ private Long bookId; /** * ...
return "AuthorIncome{" + "id=" + id + ", authorId=" + authorId + ", bookId=" + bookId + ", incomeMonth=" + incomeMonth + ", preTaxIncome=" + preTaxIncome + ", afterTaxIncome=" + afterTaxIncome + ", payStatus=" + payStatus + ", confirmStatus=" + co...
860
142
1,002
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/AuthorIncomeDetail.java
AuthorIncomeDetail
toString
class AuthorIncomeDetail implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 作家ID */ private Long authorId; /** * 小说ID;0表示全部作品 */ private Long bookId; ...
return "AuthorIncomeDetail{" + "id=" + id + ", authorId=" + authorId + ", bookId=" + bookId + ", incomeDate=" + incomeDate + ", incomeAccount=" + incomeAccount + ", incomeCount=" + incomeCount + ", incomeNumber=" + incomeNumber + ", createTime=" +...
691
115
806
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/AuthorInfo.java
AuthorInfo
toString
class AuthorInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户ID */ private Long userId; /** * 邀请码 */ private String inviteCode; /** *...
return "AuthorInfo{" + "id=" + id + ", userId=" + userId + ", inviteCode=" + inviteCode + ", penName=" + penName + ", telPhone=" + telPhone + ", chatAccount=" + chatAccount + ", email=" + email + ", workDirection=" + workDirection + ", sta...
810
131
941
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookCategory.java
BookCategory
toString
class BookCategory implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 作品方向;0-男频 1-女频 */ private Integer workDirection; /** * 类别名 */ private String name; /** * 排序 *...
return "BookCategory{" + "id=" + id + ", workDirection=" + workDirection + ", name=" + name + ", sort=" + sort + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
449
76
525
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookChapter.java
BookChapter
toString
class BookChapter implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 小说ID */ private Long bookId; /** * 章节号 */ private Integer chapterNum; /** * 章节名 */ private...
return "BookChapter{" + "id=" + id + ", bookId=" + bookId + ", chapterNum=" + chapterNum + ", chapterName=" + chapterName + ", wordCount=" + wordCount + ", isVip=" + isVip + ", createTime=" + createTime + ", updateTime=" + updateTime + "}"...
581
104
685
<no_super_class>