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 channelRead0(ChannelHandlerContext ctx,
TextWebSocketFrame msg) throws Exception {
// Handle text frame
}
}
public static final class BinaryFrameHandler extends
SimpleChannelInboundHandler<BinaryWebSocketFrame> {
@Override
public void channelRead0(ChannelHandlerContext ctx,
BinaryWebSocketFrame msg) throws Exception {
// Handle binary frame
}
}
public static final class ContinuationFrameHandler extends
SimpleChannelInboundHandler<ContinuationWebSocketFrame> {
@Override
public void channelRead0(ChannelHandlerContext ctx,
ContinuationWebSocketFrame msg) throws Exception {
// Handle continuation frame
}
}
}
|
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 = new ServerBootstrap();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(createInitializer(channelGroup));
ChannelFuture future = bootstrap.bind(address);
future.syncUninterruptibly();
channel = future.channel();
return future;
}
protected ChannelInitializer<Channel> createInitializer(
ChannelGroup group) {
return new ChatServerInitializer(group);
}
public void destroy() {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Please give port as argument");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
final ChatServer endpoint = new ChatServer();
ChannelFuture future = endpoint.start(
new InetSocketAddress(port));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
endpoint.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly();
}
}
|
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 WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandler(group));
| 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 {
String path = location.toURI() + "index.html";
path = !path.contains("file:") ? path : path.substring(5);
INDEX = new File(path);
} catch (URISyntaxException e) {
throw new IllegalStateException(
"Unable to locate index.html", e);
}
}
public HttpRequestHandler(String wsUri) {
this.wsUri = wsUri;
}
@Override
public void channelRead0(ChannelHandlerContext ctx,
FullHttpRequest request) throws Exception {<FILL_FUNCTION_BODY>}
private static void send100Continue(ChannelHandlerContext ctx) {
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
ctx.writeAndFlush(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
|
if (wsUri.equalsIgnoreCase(request.getUri())) {
ctx.fireChannelRead(request.retain());
} else {
if (HttpHeaders.is100ContinueExpected(request)) {
send100Continue(ctx);
}
RandomAccessFile file = new RandomAccessFile(INDEX, "r");
HttpResponse response = new DefaultHttpResponse(
request.getProtocolVersion(), HttpResponseStatus.OK);
response.headers().set(
HttpHeaders.Names.CONTENT_TYPE,
"text/html; charset=UTF-8");
boolean keepAlive = HttpHeaders.isKeepAlive(request);
if (keepAlive) {
response.headers().set(
HttpHeaders.Names.CONTENT_LENGTH, file.length());
response.headers().set( HttpHeaders.Names.CONNECTION,
HttpHeaders.Values.KEEP_ALIVE);
}
ctx.write(response);
if (ctx.pipeline().get(SslHandler.class) == null) {
ctx.write(new DefaultFileRegion(
file.getChannel(), 0, file.length()));
} else {
ctx.write(new ChunkedNioFile(file.getChannel()));
}
ChannelFuture future = ctx.writeAndFlush(
LastHttpContent.EMPTY_LAST_CONTENT);
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
| 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 SecureChatServerInitializer(group, context);
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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(
cert.certificate(), cert.privateKey());
final SecureChatServer endpoint = new SecureChatServer(context);
ChannelFuture future = endpoint.start(new InetSocketAddress(port));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
endpoint.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly();
| 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 evt) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void channelRead0(ChannelHandlerContext ctx,
TextWebSocketFrame msg) throws Exception {
group.writeAndFlush(msg.retain());
}
}
|
if (evt == WebSocketServerProtocolHandler
.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.pipeline().remove(HttpRequestHandler.class);
group.writeAndFlush(new TextWebSocketFrame(
"Client " + ctx.channel() + " joined"));
group.add(ctx.channel());
} else {
super.userEventTriggered(ctx, evt);
}
| 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).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new LogEventEncoder(address));
this.file = file;
}
public void run() throws Exception {<FILL_FUNCTION_BODY>}
public void stop() {
group.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException();
}
LogEventBroadcaster broadcaster = new LogEventBroadcaster(
new InetSocketAddress("255.255.255.255",
Integer.parseInt(args[0])), new File(args[1]));
try {
broadcaster.run();
}
finally {
broadcaster.stop();
}
}
}
|
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
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(pointer);
String line;
while ((line = raf.readLine()) != null) {
ch.writeAndFlush(new LogEvent(null, -1,
file.getAbsolutePath(), line));
}
pointer = raf.getFilePointer();
raf.close();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
break;
}
}
| 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(CharsetUtil.UTF_8);
LogEvent event = new LogEvent(datagramPacket.sender(),
System.currentTimeMillis(), filename, logMsg);
out.add(event);
| 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,
LogEvent logEvent, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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);
buf.writeBytes(msg);
out.add(new DatagramPacket(buf, remoteAddress));
| 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 ctx,
LogEvent event) throws Exception {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
builder.append(event.getReceivedTimestamp());
builder.append(" [");
builder.append(event.getSource().toString());
builder.append("] [");
builder.append(event.getLogfile());
builder.append("] : ");
builder.append(event.getMsg());
System.out.println(builder.toString());
| 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)
.option(ChannelOption.SO_BROADCAST, true)
.handler( new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel)
throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new LogEventDecoder());
pipeline.addLast(new LogEventHandler());
}
} )
.localAddress(address);
}
public Channel bind() {
return bootstrap.bind().syncUninterruptibly().channel();
}
public void stop() {
group.shutdownGracefully();
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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();
System.out.println("LogEventMonitor running");
channel.closeFuture().sync();
} finally {
monitor.stop();
}
| 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 Exception {
if (args.length != 2) {
System.err.println("Usage: " + EchoClient.class.getSimpleName() +
" <host> <port>"
);
return;
}
final String host = args[0];
final int port = Integer.parseInt(args[1]);
new EchoClient(host, port).start();
}
}
|
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(
new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
| 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>"
);
return;
}
int port = Integer.parseInt(args[0]);
new EchoServer(port).start();
}
public void start() throws Exception {<FILL_FUNCTION_BODY>}
}
|
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = b.bind().sync();
System.out.println(EchoServer.class.getName() +
" started and listening for connections on " + f.channel().localAddress());
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
| 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_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
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 static void writingToChannelFromManyThreads() {
final Channel channel = CHANNEL_FROM_SOMEWHERE; // Get the channel reference from somewhere
final ByteBuf buf = Unpooled.copiedBuffer("your data",
CharsetUtil.UTF_8);
Runnable writer = new Runnable() {
@Override
public void run() {
channel.write(buf.duplicate());
}
};
Executor executor = Executors.newCachedThreadPool();
// write in one thread
executor.execute(writer);
// write in another thread
executor.execute(writer);
//...
}
}
|
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 void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
System.out.println("Write successful");
} else {
System.err.println("Write error");
future.cause().printStackTrace();
}
}
});
| 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(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(
new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(
ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(buf.duplicate())
.addListener(
ChannelFutureListener.CLOSE);
}
});
}
}
);
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
| 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(OioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(
new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(
ChannelHandlerContext ctx)
throws Exception {
ctx.writeAndFlush(buf.duplicate())
.addListener(
ChannelFutureListener.CLOSE);
}
});
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
| 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();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
for (;;){
try {
selector.select();
} catch (IOException ex) {
ex.printStackTrace();
//handle exception
break;
}
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) {
ServerSocketChannel server =
(ServerSocketChannel) key.channel();
SocketChannel client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_WRITE |
SelectionKey.OP_READ, msg.duplicate());
System.out.println(
"Accepted connection from " + client);
}
if (key.isWritable()) {
SocketChannel client =
(SocketChannel) key.channel();
ByteBuffer buffer =
(ByteBuffer) key.attachment();
while (buffer.hasRemaining()) {
if (client.write(buffer) == 0) {
break;
}
}
client.close();
}
} catch (IOException ex) {
key.cancel();
try {
key.channel().close();
} catch (IOException cex) {
// ignore on close
}
}
}
}
| 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() {
@Override
public void run() {
OutputStream out;
try {
out = clientSocket.getOutputStream();
out.write("Hi!\r\n".getBytes(
Charset.forName("UTF-8")));
out.flush();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException ex) {
// ignore on close
}
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
| 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 addingChannelFutureListener(){<FILL_FUNCTION_BODY>}
}
|
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() {
@Override
public void operationComplete(io.netty.channel.ChannelFuture f) {
if (!f.isSuccess()) {
f.cause().printStackTrace();
f.channel().close();
}
}
});
| 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 ChannelHandlerAdapter {
}
private static final class SecondHandler
extends ChannelHandlerAdapter {
}
private static final class ThirdHandler
extends ChannelHandlerAdapter {
}
private static final class FourthHandler
extends ChannelHandlerAdapter {
}
}
|
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());
//...
pipeline.remove("handler3");
pipeline.remove(firstHandler);
pipeline.replace("handler2", "handler4", new FourthHandler());
| 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
* */
public static void writeViaChannel() {
ChannelHandlerContext ctx = CHANNEL_HANDLER_CONTEXT_FROM_SOMEWHERE; //get reference form somewhere
Channel channel = ctx.channel();
channel.write(Unpooled.copiedBuffer("Netty in Action",
CharsetUtil.UTF_8));
}
/**
* Listing 6.7 Accessing the ChannelPipeline from a ChannelHandlerContext
* */
public static void writeViaChannelPipeline() {<FILL_FUNCTION_BODY>}
/**
* Listing 6.8 Calling ChannelHandlerContext write()
* */
public static void writeViaChannelHandlerContext() {
ChannelHandlerContext ctx = CHANNEL_HANDLER_CONTEXT_FROM_SOMEWHERE; //get reference form somewhere;
ctx.write(Unpooled.copiedBuffer("Netty in Action", CharsetUtil.UTF_8));
}
}
|
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: readyEvents) {
ev.run();
}
}
}
private static final List<Runnable> blockUntilEventsReady() {<FILL_FUNCTION_BODY>}
}
|
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.newScheduledThreadPool(10);
ScheduledFuture<?> future = executor.schedule(
new Runnable() {
@Override
public void run() {
System.out.println("Now it is 60 seconds later");
}
}, 60, TimeUnit.SECONDS);
//...
executor.shutdown();
}
/**
* Listing 7.3 Scheduling a task with EventLoop
* */
public static void scheduleViaEventLoop() {<FILL_FUNCTION_BODY>}
/**
* Listing 7.4 Scheduling a recurring task with EventLoop
* */
public static void scheduleFixedViaEventLoop() {
Channel ch = CHANNEL_FROM_SOMEWHERE; // get reference from somewhere
ScheduledFuture<?> future = ch.eventLoop().scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
System.out.println("Run every 60 seconds");
}
}, 60, 60, TimeUnit.SECONDS);
}
/**
* Listing 7.5 Canceling a task using ScheduledFuture
* */
public static void cancelingTaskUsingScheduledFuture(){
Channel ch = CHANNEL_FROM_SOMEWHERE; // get reference from somewhere
ScheduledFuture<?> future = ch.eventLoop().scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
System.out.println("Run every 60 seconds");
}
}, 60, 60, TimeUnit.SECONDS);
// Some other code that runs...
boolean mayInterruptIfRunning = false;
future.cancel(mayInterruptIfRunning);
}
}
|
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.SECONDS);
| 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();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Received data");
}
});
ChannelFuture future =
bootstrap.connect(
new InetSocketAddress("www.manning.com", 80));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {<FILL_FUNCTION_BODY>}
});
}
}
|
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>() {
@Override
public void channelRegistered(ChannelHandlerContext ctx)
throws Exception {
Integer idValue = ctx.channel().attr(id).get();
// do something with the idValue
}
@Override
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Received data");
}
}
);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
bootstrap.attr(id, 123456);
ChannelFuture future = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80));
future.syncUninterruptibly();
| 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,
DatagramPacket msg) throws Exception {
// Do something with the packet
}
}
);
ChannelFuture future = bootstrap.bind(new InetSocketAddress(0));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Channel bound");
} else {
System.err.println("Bind attempt failed");
channelFuture.cause().printStackTrace();
}
}
});
| 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
protected void channelRead0(ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Received data");
}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Server bound");
} else {
System.err.println("Bind attempt failed");
channelFuture.cause().printStackTrace();
}
}
});
| 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)
.childHandler(
new SimpleChannelInboundHandler<ByteBuf>() {
ChannelFuture connectFuture;
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class).handler(
new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(
ChannelHandlerContext ctx, ByteBuf in)
throws Exception {
System.out.println("Received data");
}
});
bootstrap.group(ctx.channel().eventLoop());
connectFuture = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80));
}
@Override
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {<FILL_FUNCTION_BODY>}
});
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture)
throws Exception {
if (channelFuture.isSuccess()) {
System.out.println("Server bound");
} else {
System.err.println("Bind attempt failed");
channelFuture.cause().printStackTrace();
}
}
});
}
}
|
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 initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
}
}
}
|
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializerImpl());
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.sync();
| 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
protected void channelRead0(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Received data");
}
}
);
bootstrap.connect(new InetSocketAddress("www.manning.com", 80)).syncUninterruptibly();
//,,,
Future<?> future = group.shutdownGracefully();
// block until the group has shutdown
future.syncUninterruptibly();
| 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(
ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
System.out.println("Received data");
}
});
ChannelFuture future = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80));
future.syncUninterruptibly();
| 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);
}
this.frameLength = frameLength;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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 {<FILL_FUNCTION_BODY>}
}
|
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 checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {<FILL_FUNCTION_BODY>}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Always trust - it is an example.
// You should do something in the real world.
System.err.println("UNKNOWN SERVER CERTIFICATE: " + chain[0].getSubjectDN());
}
};
@Override
protected TrustManager[] engineGetTrustManagers() {
return new TrustManager[]{DUMMY_TRUST_MANAGER};
}
@Override
protected void engineInit(KeyStore keystore)
throws KeyStoreException {
// Unused
}
@Override
protected void engineInit(ManagerFactoryParameters managerFactoryParameters)
throws InvalidAlgorithmParameterException {
// Unused
}
}
|
// 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].getSubjectDN());
| 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;
public void addInterceptors(InterceptorRegistry registry) {<FILL_FUNCTION_BODY>}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:" + Constants.FILE_UPLOAD_DIC);
registry.addResourceHandler("/goods-img/**").addResourceLocations("file:" + Constants.FILE_UPLOAD_DIC);
}
}
|
// 添加一个拦截器,拦截以/admin为前缀的url路径(后台登陆拦截)
registry.addInterceptor(adminLoginInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/login")
.excludePathPatterns("/admin/dist/**")
.excludePathPatterns("/admin/plugins/**");
// 购物车中的数量统一处理
registry.addInterceptor(newBeeMallCartNumberInterceptor)
.excludePathPatterns("/admin/**")
.excludePathPatterns("/register")
.excludePathPatterns("/login")
.excludePathPatterns("/logout");
// 商城页面登陆拦截
registry.addInterceptor(newBeeMallLoginInterceptor)
.excludePathPatterns("/admin/**")
.excludePathPatterns("/register")
.excludePathPatterns("/login")
.excludePathPatterns("/logout")
.addPathPatterns("/goods/detail/**")
.addPathPatterns("/shop-cart")
.addPathPatterns("/shop-cart/**")
.addPathPatterns("/saveOrder")
.addPathPatterns("/orders")
.addPathPatterns("/orders/**")
.addPathPatterns("/personal")
.addPathPatterns("/personal/updateInfo")
.addPathPatterns("/selectPayType")
.addPathPatterns("/payPage");
| 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"})
public String index(HttpServletRequest request) {
request.setAttribute("path", "index");
return "admin/index";
}
@PostMapping(value = "/login")
public String login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("verifyCode") String verifyCode,
HttpSession session) {<FILL_FUNCTION_BODY>}
@GetMapping("/profile")
public String profile(HttpServletRequest request) {
Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
AdminUser adminUser = adminUserService.getUserDetailById(loginUserId);
if (adminUser == null) {
return "admin/login";
}
request.setAttribute("path", "profile");
request.setAttribute("loginUserName", adminUser.getLoginUserName());
request.setAttribute("nickName", adminUser.getNickName());
return "admin/profile";
}
@PostMapping("/profile/password")
@ResponseBody
public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword,
@RequestParam("newPassword") String newPassword) {
if (!StringUtils.hasText(originalPassword) || !StringUtils.hasText(newPassword)) {
return "参数不能为空";
}
Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
if (adminUserService.updatePassword(loginUserId, originalPassword, newPassword)) {
//修改成功后清空session中的数据,前端控制跳转至登录页
request.getSession().removeAttribute("loginUserId");
request.getSession().removeAttribute("loginUser");
request.getSession().removeAttribute("errorMsg");
return ServiceResultEnum.SUCCESS.getResult();
} else {
return "修改失败";
}
}
@PostMapping("/profile/name")
@ResponseBody
public String nameUpdate(HttpServletRequest request, @RequestParam("loginUserName") String loginUserName,
@RequestParam("nickName") String nickName) {
if (!StringUtils.hasText(loginUserName) || !StringUtils.hasText(nickName)) {
return "参数不能为空";
}
Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");
if (adminUserService.updateName(loginUserId, loginUserName, nickName)) {
return ServiceResultEnum.SUCCESS.getResult();
} else {
return "修改失败";
}
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
request.getSession().removeAttribute("loginUserId");
request.getSession().removeAttribute("loginUser");
request.getSession().removeAttribute("errorMsg");
return "admin/login";
}
}
|
if (!StringUtils.hasText(verifyCode)) {
session.setAttribute("errorMsg", "验证码不能为空");
return "admin/login";
}
if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) {
session.setAttribute("errorMsg", "用户名或密码不能为空");
return "admin/login";
}
ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode");
if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) {
session.setAttribute("errorMsg", "验证码错误");
return "admin/login";
}
AdminUser adminUser = adminUserService.login(userName, password);
if (adminUser != null) {
session.setAttribute("loginUser", adminUser.getNickName());
session.setAttribute("loginUserId", adminUser.getAdminUserId());
//session过期时间设置为7200秒 即两小时
//session.setMaxInactiveInterval(60 * 60 * 2);
return "redirect:/admin/index";
} else {
session.setAttribute("errorMsg", "登录失败");
return "admin/login";
}
| 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";
}
/**
* 列表
*/
@RequestMapping(value = "/carousels/list", method = RequestMethod.GET)
@ResponseBody
public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallCarouselService.getCarouselPage(pageUtil));
}
/**
* 添加
*/
@RequestMapping(value = "/carousels/save", method = RequestMethod.POST)
@ResponseBody
public Result save(@RequestBody Carousel carousel) {
if (!StringUtils.hasText(carousel.getCarouselUrl())
|| Objects.isNull(carousel.getCarouselRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallCarouselService.saveCarousel(carousel);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/carousels/update", method = RequestMethod.POST)
@ResponseBody
public Result update(@RequestBody Carousel carousel) {
if (Objects.isNull(carousel.getCarouselId())
|| !StringUtils.hasText(carousel.getCarouselUrl())
|| Objects.isNull(carousel.getCarouselRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallCarouselService.updateCarousel(carousel);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@GetMapping("/carousels/info/{id}")
@ResponseBody
public Result info(@PathVariable("id") Integer id) {
Carousel carousel = newBeeMallCarouselService.getCarouselById(id);
if (carousel == null) {
return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
return ResultGenerator.genSuccessResult(carousel);
}
/**
* 删除
*/
@RequestMapping(value = "/carousels/delete", method = RequestMethod.POST)
@ResponseBody
public Result delete(@RequestBody Integer[] ids) {<FILL_FUNCTION_BODY>}
}
|
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("backParentId") Long backParentId) {<FILL_FUNCTION_BODY>}
/**
* 列表
*/
@RequestMapping(value = "/categories/list", method = RequestMethod.GET)
@ResponseBody
public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit")) || ObjectUtils.isEmpty(params.get("categoryLevel")) || ObjectUtils.isEmpty(params.get("parentId"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallCategoryService.getCategorisPage(pageUtil));
}
/**
* 列表
*/
@RequestMapping(value = "/categories/listForSelect", method = RequestMethod.GET)
@ResponseBody
public Result listForSelect(@RequestParam("categoryId") Long categoryId) {
if (categoryId == null || categoryId < 1) {
return ResultGenerator.genFailResult("缺少参数!");
}
GoodsCategory category = newBeeMallCategoryService.getGoodsCategoryById(categoryId);
//既不是一级分类也不是二级分类则为不返回数据
if (category == null || category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ResultGenerator.genFailResult("参数异常!");
}
Map categoryResult = new HashMap(4);
if (category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_ONE.getLevel()) {
//如果是一级分类则返回当前一级分类下的所有二级分类,以及二级分类列表中第一条数据下的所有三级分类列表
//查询一级分类列表中第一个实体的所有二级分类
List<GoodsCategory> secondLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(categoryId), NewBeeMallCategoryLevelEnum.LEVEL_TWO.getLevel());
if (!CollectionUtils.isEmpty(secondLevelCategories)) {
//查询二级分类列表中第一个实体的所有三级分类
List<GoodsCategory> thirdLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(secondLevelCategories.get(0).getCategoryId()), NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel());
categoryResult.put("secondLevelCategories", secondLevelCategories);
categoryResult.put("thirdLevelCategories", thirdLevelCategories);
}
}
if (category.getCategoryLevel() == NewBeeMallCategoryLevelEnum.LEVEL_TWO.getLevel()) {
//如果是二级分类则返回当前分类下的所有三级分类列表
List<GoodsCategory> thirdLevelCategories = newBeeMallCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(categoryId), NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel());
categoryResult.put("thirdLevelCategories", thirdLevelCategories);
}
return ResultGenerator.genSuccessResult(categoryResult);
}
/**
* 添加
*/
@RequestMapping(value = "/categories/save", method = RequestMethod.POST)
@ResponseBody
public Result save(@RequestBody GoodsCategory goodsCategory) {
if (Objects.isNull(goodsCategory.getCategoryLevel())
|| !StringUtils.hasText(goodsCategory.getCategoryName())
|| Objects.isNull(goodsCategory.getParentId())
|| Objects.isNull(goodsCategory.getCategoryRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallCategoryService.saveCategory(goodsCategory);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/categories/update", method = RequestMethod.POST)
@ResponseBody
public Result update(@RequestBody GoodsCategory goodsCategory) {
if (Objects.isNull(goodsCategory.getCategoryId())
|| Objects.isNull(goodsCategory.getCategoryLevel())
|| !StringUtils.hasText(goodsCategory.getCategoryName())
|| Objects.isNull(goodsCategory.getParentId())
|| Objects.isNull(goodsCategory.getCategoryRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallCategoryService.updateGoodsCategory(goodsCategory);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@GetMapping("/categories/info/{id}")
@ResponseBody
public Result info(@PathVariable("id") Long id) {
GoodsCategory goodsCategory = newBeeMallCategoryService.getGoodsCategoryById(id);
if (goodsCategory == null) {
return ResultGenerator.genFailResult("未查询到数据");
}
return ResultGenerator.genSuccessResult(goodsCategory);
}
/**
* 分类删除
*/
@RequestMapping(value = "/categories/delete", method = RequestMethod.POST)
@ResponseBody
public Result delete(@RequestBody Integer[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newBeeMallCategoryService.deleteBatch(ids)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
|
if (categoryLevel == null || categoryLevel < 1 || categoryLevel > 3) {
NewBeeMallException.fail("参数异常");
}
request.setAttribute("path", "newbee_mall_category");
request.setAttribute("parentId", parentId);
request.setAttribute("backParentId", backParentId);
request.setAttribute("categoryLevel", categoryLevel);
return "admin/newbee_mall_category";
| 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 indexConfigTypeEnum = IndexConfigTypeEnum.getIndexConfigTypeEnumByType(configType);
if (indexConfigTypeEnum.equals(IndexConfigTypeEnum.DEFAULT)) {
NewBeeMallException.fail("参数异常");
}
request.setAttribute("path", indexConfigTypeEnum.getName());
request.setAttribute("configType", configType);
return "admin/newbee_mall_index_config";
}
/**
* 列表
*/
@RequestMapping(value = "/indexConfigs/list", method = RequestMethod.GET)
@ResponseBody
public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallIndexConfigService.getConfigsPage(pageUtil));
}
/**
* 添加
*/
@RequestMapping(value = "/indexConfigs/save", method = RequestMethod.POST)
@ResponseBody
public Result save(@RequestBody IndexConfig indexConfig) {
if (Objects.isNull(indexConfig.getConfigType())
|| !StringUtils.hasText(indexConfig.getConfigName())
|| Objects.isNull(indexConfig.getConfigRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallIndexConfigService.saveIndexConfig(indexConfig);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 修改
*/
@RequestMapping(value = "/indexConfigs/update", method = RequestMethod.POST)
@ResponseBody
public Result update(@RequestBody IndexConfig indexConfig) {<FILL_FUNCTION_BODY>}
/**
* 详情
*/
@GetMapping("/indexConfigs/info/{id}")
@ResponseBody
public Result info(@PathVariable("id") Long id) {
IndexConfig config = newBeeMallIndexConfigService.getIndexConfigById(id);
if (config == null) {
return ResultGenerator.genFailResult("未查询到数据");
}
return ResultGenerator.genSuccessResult(config);
}
/**
* 删除
*/
@RequestMapping(value = "/indexConfigs/delete", method = RequestMethod.POST)
@ResponseBody
public Result delete(@RequestBody Long[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (newBeeMallIndexConfigService.deleteBatch(ids)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
}
|
if (Objects.isNull(indexConfig.getConfigType())
|| Objects.isNull(indexConfig.getConfigId())
|| !StringUtils.hasText(indexConfig.getConfigName())
|| Objects.isNull(indexConfig.getConfigRank())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallIndexConfigService.updateIndexConfig(indexConfig);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
| 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";
}
/**
* 列表
*/
@RequestMapping(value = "/orders/list", method = RequestMethod.GET)
@ResponseBody
public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallOrderService.getNewBeeMallOrdersPage(pageUtil));
}
/**
* 修改
*/
@RequestMapping(value = "/orders/update", method = RequestMethod.POST)
@ResponseBody
public Result update(@RequestBody NewBeeMallOrder newBeeMallOrder) {
if (Objects.isNull(newBeeMallOrder.getTotalPrice())
|| Objects.isNull(newBeeMallOrder.getOrderId())
|| newBeeMallOrder.getOrderId() < 1
|| newBeeMallOrder.getTotalPrice() < 1
|| !StringUtils.hasText(newBeeMallOrder.getUserAddress())) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.updateOrderInfo(newBeeMallOrder);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 详情
*/
@GetMapping("/order-items/{id}")
@ResponseBody
public Result info(@PathVariable("id") Long id) {
List<NewBeeMallOrderItemVO> orderItems = newBeeMallOrderService.getOrderItems(id);
if (!CollectionUtils.isEmpty(orderItems)) {
return ResultGenerator.genSuccessResult(orderItems);
}
return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
}
/**
* 配货
*/
@RequestMapping(value = "/orders/checkDone", method = RequestMethod.POST)
@ResponseBody
public Result checkDone(@RequestBody Long[] ids) {<FILL_FUNCTION_BODY>}
/**
* 出库
*/
@RequestMapping(value = "/orders/checkOut", method = RequestMethod.POST)
@ResponseBody
public Result checkOut(@RequestBody Long[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.checkOut(ids);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
/**
* 关闭订单
*/
@RequestMapping(value = "/orders/close", method = RequestMethod.POST)
@ResponseBody
public Result closeOrder(@RequestBody Long[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.closeOrder(ids);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
}
}
|
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
String result = newBeeMallOrderService.checkDone(ids);
if (ServiceResultEnum.SUCCESS.getResult().equals(result)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(result);
}
| 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";
}
/**
* 列表
*/
@RequestMapping(value = "/users/list", method = RequestMethod.GET)
@ResponseBody
public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(newBeeMallUserService.getNewBeeMallUsersPage(pageUtil));
}
/**
* 用户禁用与解除禁用(0-未锁定 1-已锁定)
*/
@RequestMapping(value = "/users/lock/{lockStatus}", method = RequestMethod.POST)
@ResponseBody
public Result delete(@RequestBody Integer[] ids, @PathVariable int lockStatus) {<FILL_FUNCTION_BODY>}
}
|
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (lockStatus != 0 && lockStatus != 1) {
return ResultGenerator.genFailResult("操作非法!");
}
if (newBeeMallUserService.lockUsers(ids, lockStatus)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("禁用失败");
}
| 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.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/png");
ShearCaptcha shearCaptcha= CaptchaUtil.createShearCaptcha(150, 30, 4, 2);
// 验证码存入session
httpServletRequest.getSession().setAttribute("verifyCode", shearCaptcha);
// 输出图片流
shearCaptcha.write(httpServletResponse.getOutputStream());
}
@GetMapping("/common/mall/kaptcha")
public void mallKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {<FILL_FUNCTION_BODY>}
}
|
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, 4, 2);
// 验证码存入session
httpServletRequest.getSession().setAttribute(Constants.MALL_VERIFY_CODE_KEY, shearCaptcha);
// 输出图片流
shearCaptcha.write(httpServletResponse.getOutputStream());
| 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 ErrorPageController() {
if (errorPageController == null) {
errorPageController = new ErrorPageController(errorAttributes);
}
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {<FILL_FUNCTION_BODY>}
}
|
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 请求则返回 Result json串, 如果不是 ajax 请求则返回 error 视图
String contentTypeHeader = req.getHeader("Content-Type");
String acceptHeader = req.getHeader("Accept");
String xRequestedWith = req.getHeader("X-Requested-With");
if ((contentTypeHeader != null && contentTypeHeader.contains("application/json"))
|| (acceptHeader != null && acceptHeader.contains("application/json"))
|| "XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
return result;
} else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", e.getMessage());
modelAndView.addObject("url", req.getRequestURL());
modelAndView.addObject("stackTrace", e.getStackTrace());
modelAndView.addObject("author", "十三");
modelAndView.addObject("ltd", "新蜂商城");
modelAndView.setViewName("error/error");
return modelAndView;
}
| 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 {
String fileName = file.getOriginalFilename();
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null) {
return ResultGenerator.genFailResult("请上传图片类型的文件");
}
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
//创建文件
File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
try {
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdir()) {
throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
}
}
file.transferTo(destFile);
Result resultSuccess = ResultGenerator.genSuccessResult();
resultSuccess.setData(NewBeeMallUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
return resultSuccess;
} catch (IOException e) {
e.printStackTrace();
return ResultGenerator.genFailResult("文件上传失败");
}
}
@PostMapping({"/upload/files"})
@ResponseBody
public Result uploadV2(HttpServletRequest httpServletRequest) throws URISyntaxException, IOException {<FILL_FUNCTION_BODY>}
}
|
List<MultipartFile> multipartFiles = new ArrayList<>(8);
if (standardServletMultipartResolver.isMultipart(httpServletRequest)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) httpServletRequest;
Iterator<String> iter = multiRequest.getFileNames();
int total = 0;
while (iter.hasNext()) {
if (total > 5) {
return ResultGenerator.genFailResult("最多上传5张图片");
}
total += 1;
MultipartFile file = multiRequest.getFile(iter.next());
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
// 只处理图片类型的文件
if (bufferedImage != null) {
multipartFiles.add(file);
}
}
}
if (CollectionUtils.isEmpty(multipartFiles)) {
return ResultGenerator.genFailResult("请选择图片类型的文件上传");
}
if (multipartFiles != null && multipartFiles.size() > 5) {
return ResultGenerator.genFailResult("最多上传5张图片");
}
List<String> fileNames = new ArrayList(multipartFiles.size());
for (int i = 0; i < multipartFiles.size(); i++) {
String fileName = multipartFiles.get(i).getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成文件名称通用方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString();
File fileDirectory = new File(Constants.FILE_UPLOAD_DIC);
//创建文件
File destFile = new File(Constants.FILE_UPLOAD_DIC + newFileName);
try {
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdir()) {
throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
}
}
multipartFiles.get(i).transferTo(destFile);
fileNames.add(NewBeeMallUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
} catch (IOException e) {
e.printStackTrace();
return ResultGenerator.genFailResult("文件上传失败");
}
}
Result resultSuccess = ResultGenerator.genSuccessResult();
resultSuccess.setData(fileNames);
return resultSuccess;
| 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 (ObjectUtils.isEmpty(params.get("page"))) {
params.put("page", 1);
}
params.put("limit", Constants.GOODS_SEARCH_PAGE_LIMIT);
//封装分类数据
if (params.containsKey("goodsCategoryId") && StringUtils.hasText(params.get("goodsCategoryId") + "")) {
Long categoryId = Long.valueOf(params.get("goodsCategoryId") + "");
SearchPageCategoryVO searchPageCategoryVO = newBeeMallCategoryService.getCategoriesForSearch(categoryId);
if (searchPageCategoryVO != null) {
request.setAttribute("goodsCategoryId", categoryId);
request.setAttribute("searchPageCategoryVO", searchPageCategoryVO);
}
}
//封装参数供前端回显
if (params.containsKey("orderBy") && StringUtils.hasText(params.get("orderBy") + "")) {
request.setAttribute("orderBy", params.get("orderBy") + "");
}
String keyword = "";
//对keyword做过滤 去掉空格
if (params.containsKey("keyword") && StringUtils.hasText((params.get("keyword") + "").trim())) {
keyword = params.get("keyword") + "";
}
request.setAttribute("keyword", keyword);
params.put("keyword", keyword);
//搜索上架状态下的商品
params.put("goodsSellStatus", Constants.SELL_STATUS_UP);
//封装商品数据
PageQueryUtil pageUtil = new PageQueryUtil(params);
request.setAttribute("pageResult", newBeeMallGoodsService.searchNewBeeMallGoods(pageUtil));
return "mall/search";
}
@GetMapping("/goods/detail/{goodsId}")
public String detailPage(@PathVariable("goodsId") Long goodsId, HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
if (goodsId < 1) {
NewBeeMallException.fail("参数异常");
}
NewBeeMallGoods goods = newBeeMallGoodsService.getNewBeeMallGoodsById(goodsId);
if (Constants.SELL_STATUS_UP != goods.getGoodsSellStatus()) {
NewBeeMallException.fail(ServiceResultEnum.GOODS_PUT_DOWN.getResult());
}
NewBeeMallGoodsDetailVO goodsDetailVO = new NewBeeMallGoodsDetailVO();
BeanUtil.copyProperties(goods, goodsDetailVO);
goodsDetailVO.setGoodsCarouselList(goods.getGoodsCarousel().split(","));
request.setAttribute("goodsDetail", goodsDetailVO);
return "mall/detail";
| 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"})
public String indexPage(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
List<NewBeeMallIndexCategoryVO> categories = newBeeMallCategoryService.getCategoriesForIndex();
if (CollectionUtils.isEmpty(categories)) {
NewBeeMallException.fail("分类数据不完善");
}
List<NewBeeMallIndexCarouselVO> carousels = newBeeMallCarouselService.getCarouselsForIndex(Constants.INDEX_CAROUSEL_NUMBER);
List<NewBeeMallIndexConfigGoodsVO> hotGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_HOT.getType(), Constants.INDEX_GOODS_HOT_NUMBER);
List<NewBeeMallIndexConfigGoodsVO> newGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_NEW.getType(), Constants.INDEX_GOODS_NEW_NUMBER);
List<NewBeeMallIndexConfigGoodsVO> recommendGoodses = newBeeMallIndexConfigService.getConfigGoodsesForIndex(IndexConfigTypeEnum.INDEX_GOODS_RECOMMOND.getType(), Constants.INDEX_GOODS_RECOMMOND_NUMBER);
request.setAttribute("categories", categories);//分类数据
request.setAttribute("carousels", carousels);//轮播图
request.setAttribute("hotGoodses", hotGoodses);//热销商品
request.setAttribute("newGoodses", newGoodses);//新品
request.setAttribute("recommendGoodses", recommendGoodses);//推荐商品
return "mall/index";
| 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 orderNo, HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
NewBeeMallOrderDetailVO orderDetailVO = newBeeMallOrderService.getOrderDetailByOrderNo(orderNo, user.getUserId());
request.setAttribute("orderDetailVO", orderDetailVO);
return "mall/order-detail";
}
@GetMapping("/orders")
public String orderListPage(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
params.put("userId", user.getUserId());
if (ObjectUtils.isEmpty(params.get("page"))) {
params.put("page", 1);
}
params.put("limit", Constants.ORDER_SEARCH_PAGE_LIMIT);
//封装我的订单数据
PageQueryUtil pageUtil = new PageQueryUtil(params);
request.setAttribute("orderPageResult", newBeeMallOrderService.getMyOrders(pageUtil));
request.setAttribute("path", "orders");
return "mall/my-orders";
}
@GetMapping("/saveOrder")
public String saveOrder(HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
List<NewBeeMallShoppingCartItemVO> myShoppingCartItems = newBeeMallShoppingCartService.getMyShoppingCartItems(user.getUserId());
if (!StringUtils.hasText(user.getAddress().trim())) {
//无收货地址
NewBeeMallException.fail(ServiceResultEnum.NULL_ADDRESS_ERROR.getResult());
}
if (CollectionUtils.isEmpty(myShoppingCartItems)) {
//购物车中无数据则跳转至错误页
NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
}
//保存订单并返回订单号
String saveOrderResult = newBeeMallOrderService.saveOrder(user, myShoppingCartItems);
//跳转到订单详情页
return "redirect:/orders/" + saveOrderResult;
}
@PutMapping("/orders/{orderNo}/cancel")
@ResponseBody
public Result cancelOrder(@PathVariable("orderNo") String orderNo, HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
String cancelOrderResult = newBeeMallOrderService.cancelOrder(orderNo, user.getUserId());
if (ServiceResultEnum.SUCCESS.getResult().equals(cancelOrderResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(cancelOrderResult);
}
}
@PutMapping("/orders/{orderNo}/finish")
@ResponseBody
public Result finishOrder(@PathVariable("orderNo") String orderNo, HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
String finishOrderResult = newBeeMallOrderService.finishOrder(orderNo, user.getUserId());
if (ServiceResultEnum.SUCCESS.getResult().equals(finishOrderResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(finishOrderResult);
}
}
@GetMapping("/selectPayType")
public String selectPayType(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderService.getNewBeeMallOrderByOrderNo(orderNo);
//判断订单userId
if (!user.getUserId().equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
}
//判断订单状态
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_STATUS_ERROR.getResult());
}
request.setAttribute("orderNo", orderNo);
request.setAttribute("totalPrice", newBeeMallOrder.getTotalPrice());
return "mall/pay-select";
}
@GetMapping("/payPage")
public String payOrder(HttpServletRequest request, @RequestParam("orderNo") String orderNo, HttpSession httpSession, @RequestParam("payType") int payType) {<FILL_FUNCTION_BODY>}
@GetMapping("/paySuccess")
@ResponseBody
public Result paySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("payType") int payType) {
String payResult = newBeeMallOrderService.paySuccess(orderNo, payType);
if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult(payResult);
}
}
}
|
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
NewBeeMallOrder newBeeMallOrder = newBeeMallOrderService.getNewBeeMallOrderByOrderNo(orderNo);
//判断订单userId
if (!user.getUserId().equals(newBeeMallOrder.getUserId())) {
NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
}
//判断订单状态
if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
NewBeeMallException.fail(ServiceResultEnum.ORDER_STATUS_ERROR.getResult());
}
request.setAttribute("orderNo", orderNo);
request.setAttribute("totalPrice", newBeeMallOrder.getTotalPrice());
if (payType == 1) {
return "mall/alipay";
} else {
return "mall/wxpay";
}
| 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/personal";
}
@GetMapping("/logout")
public String logout(HttpSession httpSession) {
httpSession.removeAttribute(Constants.MALL_USER_SESSION_KEY);
return "mall/login";
}
@GetMapping({"/login", "login.html"})
public String loginPage() {
return "mall/login";
}
@GetMapping({"/register", "register.html"})
public String registerPage() {
return "mall/register";
}
@GetMapping("/personal/addresses")
public String addressesPage() {
return "mall/addresses";
}
@PostMapping("/login")
@ResponseBody
public Result login(@RequestParam("loginName") String loginName,
@RequestParam("verifyCode") String verifyCode,
@RequestParam("password") String password,
HttpSession httpSession) {
if (!StringUtils.hasText(loginName)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
}
if (!StringUtils.hasText(password)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
}
if (!StringUtils.hasText(verifyCode)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
}
ShearCaptcha shearCaptcha = (ShearCaptcha) httpSession.getAttribute(Constants.MALL_VERIFY_CODE_KEY);
if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
}
String loginResult = newBeeMallUserService.login(loginName, MD5Util.MD5Encode(password, "UTF-8"), httpSession);
//登录成功
if (ServiceResultEnum.SUCCESS.getResult().equals(loginResult)) {
//删除session中的verifyCode
httpSession.removeAttribute(Constants.MALL_VERIFY_CODE_KEY);
return ResultGenerator.genSuccessResult();
}
//登录失败
return ResultGenerator.genFailResult(loginResult);
}
@PostMapping("/register")
@ResponseBody
public Result register(@RequestParam("loginName") String loginName,
@RequestParam("verifyCode") String verifyCode,
@RequestParam("password") String password,
HttpSession httpSession) {<FILL_FUNCTION_BODY>}
@PostMapping("/personal/updateInfo")
@ResponseBody
public Result updateInfo(@RequestBody MallUser mallUser, HttpSession httpSession) {
NewBeeMallUserVO mallUserTemp = newBeeMallUserService.updateUserInfo(mallUser, httpSession);
if (mallUserTemp == null) {
Result result = ResultGenerator.genFailResult("修改失败");
return result;
} else {
//返回成功
Result result = ResultGenerator.genSuccessResult();
return result;
}
}
}
|
if (!StringUtils.hasText(loginName)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
}
if (!StringUtils.hasText(password)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
}
if (!StringUtils.hasText(verifyCode)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
}
ShearCaptcha shearCaptcha = (ShearCaptcha) httpSession.getAttribute(Constants.MALL_VERIFY_CODE_KEY);
if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) {
return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
}
String registerResult = newBeeMallUserService.register(loginName, password);
//注册成功
if (ServiceResultEnum.SUCCESS.getResult().equals(registerResult)) {
//删除session中的verifyCode
httpSession.removeAttribute(Constants.MALL_VERIFY_CODE_KEY);
return ResultGenerator.genSuccessResult();
}
//注册失败
return ResultGenerator.genFailResult(registerResult);
| 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) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
int itemsTotal = 0;
int priceTotal = 0;
List<NewBeeMallShoppingCartItemVO> myShoppingCartItems = newBeeMallShoppingCartService.getMyShoppingCartItems(user.getUserId());
if (!CollectionUtils.isEmpty(myShoppingCartItems)) {
//购物项总数
itemsTotal = myShoppingCartItems.stream().mapToInt(NewBeeMallShoppingCartItemVO::getGoodsCount).sum();
if (itemsTotal < 1) {
NewBeeMallException.fail("购物项不能为空");
}
//总价
for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();
}
if (priceTotal < 1) {
NewBeeMallException.fail("购物项价格异常");
}
}
request.setAttribute("itemsTotal", itemsTotal);
request.setAttribute("priceTotal", priceTotal);
request.setAttribute("myShoppingCartItems", myShoppingCartItems);
return "mall/cart";
}
@PostMapping("/shop-cart")
@ResponseBody
public Result saveNewBeeMallShoppingCartItem(@RequestBody NewBeeMallShoppingCartItem newBeeMallShoppingCartItem,
HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
newBeeMallShoppingCartItem.setUserId(user.getUserId());
String saveResult = newBeeMallShoppingCartService.saveNewBeeMallCartItem(newBeeMallShoppingCartItem);
//添加成功
if (ServiceResultEnum.SUCCESS.getResult().equals(saveResult)) {
return ResultGenerator.genSuccessResult();
}
//添加失败
return ResultGenerator.genFailResult(saveResult);
}
@PutMapping("/shop-cart")
@ResponseBody
public Result updateNewBeeMallShoppingCartItem(@RequestBody NewBeeMallShoppingCartItem newBeeMallShoppingCartItem,
HttpSession httpSession) {<FILL_FUNCTION_BODY>}
@DeleteMapping("/shop-cart/{newBeeMallShoppingCartItemId}")
@ResponseBody
public Result updateNewBeeMallShoppingCartItem(@PathVariable("newBeeMallShoppingCartItemId") Long newBeeMallShoppingCartItemId,
HttpSession httpSession) {
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
Boolean deleteResult = newBeeMallShoppingCartService.deleteById(newBeeMallShoppingCartItemId,user.getUserId());
//删除成功
if (deleteResult) {
return ResultGenerator.genSuccessResult();
}
//删除失败
return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
}
@GetMapping("/shop-cart/settle")
public String settlePage(HttpServletRequest request,
HttpSession httpSession) {
int priceTotal = 0;
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
List<NewBeeMallShoppingCartItemVO> myShoppingCartItems = newBeeMallShoppingCartService.getMyShoppingCartItems(user.getUserId());
if (CollectionUtils.isEmpty(myShoppingCartItems)) {
//无数据则不跳转至结算页
return "/shop-cart";
} else {
//总价
for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();
}
if (priceTotal < 1) {
NewBeeMallException.fail("购物项价格异常");
}
}
request.setAttribute("priceTotal", priceTotal);
request.setAttribute("myShoppingCartItems", myShoppingCartItems);
return "mall/order-settle";
}
}
|
NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
newBeeMallShoppingCartItem.setUserId(user.getUserId());
String updateResult = newBeeMallShoppingCartService.updateNewBeeMallCartItem(newBeeMallShoppingCartItem);
//修改成功
if (ServiceResultEnum.SUCCESS.getResult().equals(updateResult)) {
return ResultGenerator.genSuccessResult();
}
//修改失败
return ResultGenerator.genFailResult(updateResult);
| 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 createTime;
private Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
private Integer updateUser;
public Long getConfigId() {
return configId;
}
public void setConfigId(Long configId) {
this.configId = configId;
}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName == null ? null : configName.trim();
}
public Byte getConfigType() {
return configType;
}
public void setConfigType(Byte configType) {
this.configType = configType;
}
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl == null ? null : redirectUrl.trim();
}
public Integer getConfigRank() {
return configRank;
}
public void setConfigRank(Integer configRank) {
this.configRank = configRank;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getCreateUser() {
return createUser;
}
public void setCreateUser(Integer createUser) {
this.createUser = createUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getUpdateUser() {
return updateUser;
}
public void setUpdateUser(Integer updateUser) {
this.updateUser = updateUser;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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(configType);
sb.append(", goodsId=").append(goodsId);
sb.append(", redirectUrl=").append(redirectUrl);
sb.append(", configRank=").append(configRank);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", createUser=").append(createUser);
sb.append(", updateTime=").append(updateTime);
sb.append(", updateUser=").append(updateUser);
sb.append("]");
return sb.toString();
| 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 void setCartItemId(Long cartItemId) {
this.cartItemId = cartItemId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public Integer getGoodsCount() {
return goodsCount;
}
public void setGoodsCount(Integer goodsCount) {
this.goodsCount = goodsCount;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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);
sb.append(", goodsCount=").append(goodsCount);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
| 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 httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
|
String requestServletPath = request.getServletPath();
if (requestServletPath.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) {
request.getSession().setAttribute("errorMsg", "请登陆");
response.sendRedirect(request.getContextPath() + "/admin/login");
return false;
} else {
request.getSession().removeAttribute("errorMsg");
return true;
}
| 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>}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
|
//购物车中的数量会更改,但是在这些接口中并没有对session中的数据做修改,这里统一处理一下
if (null != request.getSession() && null != request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY)) {
//如果当前为登陆状态,就查询数据库并设置购物车中的数量值
NewBeeMallUserVO newBeeMallUserVO = (NewBeeMallUserVO) request.getSession().getAttribute(Constants.MALL_USER_SESSION_KEY);
//设置购物车中的数量
newBeeMallUserVO.setShopCartItemCount(newBeeMallShoppingCartItemMapper.selectCountByUserId(newBeeMallUserVO.getUserId()));
request.getSession().setAttribute(Constants.MALL_USER_SESSION_KEY, newBeeMallUserVO);
}
return true;
| 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 httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
|
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);
}
@Override
public AdminUser getUserDetailById(Integer loginUserId) {
return adminUserMapper.selectByPrimaryKey(loginUserId);
}
@Override
public Boolean updatePassword(Integer loginUserId, String originalPassword, String newPassword) {
AdminUser adminUser = adminUserMapper.selectByPrimaryKey(loginUserId);
//当前用户非空才可以进行更改
if (adminUser != null) {
String originalPasswordMd5 = MD5Util.MD5Encode(originalPassword, "UTF-8");
String newPasswordMd5 = MD5Util.MD5Encode(newPassword, "UTF-8");
//比较原密码是否正确
if (originalPasswordMd5.equals(adminUser.getLoginPassword())) {
//设置新密码并修改
adminUser.setLoginPassword(newPasswordMd5);
if (adminUserMapper.updateByPrimaryKeySelective(adminUser) > 0) {
//修改成功则返回true
return true;
}
}
}
return false;
}
@Override
public Boolean updateName(Integer loginUserId, String loginUserName, String nickName) {<FILL_FUNCTION_BODY>}
}
|
AdminUser adminUser = adminUserMapper.selectByPrimaryKey(loginUserId);
//当前用户非空才可以进行更改
if (adminUser != null) {
//设置新名称并修改
adminUser.setLoginUserName(loginUserName);
adminUser.setNickName(nickName);
if (adminUserMapper.updateByPrimaryKeySelective(adminUser) > 0) {
//修改成功则返回true
return true;
}
}
return false;
| 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 = carouselMapper.getTotalCarousels(pageUtil);
PageResult pageResult = new PageResult(carousels, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveCarousel(Carousel carousel) {<FILL_FUNCTION_BODY>}
@Override
public String updateCarousel(Carousel carousel) {
Carousel temp = carouselMapper.selectByPrimaryKey(carousel.getCarouselId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
temp.setCarouselRank(carousel.getCarouselRank());
temp.setRedirectUrl(carousel.getRedirectUrl());
temp.setCarouselUrl(carousel.getCarouselUrl());
temp.setUpdateTime(new Date());
if (carouselMapper.updateByPrimaryKeySelective(temp) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public Carousel getCarouselById(Integer id) {
return carouselMapper.selectByPrimaryKey(id);
}
@Override
public Boolean deleteBatch(Integer[] ids) {
if (ids.length < 1) {
return false;
}
//删除数据
return carouselMapper.deleteBatch(ids) > 0;
}
@Override
public List<NewBeeMallIndexCarouselVO> getCarouselsForIndex(int number) {
List<NewBeeMallIndexCarouselVO> newBeeMallIndexCarouselVOS = new ArrayList<>(number);
List<Carousel> carousels = carouselMapper.findCarouselsByNum(number);
if (!CollectionUtils.isEmpty(carousels)) {
newBeeMallIndexCarouselVOS = BeanUtil.copyList(carousels, NewBeeMallIndexCarouselVO.class);
}
return newBeeMallIndexCarouselVOS;
}
}
|
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> goodsList = goodsMapper.findNewBeeMallGoodsList(pageUtil);
int total = goodsMapper.getTotalNewBeeMallGoods(pageUtil);
PageResult pageResult = new PageResult(goodsList, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveNewBeeMallGoods(NewBeeMallGoods goods) {
GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(goods.getGoodsCategoryId());
// 分类不存在或者不是三级分类,则该参数字段异常
if (goodsCategory == null || goodsCategory.getCategoryLevel().intValue() != NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ServiceResultEnum.GOODS_CATEGORY_ERROR.getResult();
}
if (goodsMapper.selectByCategoryIdAndName(goods.getGoodsName(), goods.getGoodsCategoryId()) != null) {
return ServiceResultEnum.SAME_GOODS_EXIST.getResult();
}
goods.setGoodsName(NewBeeMallUtils.cleanString(goods.getGoodsName()));
goods.setGoodsIntro(NewBeeMallUtils.cleanString(goods.getGoodsIntro()));
goods.setTag(NewBeeMallUtils.cleanString(goods.getTag()));
if (goodsMapper.insertSelective(goods) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public void batchSaveNewBeeMallGoods(List<NewBeeMallGoods> newBeeMallGoodsList) {
if (!CollectionUtils.isEmpty(newBeeMallGoodsList)) {
goodsMapper.batchInsert(newBeeMallGoodsList);
}
}
@Override
public String updateNewBeeMallGoods(NewBeeMallGoods goods) {
GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(goods.getGoodsCategoryId());
// 分类不存在或者不是三级分类,则该参数字段异常
if (goodsCategory == null || goodsCategory.getCategoryLevel().intValue() != NewBeeMallCategoryLevelEnum.LEVEL_THREE.getLevel()) {
return ServiceResultEnum.GOODS_CATEGORY_ERROR.getResult();
}
NewBeeMallGoods temp = goodsMapper.selectByPrimaryKey(goods.getGoodsId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
NewBeeMallGoods temp2 = goodsMapper.selectByCategoryIdAndName(goods.getGoodsName(), goods.getGoodsCategoryId());
if (temp2 != null && !temp2.getGoodsId().equals(goods.getGoodsId())) {
//name和分类id相同且不同id 不能继续修改
return ServiceResultEnum.SAME_GOODS_EXIST.getResult();
}
goods.setGoodsName(NewBeeMallUtils.cleanString(goods.getGoodsName()));
goods.setGoodsIntro(NewBeeMallUtils.cleanString(goods.getGoodsIntro()));
goods.setTag(NewBeeMallUtils.cleanString(goods.getTag()));
goods.setUpdateTime(new Date());
if (goodsMapper.updateByPrimaryKeySelective(goods) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public NewBeeMallGoods getNewBeeMallGoodsById(Long id) {
NewBeeMallGoods newBeeMallGoods = goodsMapper.selectByPrimaryKey(id);
if (newBeeMallGoods == null) {
NewBeeMallException.fail(ServiceResultEnum.GOODS_NOT_EXIST.getResult());
}
return newBeeMallGoods;
}
@Override
public Boolean batchUpdateSellStatus(Long[] ids, int sellStatus) {
return goodsMapper.batchUpdateSellStatus(ids, sellStatus) > 0;
}
@Override
public PageResult searchNewBeeMallGoods(PageQueryUtil pageUtil) {<FILL_FUNCTION_BODY>}
}
|
List<NewBeeMallGoods> goodsList = goodsMapper.findNewBeeMallGoodsListBySearch(pageUtil);
int total = goodsMapper.getTotalNewBeeMallGoodsBySearch(pageUtil);
List<NewBeeMallSearchGoodsVO> newBeeMallSearchGoodsVOS = new ArrayList<>();
if (!CollectionUtils.isEmpty(goodsList)) {
newBeeMallSearchGoodsVOS = BeanUtil.copyList(goodsList, NewBeeMallSearchGoodsVO.class);
for (NewBeeMallSearchGoodsVO newBeeMallSearchGoodsVO : newBeeMallSearchGoodsVOS) {
String goodsName = newBeeMallSearchGoodsVO.getGoodsName();
String goodsIntro = newBeeMallSearchGoodsVO.getGoodsIntro();
// 字符串过长导致文字超出的问题
if (goodsName.length() > 28) {
goodsName = goodsName.substring(0, 28) + "...";
newBeeMallSearchGoodsVO.setGoodsName(goodsName);
}
if (goodsIntro.length() > 30) {
goodsIntro = goodsIntro.substring(0, 30) + "...";
newBeeMallSearchGoodsVO.setGoodsIntro(goodsIntro);
}
}
}
PageResult pageResult = new PageResult(newBeeMallSearchGoodsVOS, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
| 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> indexConfigs = indexConfigMapper.findIndexConfigList(pageUtil);
int total = indexConfigMapper.getTotalIndexConfigs(pageUtil);
PageResult pageResult = new PageResult(indexConfigs, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String saveIndexConfig(IndexConfig indexConfig) {
if (goodsMapper.selectByPrimaryKey(indexConfig.getGoodsId()) == null) {
return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
}
if (indexConfigMapper.selectByTypeAndGoodsId(indexConfig.getConfigType(), indexConfig.getGoodsId()) != null) {
return ServiceResultEnum.SAME_INDEX_CONFIG_EXIST.getResult();
}
if (indexConfigMapper.insertSelective(indexConfig) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public String updateIndexConfig(IndexConfig indexConfig) {
if (goodsMapper.selectByPrimaryKey(indexConfig.getGoodsId()) == null) {
return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
}
IndexConfig temp = indexConfigMapper.selectByPrimaryKey(indexConfig.getConfigId());
if (temp == null) {
return ServiceResultEnum.DATA_NOT_EXIST.getResult();
}
IndexConfig temp2 = indexConfigMapper.selectByTypeAndGoodsId(indexConfig.getConfigType(), indexConfig.getGoodsId());
if (temp2 != null && !temp2.getConfigId().equals(indexConfig.getConfigId())) {
//goodsId相同且不同id 不能继续修改
return ServiceResultEnum.SAME_INDEX_CONFIG_EXIST.getResult();
}
indexConfig.setUpdateTime(new Date());
if (indexConfigMapper.updateByPrimaryKeySelective(indexConfig) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
}
@Override
public IndexConfig getIndexConfigById(Long id) {
return null;
}
@Override
public List<NewBeeMallIndexConfigGoodsVO> getConfigGoodsesForIndex(int configType, int number) {<FILL_FUNCTION_BODY>}
@Override
public Boolean deleteBatch(Long[] ids) {
if (ids.length < 1) {
return false;
}
//删除数据
return indexConfigMapper.deleteBatch(ids) > 0;
}
}
|
List<NewBeeMallIndexConfigGoodsVO> newBeeMallIndexConfigGoodsVOS = new ArrayList<>(number);
List<IndexConfig> indexConfigs = indexConfigMapper.findIndexConfigsByTypeAndNum(configType, number);
if (!CollectionUtils.isEmpty(indexConfigs)) {
//取出所有的goodsId
List<Long> goodsIds = indexConfigs.stream().map(IndexConfig::getGoodsId).collect(Collectors.toList());
List<NewBeeMallGoods> newBeeMallGoods = goodsMapper.selectByPrimaryKeys(goodsIds);
newBeeMallIndexConfigGoodsVOS = BeanUtil.copyList(newBeeMallGoods, NewBeeMallIndexConfigGoodsVO.class);
for (NewBeeMallIndexConfigGoodsVO newBeeMallIndexConfigGoodsVO : newBeeMallIndexConfigGoodsVOS) {
String goodsName = newBeeMallIndexConfigGoodsVO.getGoodsName();
String goodsIntro = newBeeMallIndexConfigGoodsVO.getGoodsIntro();
// 字符串过长导致文字超出的问题
if (goodsName.length() > 30) {
goodsName = goodsName.substring(0, 30) + "...";
newBeeMallIndexConfigGoodsVO.setGoodsName(goodsName);
}
if (goodsIntro.length() > 22) {
goodsIntro = goodsIntro.substring(0, 22) + "...";
newBeeMallIndexConfigGoodsVO.setGoodsIntro(goodsIntro);
}
}
}
return newBeeMallIndexConfigGoodsVOS;
| 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 = mallUserMapper.getTotalMallUsers(pageUtil);
PageResult pageResult = new PageResult(mallUsers, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public String register(String loginName, String password) {<FILL_FUNCTION_BODY>}
@Override
public String login(String loginName, String passwordMD5, HttpSession httpSession) {
MallUser user = mallUserMapper.selectByLoginNameAndPasswd(loginName, passwordMD5);
if (user != null && httpSession != null) {
if (user.getLockedFlag() == 1) {
return ServiceResultEnum.LOGIN_USER_LOCKED.getResult();
}
//昵称太长 影响页面展示
if (user.getNickName() != null && user.getNickName().length() > 7) {
String tempNickName = user.getNickName().substring(0, 7) + "..";
user.setNickName(tempNickName);
}
NewBeeMallUserVO newBeeMallUserVO = new NewBeeMallUserVO();
BeanUtil.copyProperties(user, newBeeMallUserVO);
//设置购物车中的数量
httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY, newBeeMallUserVO);
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.LOGIN_ERROR.getResult();
}
@Override
public NewBeeMallUserVO updateUserInfo(MallUser mallUser, HttpSession httpSession) {
NewBeeMallUserVO userTemp = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
MallUser userFromDB = mallUserMapper.selectByPrimaryKey(userTemp.getUserId());
if (userFromDB != null) {
if (StringUtils.hasText(mallUser.getNickName())) {
userFromDB.setNickName(NewBeeMallUtils.cleanString(mallUser.getNickName()));
}
if (StringUtils.hasText(mallUser.getAddress())) {
userFromDB.setAddress(NewBeeMallUtils.cleanString(mallUser.getAddress()));
}
if (StringUtils.hasText(mallUser.getIntroduceSign())) {
userFromDB.setIntroduceSign(NewBeeMallUtils.cleanString(mallUser.getIntroduceSign()));
}
if (mallUserMapper.updateByPrimaryKeySelective(userFromDB) > 0) {
NewBeeMallUserVO newBeeMallUserVO = new NewBeeMallUserVO();
BeanUtil.copyProperties(userFromDB, newBeeMallUserVO);
httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY, newBeeMallUserVO);
return newBeeMallUserVO;
}
}
return null;
}
@Override
public Boolean lockUsers(Integer[] ids, int lockStatus) {
if (ids.length < 1) {
return false;
}
return mallUserMapper.lockUserBatch(ids, lockStatus) > 0;
}
}
|
if (mallUserMapper.selectByLoginName(loginName) != null) {
return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult();
}
MallUser registerUser = new MallUser();
registerUser.setLoginName(loginName);
registerUser.setNickName(loginName);
String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8");
registerUser.setPasswordMd5(passwordMD5);
if (mallUserMapper.insertSelective(registerUser) > 0) {
return ServiceResultEnum.SUCCESS.getResult();
}
return ServiceResultEnum.DB_ERROR.getResult();
| 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> copyList(List sources, Class<T> clazz) {
return copyList(sources, clazz, null);
}
public static <T> List<T> copyList(List sources, Class<T> clazz, Callback<T> callback) {<FILL_FUNCTION_BODY>}
public static Map<String, Object> toMap(Object bean, String... ignoreProperties) {
Map<String, Object> map = new LinkedHashMap<>();
List<String> ignoreList = new ArrayList<>(Arrays.asList(ignoreProperties));
ignoreList.add("class");
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
if (!ignoreList.contains(pd.getName()) && beanWrapper.isReadableProperty(pd.getName())) {
Object propertyValue = beanWrapper.getPropertyValue(pd.getName());
map.put(pd.getName(), propertyValue);
}
}
return map;
}
public static <T> T toBean(Map<String, Object> map, Class<T> beanType) {
BeanWrapper beanWrapper = new BeanWrapperImpl(beanType);
map.forEach((key, value) -> {
if (beanWrapper.isWritableProperty(key)) {
beanWrapper.setPropertyValue(key, value);
}
});
return (T) beanWrapper.getWrappedInstance();
}
public static interface Callback<T> {
void set(Object source, T target);
}
//检查Pojo对象是否有null字段
public static boolean checkPojoNullField(Object o, Class<?> clz) {
try {
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.get(o) == null) {
return false;
}
}
if (clz.getSuperclass() != Object.class) {
return checkPojoNullField(o, clz.getSuperclass());
}
return true;
} catch (IllegalAccessException e) {
return false;
}
}
}
|
List<T> targetList = new ArrayList<>();
if (sources != null) {
try {
for (Object source : sources) {
T target = clazz.newInstance();
copyProperties(source, target);
if (callback != null) {
callback.set(source, target);
}
targetList.add(target);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return targetList;
| 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];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}
|
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;
}
return effectiveURI;
}
public static String cleanString(String value) {<FILL_FUNCTION_BODY>}
}
|
if (!StringUtils.hasText(value)) {
return "";
}
value = value.toLowerCase();
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("onload", "0nl0ad");
value = value.replaceAll("xml", "xm1");
value = value.replaceAll("window", "wind0w");
value = value.replaceAll("click", "cl1ck");
value = value.replaceAll("var", "v0r");
value = value.replaceAll("let", "1et");
value = value.replaceAll("function", "functi0n");
value = value.replaceAll("return", "retu1n");
value = value.replaceAll("$", "");
value = value.replaceAll("document", "d0cument");
value = value.replaceAll("const", "c0nst");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "scr1pt");
value = value.replaceAll("insert", "1nsert");
value = value.replaceAll("drop", "dr0p");
value = value.replaceAll("create", "cre0ate");
value = value.replaceAll("update", "upd0ate");
value = value.replaceAll("alter", "a1ter");
value = value.replaceAll("from", "fr0m");
value = value.replaceAll("where", "wh1re");
value = value.replaceAll("database", "data1base");
value = value.replaceAll("table", "tab1e");
value = value.replaceAll("tb", "tb0");
return value;
| 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 length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 生成订单流水号
*
* @return
*/
public static String genOrderNo() {
StringBuffer buffer = new StringBuffer(String.valueOf(System.currentTimeMillis()));
int num = genRandomNum(4);
buffer.append(num);
return buffer.toString();
}
}
|
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 = Integer.parseInt(params.get("limit").toString());
this.put("start", (page - 1) * limit);
this.put("page", page);
this.put("limit", limit);
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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.lang.Object>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public Set<java.lang.String> keySet() ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public Collection<java.lang.Object> values() <variables>final boolean accessOrder,transient Entry<java.lang.String,java.lang.Object> head,private static final long serialVersionUID,transient Entry<java.lang.String,java.lang.Object> tail
|
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 Boolean validKeyword(String keyword) {
String regex = "^[a-zA-Z0-9\u4E00-\u9FA5]+$";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(keyword);
return match.matches();
}
/**
* 判断是否是邮箱
*
* @param emailStr
* @return
*/
public static boolean isEmail(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
/**
* 判断是否是网址
*
* @param urlString
* @return
*/
public static boolean isURL(String urlString) {<FILL_FUNCTION_BODY>}
}
|
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;
} else {
return false;
}
| 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 = message;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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);
return result;
}
public static Result genSuccessResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(message);
return result;
}
public static Result genSuccessResult(Object data) {<FILL_FUNCTION_BODY>}
public static Result genFailResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SERVER_ERROR);
if (!StringUtils.hasText(message)) {
result.setMessage(DEFAULT_FAIL_MESSAGE);
} else {
result.setMessage(message);
}
return result;
}
public static Result genErrorResult(int code, String message) {
Result result = new Result();
result.setResultCode(code);
result.setMessage(message);
return result;
}
}
|
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) {
result = result + "-";
}
System.out.println(result);
return result;
} catch (Exception e) {
return null;
}
| 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(HttpSecurity http) throws Exception {
http.csrf().disable()
.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(requests -> requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
return http.build();
}
}
|
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(ProceedingJoinPoint joinPoint) {<FILL_FUNCTION_BODY>}
private String buildLockKey(String prefix, Method method, Object[] args) {
StringBuilder builder = new StringBuilder();
if (StringUtils.hasText(prefix)) {
builder.append(KEY_SEPARATOR).append(prefix);
}
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
builder.append(KEY_SEPARATOR);
if (parameters[i].isAnnotationPresent(Key.class)) {
Key key = parameters[i].getAnnotation(Key.class);
builder.append(parseKeyExpr(key.expr(), args[i]));
}
}
return builder.toString();
}
private String parseKeyExpr(String expr, Object arg) {
if (!StringUtils.hasText(expr)) {
return arg.toString();
}
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(expr, new TemplateParserContext());
return expression.getValue(arg, String.class);
}
}
|
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());
RLock rLock = redissonClient.getLock(lockKey);
if (lock.isWait() ? rLock.tryLock(lock.waitTime(), TimeUnit.SECONDS) : rLock.tryLock()) {
try {
return joinPoint.proceed();
} finally {
rLock.unlock();
}
}
throw new BusinessException(lock.failCode());
| 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(
ApiRouterConsts.API_AUTHOR_URL_PREFIX + "/register",
ApiRouterConsts.API_AUTHOR_URL_PREFIX + "/status"
);
@Override
public void auth(String token, String requestUri) throws BusinessException {<FILL_FUNCTION_BODY>}
}
|
// 统一账号认证
Long userId = authSSO(jwtUtils, userInfoCacheManager, token);
if (EXCLUDE_URI.contains(requestUri)) {
// 该请求不需要进行作家权限认证
return;
}
// 作家权限认证
AuthorInfoDto authorInfo = authorInfoCacheManager.getAuthor(userId);
if (Objects.isNull(authorInfo)) {
// 作家账号不存在,无权访问作家专区
throw new BusinessException(ErrorCodeEnum.USER_UN_AUTH);
}
// 设置作家ID到当前线程
UserHolder.setAuthorId(authorInfo.getId());
| 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;
/**
* 该构造函数用于通用分页查询的场景 接收普通分页数据和普通集合
*/
public PageRespDto(long pageNum, long pageSize, long total, List<T> list) {
this.pageNum = pageNum;
this.pageSize = pageSize;
this.total = total;
this.list = list;
}
public static <T> PageRespDto<T> of(long pageNum, long pageSize, long total, List<T> list) {
return new PageRespDto<>(pageNum, pageSize, total, list);
}
/**
* 获取分页数
*/
public long getPages() {<FILL_FUNCTION_BODY>}
}
|
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();
/**
* 获得字体
*/
private Font getFont() {
return new Font("Fixed", Font.PLAIN, 23);
}
/**
* 生成校验码图片
*/
public String genVerifyCodeImg(String verifyCode) throws IOException {
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
Graphics g = image.getGraphics();
//图片大小
g.fillRect(0, 0, width, height);
//字体大小
//字体颜色
g.setColor(new Color(204, 204, 204));
// 绘制干扰线
// 干扰线数量
int lineSize = 40;
for (int i = 0; i <= lineSize; i++) {
drawLine(g);
}
// 绘制随机字符
drawString(g, verifyCode);
g.dispose();
//将图片转换成Base64字符串
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", stream);
return Base64.getEncoder().encodeToString(stream.toByteArray());
}
/**
* 绘制字符串
*/
private void drawString(Graphics g, String verifyCode) {
for (int i = 1; i <= verifyCode.length(); i++) {
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
.nextInt(121)));
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(String.valueOf(verifyCode.charAt(i - 1)), 13 * i, 23);
}
}
/**
* 绘制干扰线
*/
private void drawLine(Graphics g) {<FILL_FUNCTION_BODY>}
/**
* 获取随机的校验码
*/
public String getRandomVerifyCode(int num) {
int randNumberSize = randNumber.length();
StringBuilder verifyCode = new StringBuilder();
for (int i = 0; i < num; i++) {
String rand = String.valueOf(randNumber.charAt(random.nextInt(randNumberSize)));
verifyCode.append(rand);
}
return verifyCode.toString();
}
}
|
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)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN_IP.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 处理多IP的情况(只取第一个IP)
if (ip != null && ip.contains(IP_SEPARATOR)) {
String[] ipArray = ip.split(IP_SEPARATOR);
ip = ipArray[0];
}
return 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 redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(
connectionFactory);
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues().prefixCacheNameWith(CacheConsts.REDIS_CACHE_PREFIX);
Map<String, RedisCacheConfiguration> cacheMap = new LinkedHashMap<>(
CacheConsts.CacheEnum.values().length);
// 类型推断 var 非常适合 for 循环,JDK 10 引入,JDK 11 改进
for (var c : CacheConsts.CacheEnum.values()) {
if (c.isRemote()) {
if (c.getTtl() > 0) {
cacheMap.put(c.getName(),
RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()
.prefixCacheNameWith(CacheConsts.REDIS_CACHE_PREFIX)
.entryTtl(Duration.ofSeconds(c.getTtl())));
} else {
cacheMap.put(c.getName(),
RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()
.prefixCacheNameWith(CacheConsts.REDIS_CACHE_PREFIX));
}
}
}
RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
defaultCacheConfig, cacheMap);
redisCacheManager.setTransactionAware(true);
redisCacheManager.initializeCaches();
return redisCacheManager;
}
}
|
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()) {
Caffeine<Object, Object> caffeine = Caffeine.newBuilder().recordStats()
.maximumSize(c.getMaxSize());
if (c.getTtl() > 0) {
caffeine.expireAfterWrite(Duration.ofSeconds(c.getTtl()));
}
caches.add(new CaffeineCache(c.getName(), caffeine.build()));
}
}
cacheManager.setCaches(caches);
return cacheManager;
| 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.addAllowedMethod("*");
// 是否允许携带Cookie信息
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
// 添加映射路径,拦截一切请求
configurationSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configurationSource);
| 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.certpath.SunCertPathBuilderException:
* unable to find valid certification path to requested target`
*/
@ConditionalOnProperty(value = "spring.elasticsearch.ssl.verification-mode", havingValue = "none")
@Bean
RestClient elasticsearchRestClient(RestClientBuilder restClientBuilder,
ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {<FILL_FUNCTION_BODY>}
}
|
restClientBuilder.setHttpClientConfigCallback((HttpAsyncClientBuilder clientBuilder) -> {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
log.error("Elasticsearch RestClient 配置失败!", e);
}
assert sc != null;
clientBuilder.setSSLContext(sc);
clientBuilder.setSSLHostnameVerifier((hostname, session) -> true);
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(clientBuilder));
return clientBuilder;
});
return restClientBuilder.build();
| 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 addInterceptors(InterceptorRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
// 流量限制拦截器
registry.addInterceptor(flowLimitInterceptor)
.addPathPatterns("/**")
.order(0);
// 文件访问拦截
registry.addInterceptor(fileInterceptor)
.addPathPatterns(SystemConfigConsts.IMAGE_UPLOAD_DIRECTORY + "**")
.order(1);
// 权限认证拦截
registry.addInterceptor(authInterceptor)
// 拦截会员中心相关请求接口
.addPathPatterns(ApiRouterConsts.API_FRONT_USER_URL_PREFIX + "/**",
// 拦截作家后台相关请求接口
ApiRouterConsts.API_AUTHOR_URL_PREFIX + "/**",
// 拦截平台后台相关请求接口
ApiRouterConsts.API_ADMIN_URL_PREFIX + "/**")
// 放行登录注册相关请求接口
.excludePathPatterns(ApiRouterConsts.API_FRONT_USER_URL_PREFIX + "/register",
ApiRouterConsts.API_FRONT_USER_URL_PREFIX + "/login",
ApiRouterConsts.API_ADMIN_URL_PREFIX + "/login")
.order(2);
// Token 解析拦截器
registry.addInterceptor(tokenParseInterceptor)
// 拦截小说内容查询接口,需要解析 token 以判断该用户是否有权阅读该章节(付费章节是否已购买)
.addPathPatterns(ApiRouterConsts.API_FRONT_BOOK_URL_PREFIX + "/content/*")
.order(3);
| 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
public XxlJobSpringExecutor xxlJobExecutor() {<FILL_FUNCTION_BODY>}
}
|
log.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setLogPath(logPath);
return xxlJobSpringExecutor;
| 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 servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
if (handleExcludeUrl(req)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
(HttpServletRequest) servletRequest);
filterChain.doFilter(xssRequest, servletResponse);
}
private boolean handleExcludeUrl(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
Filter.super.destroy();
}
}
|
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.find()) {
return true;
}
}
return false;
| 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, HttpServletResponse response,
Object handler) throws Exception {<FILL_FUNCTION_BODY>}
/**
* handler 执行后调用,出现异常不调用
*/
@SuppressWarnings("NullableProblems")
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/**
* DispatcherServlet 完全处理完请求后调用,出现异常照常调用
*/
@SuppressWarnings("NullableProblems")
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// 清理当前线程保存的用户数据
UserHolder.clear();
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
|
// 获取登录 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 systemName = subUri.substring(0, subUri.indexOf("/"));
String authStrategyName = String.format("%sAuthStrategy", systemName);
// 开始认证
try {
authStrategy.get(authStrategyName).auth(token, requestUri);
return HandlerInterceptor.super.preHandle(request, response, handler);
} catch (BusinessException exception) {
// 认证失败
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(
objectMapper.writeValueAsString(RestResp.fail(exception.getErrorCodeEnum())));
return false;
}
| 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 {<FILL_FUNCTION_BODY>}
}
|
// 获取请求的 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 + requestUri)) {
byte[] b = new byte[4096];
for (int n; (n = input.read(b)) != -1; ) {
out.write(b, 0, n);
}
}
return false;
| 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<>();
FlowRule rule1 = new FlowRule();
rule1.setResource(NOVEL_RESOURCE);
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
// Set limit QPS to 2000.
rule1.setCount(2000);
rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
rules.add(rule1);
FlowRuleManager.loadRules(rules);
// 接口防刷规则 1:所有的请求,限制每个 IP 每秒最多只能通过 50 个,超出限制直接拒绝
ParamFlowRule rule2 = new ParamFlowRule(NOVEL_RESOURCE)
.setParamIdx(0)
.setCount(50);
// 接口防刷规则 2:所有的请求,限制每个 IP 每分钟最多只能通过 1000 个,超出限制直接拒绝
ParamFlowRule rule3 = new ParamFlowRule(NOVEL_RESOURCE)
.setParamIdx(0)
.setCount(1000)
.setDurationInSec(60);
ParamFlowRuleManager.loadRules(Arrays.asList(rule2, rule3));
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {<FILL_FUNCTION_BODY>}
}
|
String ip = IpUtils.getRealIp(request);
Entry entry = null;
try {
// 若需要配置例外项,则传入的参数只支持基本类型。
// EntryType 代表流量类型,其中系统规则只对 IN 类型的埋点生效
// count 大多数情况都填 1,代表统计为一次调用。
entry = SphU.entry(NOVEL_RESOURCE, EntryType.IN, 1, ip);
// Your logic here.
return HandlerInterceptor.super.preHandle(request, response, handler);
} catch (BlockException ex) {
// Handle request rejection.
log.info("IP:{}被限流了!", ip);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter()
.write(objectMapper.writeValueAsString(RestResp.fail(ErrorCodeEnum.USER_REQ_MANY)));
} finally {
// 注意:exit 的时候也一定要带上对应的参数,否则可能会有统计错误。
if (entry != null) {
entry.exit(1, ip);
}
}
return false;
| 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>}
/**
* DispatcherServlet 完全处理完请求后调用,出现异常照常调用
*/
@SuppressWarnings("NullableProblems")
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// 清理当前线程保存的用户数据
UserHolder.clear();
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
|
// 获取登录 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.super.preHandle(request, response, handler);
| 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_FUNCTION_BODY>}
}
|
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 " + response.version());
| 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())
.gt(DatabaseConsts.CommonColumnEnum.ID.getName(), maxId)
.gt(DatabaseConsts.BookTable.COLUMN_WORD_COUNT, 0)
.last(DatabaseConsts.SqlEnum.LIMIT_30.getSql());
bookInfos = bookInfoMapper.selectList(queryWrapper);
if (bookInfos.isEmpty()) {
break;
}
BulkRequest.Builder br = new BulkRequest.Builder();
for (BookInfo book : bookInfos) {
br.operations(op -> op
.index(idx -> idx
.index(EsConsts.BookIndex.INDEX_NAME)
.id(book.getId().toString())
.document(EsBookDto.build(book))
)
).timeout(Time.of(t -> t.time("10s")));
maxId = book.getId();
}
BulkResponse result = elasticsearchClient.bulk(br.build());
// Log errors, if any
if (result.errors()) {
log.error("Bulk had errors");
for (BulkResponseItem item : result.items()) {
if (item.error() != null) {
log.error(item.error().reason());
}
}
}
}
return ReturnT.SUCCESS;
} catch (Exception e) {
log.error(e.getMessage(), e);
return ReturnT.FAIL;
}
| 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 系统标识
* @return JWT
*/
public String generateToken(Long uid, String systemKey) {
return Jwts.builder()
.setHeaderParam(HEADER_SYSTEM_KEY, systemKey)
.setSubject(uid.toString())
.signWith(Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)))
.compact();
}
/**
* 解析JWT返回用户ID
*
* @param token JWT
* @param systemKey 系统标识
* @return 用户ID
*/
public Long parseToken(String token, String systemKey) {<FILL_FUNCTION_BODY>}
}
|
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 是否属于指定系统
if (Objects.equals(claimsJws.getHeader().get(HEADER_SYSTEM_KEY), systemKey)) {
return Long.parseLong(claimsJws.getBody().getSubject());
}
} catch (JwtException e) {
log.warn("JWT解析失败:{}", token);
// don't trust the JWT!
}
return null;
| 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("<", "<");
REPLACE_RULE.put(">", ">");
}
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name) {<FILL_FUNCTION_BODY>}
}
|
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;
REPLACE_RULE.forEach(
(k, v) -> escapeValues[index] = escapeValues[index].replaceAll(k, v));
}
return escapeValues;
}
return new String[0];
| 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;
/**
* 是否使用过;0-未使用 1-使用过
*/
private Integer isUsed;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInviteCode() {
return inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode;
}
public LocalDateTime getValidityTime() {
return validityTime;
}
public void setValidityTime(LocalDateTime validityTime) {
this.validityTime = validityTime;
}
public Integer getIsUsed() {
return isUsed;
}
public void setIsUsed(Integer isUsed) {
this.isUsed = isUsed;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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;
/**
* 收入月份
*/
private LocalDate incomeMonth;
/**
* 税前收入;单位:分
*/
private Integer preTaxIncome;
/**
* 税后收入;单位:分
*/
private Integer afterTaxIncome;
/**
* 支付状态;0-待支付 1-已支付
*/
private Integer payStatus;
/**
* 稿费确认状态;0-待确认 1-已确认
*/
private Integer confirmStatus;
/**
* 详情
*/
private String detail;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public LocalDate getIncomeMonth() {
return incomeMonth;
}
public void setIncomeMonth(LocalDate incomeMonth) {
this.incomeMonth = incomeMonth;
}
public Integer getPreTaxIncome() {
return preTaxIncome;
}
public void setPreTaxIncome(Integer preTaxIncome) {
this.preTaxIncome = preTaxIncome;
}
public Integer getAfterTaxIncome() {
return afterTaxIncome;
}
public void setAfterTaxIncome(Integer afterTaxIncome) {
this.afterTaxIncome = afterTaxIncome;
}
public Integer getPayStatus() {
return payStatus;
}
public void setPayStatus(Integer payStatus) {
this.payStatus = payStatus;
}
public Integer getConfirmStatus() {
return confirmStatus;
}
public void setConfirmStatus(Integer confirmStatus) {
this.confirmStatus = confirmStatus;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "AuthorIncome{" +
"id=" + id +
", authorId=" + authorId +
", bookId=" + bookId +
", incomeMonth=" + incomeMonth +
", preTaxIncome=" + preTaxIncome +
", afterTaxIncome=" + afterTaxIncome +
", payStatus=" + payStatus +
", confirmStatus=" + confirmStatus +
", detail=" + detail +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
| 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;
/**
* 收入日期
*/
private LocalDate incomeDate;
/**
* 订阅总额
*/
private Integer incomeAccount;
/**
* 订阅次数
*/
private Integer incomeCount;
/**
* 订阅人数
*/
private Integer incomeNumber;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public LocalDate getIncomeDate() {
return incomeDate;
}
public void setIncomeDate(LocalDate incomeDate) {
this.incomeDate = incomeDate;
}
public Integer getIncomeAccount() {
return incomeAccount;
}
public void setIncomeAccount(Integer incomeAccount) {
this.incomeAccount = incomeAccount;
}
public Integer getIncomeCount() {
return incomeCount;
}
public void setIncomeCount(Integer incomeCount) {
this.incomeCount = incomeCount;
}
public Integer getIncomeNumber() {
return incomeNumber;
}
public void setIncomeNumber(Integer incomeNumber) {
this.incomeNumber = incomeNumber;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "AuthorIncomeDetail{" +
"id=" + id +
", authorId=" + authorId +
", bookId=" + bookId +
", incomeDate=" + incomeDate +
", incomeAccount=" + incomeAccount +
", incomeCount=" + incomeCount +
", incomeNumber=" + incomeNumber +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
| 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;
/**
* 笔名
*/
private String penName;
/**
* 手机号码
*/
private String telPhone;
/**
* QQ或微信账号
*/
private String chatAccount;
/**
* 电子邮箱
*/
private String email;
/**
* 作品方向;0-男频 1-女频
*/
private Integer workDirection;
/**
* 0:正常;1-封禁
*/
private Integer status;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getInviteCode() {
return inviteCode;
}
public void setInviteCode(String inviteCode) {
this.inviteCode = inviteCode;
}
public String getPenName() {
return penName;
}
public void setPenName(String penName) {
this.penName = penName;
}
public String getTelPhone() {
return telPhone;
}
public void setTelPhone(String telPhone) {
this.telPhone = telPhone;
}
public String getChatAccount() {
return chatAccount;
}
public void setChatAccount(String chatAccount) {
this.chatAccount = chatAccount;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getWorkDirection() {
return workDirection;
}
public void setWorkDirection(Integer workDirection) {
this.workDirection = workDirection;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "AuthorInfo{" +
"id=" + id +
", userId=" + userId +
", inviteCode=" + inviteCode +
", penName=" + penName +
", telPhone=" + telPhone +
", chatAccount=" + chatAccount +
", email=" + email +
", workDirection=" + workDirection +
", status=" + status +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
| 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;
/**
* 排序
*/
private Integer sort;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getWorkDirection() {
return workDirection;
}
public void setWorkDirection(Integer workDirection) {
this.workDirection = workDirection;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
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 String chapterName;
/**
* 章节字数
*/
private Integer wordCount;
/**
* 是否收费;1-收费 0-免费
*/
private Integer isVip;
private LocalDateTime createTime;
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public Integer getChapterNum() {
return chapterNum;
}
public void setChapterNum(Integer chapterNum) {
this.chapterNum = chapterNum;
}
public String getChapterName() {
return chapterName;
}
public void setChapterName(String chapterName) {
this.chapterName = chapterName;
}
public Integer getWordCount() {
return wordCount;
}
public void setWordCount(Integer wordCount) {
this.wordCount = wordCount;
}
public Integer getIsVip() {
return isVip;
}
public void setIsVip(Integer isVip) {
this.isVip = isVip;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "BookChapter{" +
"id=" + id +
", bookId=" + bookId +
", chapterNum=" + chapterNum +
", chapterName=" + chapterName +
", wordCount=" + wordCount +
", isVip=" + isVip +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
| 581
| 104
| 685
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.