Dataset Viewer
Auto-converted to Parquet Duplicate
code
stringlengths
1
1.05M
repo_name
stringlengths
7
65
path
stringlengths
2
255
language
stringclasses
236 values
license
stringclasses
24 values
size
int64
1
1.05M
package com.study.aio.client; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; /** * Created by wusz on 2018/5/17. */ public class AsyncTimeClientHandler implements Runnable,CompletionHandler<Void,AsyncTimeClientHandler> { private String host; private int port; AsynchronousSocketChannel client; CountDownLatch latch; public AsyncTimeClientHandler(String host, int port) { this.host = host; this.port = port; try { client = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { latch = new CountDownLatch(1); client.connect(new InetSocketAddress(host,port),this,this); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } try { client.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void completed(Void result, AsyncTimeClientHandler attachment) { byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { if(buffer.hasRemaining()) { client.write(buffer,buffer,this); } else { ByteBuffer readBuffer = ByteBuffer.allocate(1024); client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); try { String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); latch.countDown(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { client.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { client.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); } @Override public void failed(Throwable exc, AsyncTimeClientHandler attachment) { } }
vincentjava/netty-study
src/main/java/com/study/aio/client/AsyncTimeClientHandler.java
Java
apache-2.0
3,563
package com.study.aio.client; /** * @description: * @author: wusz * @date: 2018/6/12 */ public class Demo1 { }
vincentjava/netty-study
src/main/java/com/study/aio/client/Demo1.java
Java
apache-2.0
116
package com.study.aio.client; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by wusz on 2018/5/17. */ public class Test implements Serializable { public String s = "hello"; public static final long serialVersionUID = -4841994837142898086L; private List<String> list = new ArrayList<>(); /* stash测试 */ public static void main(String[] args) throws UnsupportedEncodingException, ParseException { // testLatch(); // bigDecimal(); // Date date = new Date(); // System.out.println(System.currentTimeMillis()); // long l = System.currentTimeMillis(); // Date date = new Date(l); // Date date1 = new Date(l); // System.out.println(date.equals(date1)); // String tom = new String("Tom"); // System.out.println(tom); // serialize(); // fun(); /*Test t1 = new Test(); Test t2 = new Test(); System.out.println(t1.equals(t2)); List<Test> list = Arrays.asList(t1); boolean c = list.contains(t2); System.out.println(c); System.out.println(((Test)null).serialVersionUID);*/ // try { // int i = 1 / 0; // } finally { // System.out.println("end"); // } // System.out.println("-----"+System.getProperty("line.separator")+"------"); /*ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.putInt(3); byteBuffer.position(0); byteBuffer.put("hello".getBytes()); byteBuffer.flip(); byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); System.out.println(new String(bytes,"UTF-8"));*/ /* List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); list.remove(5L); System.out.println(list);*/ /*List<String> list = Arrays.asList("a","b"); String[] arr1 = list.stream().toArray(size -> { System.out.println(size); return new String[size]; }); String s = StringUtils.join(list, " "); System.out.println(s);*/ /*double v = 1.4999; String s = new BigDecimal(v).setScale(2, BigDecimal.ROUND_HALF_UP).toString(); System.out.println(s);*/ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"); Date date1 = sdf.parse("2018-06-06 12:00:00"); Date date2 = sdf.parse("2019-06-06 12:00:00"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int start = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(date2); int end = calendar.get(Calendar.DAY_OF_YEAR); long time = date2.getTime() - date1.getTime(); if(start != end || time > 24 * 60 * 3600 * 1000) { System.out.println("error"); } } @Override public boolean equals(Object obj) { if(obj instanceof Test) { Test t = (Test) obj; if(t.s.equalsIgnoreCase(this.s)) { return true; } } return super.equals(obj); } private static void fun() { for(int i = 1; i<101;i++) { for(int j = 2; ; j++) { if(j >= i) { System.out.println(i); break; } if(i % j == 0) break; } } } @org.junit.Test public void candidate() { List<Integer> list = Arrays.asList(1, 2); listAll(list,""); } private void listAll(List<Integer> list, String s) { for(int i = 0; i< list.size();i++) { List<Integer> list1 = new LinkedList<>(list); String temp = s + list.get(i); System.out.println(temp); list1.remove(i); listAll(list1,temp); } } @org.junit.Test public void dserialize() throws IOException, ClassNotFoundException { try (ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.txt"))) { Test test = (Test)is.readObject(); System.out.println(test.serialVersionUID); System.out.println(test.list); } } @org.junit.Test public void serialize() throws IOException { Test test = new Test(); System.out.println(test.serialVersionUID); test.list.addAll(Arrays.asList("a","b")); System.out.println(test.list); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.txt")); os.writeObject(test); os.close(); } private static void bigDecimal() { BigDecimal bigDecimal = new BigDecimal(1); BigDecimal bigDecimal1 = bigDecimal.setScale(1, BigDecimal.ROUND_DOWN); System.out.println(bigDecimal); System.out.println(bigDecimal1); } /*private static void testLatch() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); executor.execute(()->{ try { System.out.println("睡眠中"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } for (int i=0;i<2;i++) { System.out.println("释放:" + i); latch.countDown(); } }); latch.await(); System.out.println("end"); executor.shutdown(); }*/ }
vincentjava/netty-study
src/main/java/com/study/aio/client/Test.java
Java
apache-2.0
5,568
package com.study.aio.client; /** * Created by wusz on 2018/5/17. */ public class TimeClient { public static void main(String[] args) { new Thread(new AsyncTimeClientHandler("127.0.0.1", 8080)).start(); } }
vincentjava/netty-study
src/main/java/com/study/aio/client/TimeClient.java
Java
apache-2.0
226
package com.study.aio.server; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * Created by wusz on 2018/5/16. */ public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> { @Override public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) { attachment.asynchronousServerSocketChannel.accept(attachment,this); ByteBuffer buffer = ByteBuffer.allocate(1024); result.read(buffer,buffer,new ReadCompletionHandler(result)); } @Override public void failed(Throwable exc, AsyncTimeServerHandler attachment) { exc.printStackTrace(); attachment.latch.countDown(); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/AcceptCompletionHandler.java
Java
apache-2.0
802
package com.study.aio.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AsynchronousServerSocketChannel; import java.util.concurrent.CountDownLatch; public class AsyncTimeServerHandler implements Runnable { private int port; AsynchronousServerSocketChannel asynchronousServerSocketChannel; CountDownLatch latch; public AsyncTimeServerHandler(int port) { this.port = port; try { asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open(); asynchronousServerSocketChannel.bind(new InetSocketAddress(port)); System.out.println("The time server is start in port:"+port); } catch (IOException e) { e.printStackTrace(); } } public void run() { latch = new CountDownLatch(1); doAccept(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void doAccept() { asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler()); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/AsyncTimeServerHandler.java
Java
apache-2.0
1,121
package com.study.aio.server; import io.netty.util.internal.StringUtil; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.Date; /** * Created by wusz on 2018/5/16. */ public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> { private AsynchronousSocketChannel channel; public ReadCompletionHandler(AsynchronousSocketChannel channel) { this.channel = channel; } @Override public void completed(Integer result, ByteBuffer attachment) { attachment.flip(); byte[] body = new byte[attachment.remaining()]; attachment.get(body); try { String req = new String(body, "UTF-8"); System.out.println("The time server receive order:"+req); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; doWirte(currentTime); } catch (Exception e) { } } private void doWirte(String currentTime) { if(currentTime != null && currentTime.trim().length() > 0) { byte[] bytes = currentTime.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer buffer) { if(buffer.hasRemaining()) { channel.write(buffer,buffer,this); } } @Override public void failed(Throwable exc, ByteBuffer buffer) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } }); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { this.channel.close(); } catch (IOException e) { e.printStackTrace(); } } }
vincentjava/netty-study
src/main/java/com/study/aio/server/ReadCompletionHandler.java
Java
apache-2.0
2,281
package com.study.aio.server; public class TimeServer { public static void main(String[] args) { AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(8080); new Thread(timeServer,"AIO-AsyncTimeServerHandler-001").start(); } }
vincentjava/netty-study
src/main/java/com/study/aio/server/TimeServer.java
Java
apache-2.0
261
package com.study.four.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeClient { public void connect(int port, String host) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) { int port = 8080; new TimeClient().connect(port,"127.0.0.1"); } }
vincentjava/netty-study
src/main/java/com/study/four/client/TimeClient.java
Java
apache-2.0
1,696
package com.study.four.client; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Logger; /** * Created by wusz on 2018/5/28. */ public class TimeClientHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName()); private byte[] req; public TimeClientHandler() { req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream: " + cause.getMessage()); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { for (int i = 0; i < 2; i++) { ByteBuf msg = Unpooled.buffer(req.length); msg.writeBytes(req); ctx.channel().writeAndFlush(msg); System.out.println("send " + i + " msg..........."); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String message = (String) msg; System.out.println("Now is : " + message); } }
vincentjava/netty-study
src/main/java/com/study/four/client/TimeClientHandler.java
Java
apache-2.0
1,341
package com.study.four.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeServer { public void bind(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) { int port = 8080; new TimeServer().bind(port); } }
vincentjava/netty-study
src/main/java/com/study/four/server/TimeServer.java
Java
apache-2.0
1,778
package com.study.four.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * Created by wusz on 2018/5/28. */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String body = (String) msg; System.out.println("The time server receiver order: " + body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; currentTime += System.getProperty("line.separator"); ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); ctx.writeAndFlush(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
vincentjava/netty-study
src/main/java/com/study/four/server/TimeServerHandler.java
Java
apache-2.0
1,098
package com.study.http.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpRequestDecoder; /** * @description: * @author: wusz * @date: 2018/6/8 */ public class HttpFileServer { private static final String DEFAULT_URL = "D:/study"; public void run(final int port, final String url) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder",new HttpRequestDecoder()); } }); } }
vincentjava/netty-study
src/main/java/com/study/http/server/HttpFileServer.java
Java
apache-2.0
1,159
package com.study.nio.client; /** * Create by wusz on 2018/5/14 */ public class TimeClient { public static void main(String[] args) { int port = 8080; new Thread(new TimeClientHandler("127.0.0.1",port)).start(); } }
vincentjava/netty-study
src/main/java/com/study/nio/client/TimeClient.java
Java
apache-2.0
243
package com.study.nio.client; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; /** * Create by wusz on 2018/5/14 */ public class TimeClientHandler implements Runnable { private String host; private int port; private Selector selector; private SocketChannel socketChannel; private boolean stop; public TimeClientHandler(String host, int port) { this.host = host == null ? "127.0.0.1" : host; this.port = port; try { selector = Selector.open(); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void run() { try { doConnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } while (!stop) { try { selector.select(1000); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(key); } catch (IOException e) { if (key != null) { key.cancel(); if (key.channel() != null) { key.channel().close(); } } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } if (selector != null) { try { selector.close(); } catch (IOException e) { e.printStackTrace(); } } } private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); doWrite(sc); } else { System.exit(1); } } if (key.isReadable()) { ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { key.cancel(); sc.close(); } else ; } } } private void doConnect() throws IOException { if (socketChannel.connect(new InetSocketAddress(host, port))) { socketChannel.register(selector, SelectionKey.OP_READ); doWrite(socketChannel); } else { socketChannel.register(selector, SelectionKey.OP_CONNECT); } } private void doWrite(SocketChannel sc) throws IOException { byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); sc.write(writeBuffer); if (!writeBuffer.hasRemaining()) { System.out.println("Send order 2 server succeed"); } } }
vincentjava/netty-study
src/main/java/com/study/nio/client/TimeClientHandler.java
Java
apache-2.0
4,048
package com.study.nio.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Date; import java.util.Iterator; import java.util.Set; /** * Create by wusz on 2018/5/11 */ public class MultiplexerTimeServer implements Runnable { private int port; private Selector selector; private ServerSocketChannel servChannel; private volatile boolean stop; public MultiplexerTimeServer(int port) { this.port = port; try { selector = Selector.open(); servChannel = ServerSocketChannel.open(); servChannel.configureBlocking(false); servChannel.socket().bind(new InetSocketAddress(port)); servChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("The time server is start in port:"+ port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void stop() { this.stop = true; } public void run() { while (!stop) { try { selector.select(1000); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try{ handleInput(key); }catch (Exception e) { if(key != null) { key.cancel(); if(key.channel() != null) { key.channel().close(); } } } } } catch (IOException e) { e.printStackTrace(); } } } private void handleInput(SelectionKey key) throws IOException { if(key.isValid()) { if(key.isAcceptable()) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector,SelectionKey.OP_READ); } if(key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if(readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes,"UTF-8"); System.out.println("The time server receive order:"+body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; doWrite(sc,currentTime); } else if(readBytes < 0) { key.cancel(); sc.close(); } else { } } } } private void doWrite(SocketChannel channel, String response) throws IOException { if(response != null && response.trim().length()>0) { byte[] bytes = response.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); channel.write(writeBuffer); } } }
vincentjava/netty-study
src/main/java/com/study/nio/server/MultiplexerTimeServer.java
Java
apache-2.0
3,801
package com.study.nio.server; /** * Create by wusz on 2018/5/11 */ public class TimeServer { public static void main(String[] args) { int port = 8080; MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port); new Thread(timeServer,"NIO-MultiplexerTimeServer").start(); } }
vincentjava/netty-study
src/main/java/com/study/nio/server/TimeServer.java
Java
apache-2.0
318
package com.study.three.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeClient { public void connect(int port, String host) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) { int port = 8080; new TimeClient().connect(port,"127.0.0.1"); } }
vincentjava/netty-study
src/main/java/com/study/three/client/TimeClient.java
Java
apache-2.0
1,697
package com.study.three.client; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Logger; /** * Created by wusz on 2018/5/28. */ public class TimeClientHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName()); private final ByteBuf firstMessage; public TimeClientHandler() { byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warning("Unexpected exception from downstream: " + cause.getMessage()); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { for (int i = 0; i < 10; i++) { ctx.channel().writeAndFlush(firstMessage); System.out.println("send " + i + " msg..........."); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("Now is : " + body); } }
vincentjava/netty-study
src/main/java/com/study/three/client/TimeClientHandler.java
Java
apache-2.0
1,500
package com.study.three.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Created by wusz on 2018/5/28. */ public class TimeServer { public void bind(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeServerHandler()); } } public static void main(String[] args) { int port = 8080; new TimeServer().bind(port); } }
vincentjava/netty-study
src/main/java/com/study/three/server/TimeServer.java
Java
apache-2.0
1,779
package com.study.three.server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * Created by wusz on 2018/5/28. */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("The time server receiver order: " + body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; ByteBuf resp = Unpooled.copiedBuffer((currentTime + System.getProperty("line.separator")).getBytes()); ctx.write(resp); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
vincentjava/netty-study
src/main/java/com/study/three/server/TimeServerHandler.java
Java
apache-2.0
1,198
package com.kariqu.cldld.wss; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; public class CloseFramer extends CloseWebSocketFrame { private CloseFramer(WebsocketStatusCode code) { super(code.getStatusCode(), code.getStr()); } public static CloseFramer normalClose() { return new CloseFramer(WebsocketStatusCode.NORMAL_CLOSE); } public static CloseFramer repeatedLoginClose() { return new CloseFramer(WebsocketStatusCode.REPEATED_LOGIN_CLOSE); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/CloseFramer.java
Java
unknown
532
package com.kariqu.cldld.wss; public class Main { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new WebSocketServer(7910)); thread.start(); thread.join(); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/Main.java
Java
unknown
242
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor; /** * Echoes uppercase content of text frames. */ public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> { private static final Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class); public WebSocketFrameHandler() { } //通道创建监听 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("channelActive channel_id: {}", ctx.channel().id().asShortText()); } //通道销毁监听 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("channelInactive channel_id: {}", ctx.channel().id().asShortText()); } //监听通道事件 @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; switch (e.state()) { case READER_IDLE: //读取超时 handleReaderIdle(ctx); break; case WRITER_IDLE: //写入超时 handleWriterIdle(ctx); break; case ALL_IDLE: //全部超时 handleAllIdle(ctx); break; default: break; } } } /** * 消息读取 */ @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { decoder(ctx, frame); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.warn("exception: {}", cause.toString()); closeChannle(ctx); } private void decoder(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof TextWebSocketFrame) { String request_encrypt = ((TextWebSocketFrame) frame).text(); if(request_encrypt.isEmpty() || request_encrypt.trim().isEmpty()) return; String request = ""; // 解密 try { //request = Utility.decrypt(request_encrypt); request = request_encrypt; System.out.println("收到消息-----------》" + request); } catch (Exception e) { Channel channel = ctx.channel(); String str = String.format("decode websocket request decrypt error. shutdownChannel channel: %s %s" , e.toString(), channel.id().asShortText()); throw new UnsupportedOperationException(str); } } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } } private void handleReaderIdle(ChannelHandlerContext ctx) { logger.info("reader idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void handleWriterIdle(ChannelHandlerContext ctx) { logger.info("writer idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void handleAllIdle(ChannelHandlerContext ctx) { logger.info("all idle. {}", ctx.channel().id().asShortText()); closeChannle(ctx); } private void closeChannle(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); channel.writeAndFlush(CloseFramer.normalClose()); ChannelFuture f2 = ctx.close(); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketFrameHandler.java
Java
unknown
4,739
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.ssl.SslHandler; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * Outputs index page content. */ public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final Logger logger = LoggerFactory.getLogger(WebSocketIndexPageHandler.class); private final String websocketPath; public WebSocketIndexPageHandler(String websocketPath) { this.websocketPath = websocketPath; } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { //super.channelRegistered(ctx); super.channelRegistered(ctx); logger.info("====== channel registered: {}", ctx.channel().id().asLongText()); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { super.channelUnregistered(ctx); logger.info("====== channel unregistered: {}", ctx.channel().id().asLongText()); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { logger.info("===== handlerAdded {}", ctx.channel().id().asLongText()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { logger.info("===== handlerRemoved {}", ctx.channel().id().asLongText()); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { // sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } logger.info("channelRead0 return"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) { String protocol = "ws"; if (cp.get(SslHandler.class) != null) { // SSL in use so use Secure WebSockets protocol = "wss"; } return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path; } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketIndexPageHandler.java
Java
unknown
4,887
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WebSocketServer implements Runnable { private final int PORT; //= Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); public WebSocketServer(int PORT) { this.PORT = PORT; } @Override public void run() { //接收线程组 处理连接请求 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //工作线程组 处理信息读取以及发送 EventLoopGroup workerGroup = new NioEventLoopGroup(1); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer()); //初始化通道配置 Channel ch = b.bind(PORT).sync().channel(); //开启监听 客户端连接 log.info("server name: world thread: {}", Thread.currentThread().getId()); ch.closeFuture().sync(); } catch (Exception e) { log.error("exception {}", e.toString()); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServer.java
Java
unknown
2,372
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; /** * Generates the demo HTML page which is served at http://localhost:8080/ */ public final class WebSocketServerIndexPage { private static final String NEWLINE = "\r\n"; public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer( "<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + " window.WebSocket = window.MozWebSocket;" + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + " socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE + " socket.onmessage = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + '\\n' + event.data" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = \"Web Socket opened!\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE + NEWLINE + "function send(message) {" + NEWLINE + " if (!window.WebSocket) { return; }" + NEWLINE + " if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + " socket.send(message);" + NEWLINE + " } else {" + NEWLINE + " alert(\"The socket is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" + "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE + " onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII); } private WebSocketServerIndexPage() { // Unused } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServerIndexPage.java
Java
unknown
3,686
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.kariqu.cldld.wss; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; import io.netty.handler.timeout.IdleStateHandler; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; /** */ public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> { private static final String HTTP_PATH = "/http"; private final SSLContext context = null; public WebSocketServerInitializer(/*SslContext sslCtx,*/) { } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); int readTimeout = 5; int writeTimeout = 0; //设置读取写入超时时间 pipeline.addLast(new IdleStateHandler(readTimeout, writeTimeout,0)); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new WebSocketServerProtocolHandler("/websocket", null, true)); //设置消息处理器 pipeline.addLast(new WebSocketFrameHandler()); } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebSocketServerInitializer.java
Java
unknown
2,233
package com.kariqu.cldld.wss; /* 0-999 Status codes in the range 0-999 are not used. 1000-2999 Status codes in the range 1000-2999 are reserved for definition by this protocol, its future revisions, and extensions specified in a permanent and readily available public specification. 3000-3999 Status codes in the range 3000-3999 are reserved for use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by this protocol. 4000-4999 Status codes in the range 4000-4999 are reserved for private use and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by this protocol. */ public enum WebsocketStatusCode { NORMAL_CLOSE(4000, "normal_close"), // 正常关闭 REPEATED_LOGIN_CLOSE(4001, "repeated_login_close"); // 重复登陆关闭 private int statusCode; private String str; private WebsocketStatusCode(int code, String str) { this.statusCode = code; this.str = str; } public int getStatusCode() { return statusCode; } public String getStr() { return str; } }
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/WebsocketStatusCode.java
Java
unknown
1,419
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * <p>This package contains an example web socket web server. * <p>The web server only handles text, ping and closing frames. For text frames, * it echoes the received text in upper case. * <p>Once started, you can test the web server against your browser by navigating * to http://localhost:8080/ * <p>You can also test it with a web socket client. Send web socket traffic to * ws://localhost:8080/websocket. */ package com.kariqu.cldld.wss;
vincentjava/ws_server
src/main/java/com/kariqu/cldld/wss/package-info.java
Java
unknown
1,091
cmake_minimum_required(VERSION 3.1 FATAL_ERROR) file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/src/oatpp/core/base/Environment.hpp" OATPP_VERSION_MACRO REGEX "#define OATPP_VERSION \"[0-9]+.[0-9]+.[0-9]+\"$") string(REGEX REPLACE "#define OATPP_VERSION \"([0-9]+.[0-9]+.[0-9]+)\"$" "\\1" oatpp_VERSION "${OATPP_VERSION_MACRO}") ################################################################################################### ## These variables are passed to oatpp-module-install.cmake script ## use these variables to configure module installation set(OATPP_THIS_MODULE_NAME oatpp) ## name of the module (also name of folders in installation dirs) set(OATPP_THIS_MODULE_VERSION ${oatpp_VERSION}) ## version of the module (also sufix of folders in installation dirs) ################################################################################################### project(oatpp VERSION ${OATPP_THIS_MODULE_VERSION} LANGUAGES CXX) option(BUILD_SHARED_LIBS "Build shared libraries" OFF) option(OATPP_INSTALL "Create installation target for oat++" ON) option(OATPP_BUILD_TESTS "Create test target for oat++" ON) option(OATPP_LINK_TEST_LIBRARY "Link oat++ test library" ON) option(OATPP_LINK_ATOMIC "Link atomic library for other platform than MSVC|MINGW|APPLE|FreeBSD" ON) option(OATPP_MSVC_LINK_STATIC_RUNTIME "MSVC: Link with static runtime (/MT and /MTd)." OFF) ################################################################################################### ## COMPILATION CONFIG ############################################################################# ################################################################################################### if(OATPP_LINK_TEST_LIBRARY) set(OATPP_THIS_MODULE_LIBRARIES oatpp oatpp-test) ## list of libraries to find when find_package is called set(OATPP_THIS_MODULE_TARGETS oatpp oatpp-test) ## list of targets to install set(OATPP_THIS_MODULE_DIRECTORIES oatpp oatpp-test) ## list of directories to install else() set(OATPP_THIS_MODULE_LIBRARIES oatpp) ## list of libraries to find when find_package is called set(OATPP_THIS_MODULE_TARGETS oatpp) ## list of targets to install set(OATPP_THIS_MODULE_DIRECTORIES oatpp) ## list of directories to install endif() option(OATPP_DISABLE_ENV_OBJECT_COUNTERS "Disable object counting for Release builds for better performance" OFF) option(OATPP_DISABLE_POOL_ALLOCATIONS "This will make oatpp::base::memory::MemoryPool, method obtain and free call new and delete directly" OFF) set(OATPP_THREAD_HARDWARE_CONCURRENCY "AUTO" CACHE STRING "Predefined value for function oatpp::concurrency::Thread::getHardwareConcurrency()") option(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL "Disable 'thread_local' feature" OFF) option(OATPP_COMPAT_BUILD_NO_SET_AFFINITY "No 'pthread_setaffinity_np' method" OFF) option(OATPP_DISABLE_LOGV "DISABLE logs priority V" OFF) option(OATPP_DISABLE_LOGD "DISABLE logs priority D" OFF) option(OATPP_DISABLE_LOGI "DISABLE logs priority I" OFF) option(OATPP_DISABLE_LOGW "DISABLE logs priority W" OFF) option(OATPP_DISABLE_LOGE "DISABLE logs priority E" OFF) ## Print config ################################################################################## message("\n############################################################################") message("## oatpp module compilation config:\n") message("OATPP_DISABLE_ENV_OBJECT_COUNTERS=${OATPP_DISABLE_ENV_OBJECT_COUNTERS}") message("OATPP_THREAD_HARDWARE_CONCURRENCY=${OATPP_THREAD_HARDWARE_CONCURRENCY}") message("OATPP_COMPAT_BUILD_NO_THREAD_LOCAL=${OATPP_COMPAT_BUILD_NO_THREAD_LOCAL}") ## Set definitions ############################################################################### if(OATPP_DISABLE_ENV_OBJECT_COUNTERS) add_definitions(-DOATPP_DISABLE_ENV_OBJECT_COUNTERS) endif() if(OATPP_DISABLE_POOL_ALLOCATIONS) add_definitions (-DOATPP_DISABLE_POOL_ALLOCATIONS) message("WARNING: OATPP_DISABLE_POOL_ALLOCATIONS option is deprecated and has no effect.") endif() set(AUTO_VALUE AUTO) if(NOT OATPP_THREAD_HARDWARE_CONCURRENCY STREQUAL AUTO_VALUE) add_definitions (-DOATPP_THREAD_HARDWARE_CONCURRENCY=${OATPP_THREAD_HARDWARE_CONCURRENCY}) endif() if(OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT) add_definitions (-DOATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT=${OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT}) message("WARNING: OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT option is deprecated and has no effect.") endif() if(OATPP_COMPAT_BUILD_NO_THREAD_LOCAL) add_definitions(-DOATPP_COMPAT_BUILD_NO_THREAD_LOCAL) endif() if(OATPP_COMPAT_BUILD_NO_SET_AFFINITY) add_definitions(-DOATPP_COMPAT_BUILD_NO_SET_AFFINITY) endif() if(OATPP_DISABLE_LOGV) add_definitions(-DOATPP_DISABLE_LOGV) endif() if(OATPP_DISABLE_LOGD) add_definitions(-DOATPP_DISABLE_LOGD) endif() if(OATPP_DISABLE_LOGI) add_definitions(-DOATPP_DISABLE_LOGI) endif() if(OATPP_DISABLE_LOGW) add_definitions(-DOATPP_DISABLE_LOGW) endif() if(OATPP_DISABLE_LOGE) add_definitions(-DOATPP_DISABLE_LOGE) endif() if(CMAKE_COMPILER_IS_GNUCXX AND ${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 5.0) add_definitions(-DOATPP_DISABLE_STD_PUT_TIME) endif() message("\n############################################################################\n") ################################################################################################### message("oatpp version: '${OATPP_THIS_MODULE_VERSION}'") #SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") #SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread") include(cmake/msvc-runtime.cmake) configure_msvc_runtime() add_subdirectory(src) if(OATPP_BUILD_TESTS) enable_testing() add_subdirectory(test) endif() include(cpack.cmake) # This must always be last! include( CPack )
vincent-in-black-sesame/oat
CMakeLists.txt
CMake
apache-2.0
5,776
@PACKAGE_INIT@ if(NOT TARGET oatpp::@OATPP_MODULE_NAME@) include("${CMAKE_CURRENT_LIST_DIR}/@OATPP_MODULE_NAME@Targets.cmake") endif() set_and_check(@OATPP_MODULE_NAME@_INCLUDE_DIRS "${PACKAGE_PREFIX_DIR}/include/oatpp-@OATPP_MODULE_VERSION@/@OATPP_MODULE_NAME@/") set_and_check(@OATPP_MODULE_NAME@_LIBRARIES_DIRS "${PACKAGE_PREFIX_DIR}/@OATPP_MODULE_LIBDIR@/oatpp-@OATPP_MODULE_VERSION@/") set(@OATPP_MODULE_NAME@_LIBRARIES @OATPP_MODULE_LIBRARIES@) set(OATPP_BASE_DIR "${PACKAGE_PREFIX_DIR}/include/oatpp-@OATPP_MODULE_VERSION@/")
vincent-in-black-sesame/oat
cmake/module-config.cmake.in
CMake
apache-2.0
540
####################################################################################### ## Set module properties ## all oatpp modules should have the same installation procedure ## ## installation tree: ## ## prefix/ ## | ## |- include/oatpp-<version>/<module-name> ## - lib/ ## | ## |- cmake/<module-name>-<version>/ ## | | ## | |- <module-name>Config.cmake ## | - <module-name>ConfigVersion.cmake ## | ## - oatpp-<version>/ ## | ## |- lib1.a ## |- lib2.a ## - ... ## ###################################################################################### message("\n############################################################################") message("## oatpp-module-install.cmake\n") message("OATPP_THIS_MODULE_NAME=${OATPP_THIS_MODULE_NAME}") message("OATPP_THIS_MODULE_VERSION=${OATPP_THIS_MODULE_VERSION}") message("OATPP_THIS_MODULE_LIBRARIES=${OATPP_THIS_MODULE_LIBRARIES}") message("OATPP_THIS_MODULE_TARGETS=${OATPP_THIS_MODULE_TARGETS}") message("OATPP_THIS_MODULE_DIRECTORIES=${OATPP_THIS_MODULE_DIRECTORIES}") message("\n############################################################################\n") ####################################################################################### ## Set cache variables to configure module-config.cmake.in template ## via call to configure_package_config_file include(GNUInstallDirs) set(OATPP_MODULE_NAME ${OATPP_THIS_MODULE_NAME} CACHE STRING "oatpp module name") set(OATPP_MODULE_VERSION "${OATPP_THIS_MODULE_VERSION}" CACHE STRING "oatpp module version") set(OATPP_MODULE_LIBRARIES "${OATPP_THIS_MODULE_LIBRARIES}" ## list libraries to find when find_package is called CACHE INTERNAL "oatpp module libraries" ) set(OATPP_MODULE_LIBDIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING "lib folder name") ####################################################################################### ## calc directories to install (relative to this script) ## dirs should be in ( relative ../src/<dirs>) foreach(CURR_DIR ${OATPP_THIS_MODULE_DIRECTORIES}) list(APPEND OATPP_DIRS_TO_INSTALL ${CMAKE_CURRENT_LIST_DIR}/../src/${CURR_DIR}) endforeach() ####################################################################################### install( TARGETS ${OATPP_THIS_MODULE_TARGETS} EXPORT "${OATPP_MODULE_NAME}Targets" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Devel LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Library RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}/oatpp-${OATPP_MODULE_VERSION}" COMPONENT Library INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/oatpp-${OATPP_MODULE_VERSION}/${OATPP_MODULE_NAME}" ) install(DIRECTORY ${OATPP_DIRS_TO_INSTALL} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/oatpp-${OATPP_MODULE_VERSION}/${OATPP_MODULE_NAME}" COMPONENT Devel FILES_MATCHING PATTERN "*.hpp" ) install(EXPORT "${OATPP_MODULE_NAME}Targets" FILE "${OATPP_MODULE_NAME}Targets.cmake" NAMESPACE oatpp:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" COMPONENT Devel ) include(CMakePackageConfigHelpers) write_basic_package_version_file("${OATPP_MODULE_NAME}ConfigVersion.cmake" VERSION ${OATPP_MODULE_VERSION} COMPATIBILITY ExactVersion ## Use exact version matching. ) ## Take module-config.cmake.in file in this direcory as a template configure_package_config_file( "${CMAKE_CURRENT_LIST_DIR}/module-config.cmake.in" "${OATPP_MODULE_NAME}Config.cmake" INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" PATH_VARS OATPP_MODULE_NAME OATPP_MODULE_VERSION OATPP_MODULE_LIBRARIES OATPP_MODULE_LIBDIR NO_CHECK_REQUIRED_COMPONENTS_MACRO ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${OATPP_MODULE_NAME}Config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/${OATPP_MODULE_NAME}ConfigVersion.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${OATPP_MODULE_NAME}-${OATPP_MODULE_VERSION}" COMPONENT Devel )
vincent-in-black-sesame/oat
cmake/module-install.cmake
CMake
apache-2.0
4,366
macro(configure_msvc_runtime) if(MSVC) # Set compiler options. set(variables CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO) if(OATPP_MSVC_LINK_STATIC_RUNTIME) message(STATUS "MSVC: using statically-linked runtime (/MT and /MTd).") foreach(variable ${variables}) if(${variable} MATCHES "/MD") string(REGEX REPLACE "/MD" "/MT" ${variable} "${${variable}}") endif() endforeach() else() message(STATUS "MSVC: using dynamically-linked runtime (/MD and /MDd).") foreach(variable ${variables}) if(${variable} MATCHES "/MT") string(REGEX REPLACE "/MT" "/MD" ${variable} "${${variable}}") endif() endforeach() endif() foreach(variable ${variables}) set(${variable} "${${variable}}" CACHE STRING "MSVC_${variable}" FORCE) endforeach() endif() endmacro(configure_msvc_runtime)
vincent-in-black-sesame/oat
cmake/msvc-runtime.cmake
CMake
apache-2.0
1,079
# # Packaging # https://cmake.org/cmake/help/latest/module/CPack.html # set( CPACK_PACKAGE_NAME ${PROJECT_NAME} ) set( CPACK_PACKAGE_VENDOR "Balluff" ) set( CPACK_PACKAGE_DESCRIPTION_SUMMARY "oatpp - Light and powerful C++ web framework" ) set( CPACK_PACKAGE_HOMEPAGE_URL "https://github.com/oatpp/oatpp" ) set( CPACK_PACKAGE_CONTACT "https://github.com/oatpp/oatpp" ) set( CPACK_PACKAGE_VERSION ${OATPP_THIS_MODULE_VERSION} ) set( CPACK_PACKAGE_INSTALL_DIRECTORY ${PROJECT_NAME} ) get_filename_component( oatpp_root_dir ${CMAKE_CURRENT_SOURCE_DIR} DIRECTORY ) set( CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" ) set( CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md" ) set( CPACK_COMPONENT_Library_DISPLAY_NAME "oatpp Library" ) set( CPACK_COMPONENT_Library_DESCRIPTION "The oatpp binary library." ) set( CPACK_COMPONENT_Library_REQUIRED 1 ) set( CPACK_COMPONENT_Devel_DISPLAY_NAME "oatpp Development Files" ) set( CPACK_COMPONENT_Devel_DESCRIPTION "Development files for compiling against oatpp." ) set( CPACK_COMPONENT_Devel_REQUIRED 0 ) if( ${CMAKE_SYSTEM_NAME} STREQUAL "Linux" ) if ( "${CPACK_PACKAGE_ARCHITECTURE}" STREQUAL "" ) # Note: the architecture should default to the local architecture, but it # in fact comes up empty. We call `uname -m` to ask the kernel instead. EXECUTE_PROCESS( COMMAND uname -m COMMAND tr -d '\n' OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE ) endif() set( CPACK_INCLUDE_TOPLEVEL_DIRECTORY 1 ) set( CPACK_PACKAGE_RELEASE 1 ) # RPM - https://cmake.org/cmake/help/latest/cpack_gen/rpm.html set( CPACK_RPM_PACKAGE_RELEASE ${CPACK_PACKAGE_RELEASE} ) set( CPACK_RPM_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) set( CPACK_RPM_PACKAGE_DESCRIPTION ${CPACK_PACKAGE_DESCRIPTION_SUMMARY} ) set( CPACK_RPM_PACKAGE_URL ${CPACK_PACKAGE_HOMEPAGE_URL} ) set( CPACK_RPM_PACKAGE_LICENSE "APACHE-2" ) set( CPACK_RPM_COMPONENT_INSTALL 1 ) set( CPACK_RPM_MAIN_COMPONENT "Library" ) set( CPACK_RPM_COMPRESSION_TYPE "xz" ) set( CPACK_RPM_PACKAGE_AUTOPROV 1 ) set( CPACK_RPM_PACKAGE_NAME "${CPACK_PACKAGE_NAME}" ) set( CPACK_RPM_FILE_NAME "RPM-DEFAULT" ) set( CPACK_RPM_Library_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) set( CPACK_RPM_Library_PACKAGE_NAME ${CPACK_PACKAGE_NAME} ) set( CPACK_RPM_Library_FILE_NAME "${CPACK_RPM_Library_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}.${CPACK_RPM_Library_PACKAGE_ARCHITECTURE}.rpm" ) set( CPACK_RPM_Library_PACKAGE_SUMMARY ${CPACK_COMPONENT_Library_DESCRIPTION} ) set( CPACK_RPM_Devel_PACKAGE_REQUIRES "cmake >= ${CMAKE_MINIMUM_REQUIRED_VERSION},oatpp >= ${CPACK_PACKAGE_VERSION}" ) set( CPACK_RPM_Devel_PACKAGE_SUMMARY ${CPACK_COMPONENT_Devel_DESCRIPTION} ) set( CPACK_RPM_Devel_PACKAGE_ARCHITECTURE "noarch" ) # only contains headers and cmake files set( CPACK_RPM_Devel_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-devel" ) set( CPACK_RPM_Devel_FILE_NAME "${CPACK_RPM_Devel_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}.${CPACK_RPM_Devel_PACKAGE_ARCHITECTURE}.rpm" ) # DEB - https://cmake.org/cmake/help/latest/cpack_gen/deb.html set( CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-dev" ) set( CPACK_DEBIAN_PACKAGE_RELEASE ${CPACK_PACKAGE_RELEASE} ) set( CPACK_DEBIAN_PACKAGE_HOMEPAGE ${CPACK_PACKAGE_HOMEPAGE_URL} ) set( CPACK_DEB_COMPONENT_INSTALL 1 ) set( CPACK_DEBIAN_COMPRESSION_TYPE "xz") if ( ${CPACK_PACKAGE_ARCHITECTURE} STREQUAL "x86_64" ) set( CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64" ) # DEB doesn't always use the kernel's arch name else() set( CPACK_DEBIAN_PACKAGE_ARCHITECTURE ${CPACK_PACKAGE_ARCHITECTURE} ) endif() set( CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT" ) # Use default naming scheme set( CPACK_DEBIAN_LIBRARY_PACKAGE_NAME ${CPACK_PACKAGE_NAME} ) set( CPACK_DEBIAN_LIBRARY_PACKAGE_SHLIBDEPS 1 ) set( CPACK_DEBIAN_DEVEL_PACKAGE_DEPENDS "cmake (>= ${CMAKE_MINIMUM_REQUIRED_VERSION}), oatpp (>= ${CPACK_PACKAGE_VERSION})" ) set( CPACK_DEBIAN_DEVEL_PACKAGE_NAME "${CPACK_PACKAGE_NAME}-dev" ) elseif( ${CMAKE_HOST_WIN32} ) set( CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON ) set( CPACK_NSIS_DISPLAY_NAME ${PROJECT_NAME} ) set( CPACK_NSIS_PACKAGE_NAME ${PROJECT_NAME} ) set( CPACK_NSIS_URL_INFO_ABOUT ${CPACK_PACKAGE_HOMEPAGE_URL} ) endif()
vincent-in-black-sesame/oat
cpack.cmake
CMake
apache-2.0
4,474
#include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" typedef oatpp::parser::Caret ParsingCaret; typedef oatpp::parser::json::mapping::Serializer Serializer; typedef oatpp::parser::json::mapping::Deserializer Deserializer; #include OATPP_CODEGEN_BEGIN(DTO) class EmptyDto : public oatpp::DTO { DTO_INIT(EmptyDto, DTO) }; class Test1 : public oatpp::DTO { DTO_INIT(Test1, DTO) DTO_FIELD(String, strF); }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { oatpp::String input(reinterpret_cast<const char*>(data), size); oatpp::parser::json::mapping::ObjectMapper mapper; try { mapper.readFromString<oatpp::Object<Test1>>(input); } catch(...) {} return 0; }
vincent-in-black-sesame/oat
fuzzers/oatpp/parser/json/mapping/ObjectMapper.cpp
C++
apache-2.0
745
####################################################################################################### ## oatpp add_library(oatpp oatpp/algorithm/CRC.cpp oatpp/algorithm/CRC.hpp oatpp/codegen/ApiClient_define.hpp oatpp/codegen/ApiClient_undef.hpp oatpp/codegen/api_controller/base_define.hpp oatpp/codegen/api_controller/base_undef.hpp oatpp/codegen/api_controller/auth_define.hpp oatpp/codegen/api_controller/auth_undef.hpp oatpp/codegen/api_controller/bundle_define.hpp oatpp/codegen/api_controller/bundle_undef.hpp oatpp/codegen/api_controller/cors_define.hpp oatpp/codegen/api_controller/cors_undef.hpp oatpp/codegen/ApiController_define.hpp oatpp/codegen/ApiController_undef.hpp oatpp/codegen/DbClient_define.hpp oatpp/codegen/DbClient_undef.hpp oatpp/codegen/dto/base_define.hpp oatpp/codegen/dto/base_undef.hpp oatpp/codegen/dto/enum_define.hpp oatpp/codegen/dto/enum_undef.hpp oatpp/codegen/DTO_define.hpp oatpp/codegen/DTO_undef.hpp oatpp/core/Types.hpp oatpp/core/async/utils/FastQueue.hpp oatpp/core/async/Coroutine.cpp oatpp/core/async/Coroutine.hpp oatpp/core/async/CoroutineWaitList.cpp oatpp/core/async/CoroutineWaitList.hpp oatpp/core/async/Error.cpp oatpp/core/async/Error.hpp oatpp/core/async/Executor.cpp oatpp/core/async/Executor.hpp oatpp/core/async/Lock.cpp oatpp/core/async/Lock.hpp oatpp/core/async/Processor.cpp oatpp/core/async/Processor.hpp oatpp/core/async/worker/Worker.cpp oatpp/core/async/worker/Worker.hpp oatpp/core/async/worker/IOEventWorker_common.cpp oatpp/core/async/worker/IOEventWorker_kqueue.cpp oatpp/core/async/worker/IOEventWorker_epoll.cpp oatpp/core/async/worker/IOEventWorker_stub.cpp oatpp/core/async/worker/IOEventWorker.hpp oatpp/core/async/worker/IOWorker.cpp oatpp/core/async/worker/IOWorker.hpp oatpp/core/async/worker/TimerWorker.cpp oatpp/core/async/worker/TimerWorker.hpp oatpp/core/base/CommandLineArguments.cpp oatpp/core/base/CommandLineArguments.hpp oatpp/core/base/Config.hpp oatpp/core/base/Countable.cpp oatpp/core/base/Countable.hpp oatpp/core/base/Environment.cpp oatpp/core/base/Environment.hpp oatpp/core/base/ObjectHandle.hpp oatpp/core/concurrency/SpinLock.cpp oatpp/core/concurrency/SpinLock.hpp oatpp/core/concurrency/Thread.cpp oatpp/core/concurrency/Thread.hpp oatpp/core/IODefinitions.cpp oatpp/core/IODefinitions.hpp oatpp/core/data/buffer/FIFOBuffer.cpp oatpp/core/data/buffer/FIFOBuffer.hpp oatpp/core/data/buffer/IOBuffer.cpp oatpp/core/data/buffer/IOBuffer.hpp oatpp/core/data/buffer/Processor.cpp oatpp/core/data/buffer/Processor.hpp oatpp/core/data/mapping/ObjectMapper.cpp oatpp/core/data/mapping/ObjectMapper.hpp oatpp/core/data/mapping/TypeResolver.cpp oatpp/core/data/mapping/TypeResolver.hpp oatpp/core/data/mapping/type/Any.cpp oatpp/core/data/mapping/type/Any.hpp oatpp/core/data/mapping/type/Collection.hpp oatpp/core/data/mapping/type/Enum.cpp oatpp/core/data/mapping/type/Enum.hpp oatpp/core/data/mapping/type/List.cpp oatpp/core/data/mapping/type/List.hpp oatpp/core/data/mapping/type/Map.hpp oatpp/core/data/mapping/type/PairList.cpp oatpp/core/data/mapping/type/PairList.hpp oatpp/core/data/mapping/type/Object.cpp oatpp/core/data/mapping/type/Object.hpp oatpp/core/data/mapping/type/Primitive.cpp oatpp/core/data/mapping/type/Primitive.hpp oatpp/core/data/mapping/type/Type.cpp oatpp/core/data/mapping/type/Type.hpp oatpp/core/data/mapping/type/UnorderedMap.cpp oatpp/core/data/mapping/type/UnorderedMap.hpp oatpp/core/data/mapping/type/UnorderedSet.cpp oatpp/core/data/mapping/type/UnorderedSet.hpp oatpp/core/data/mapping/type/Vector.cpp oatpp/core/data/mapping/type/Vector.hpp oatpp/core/data/resource/File.cpp oatpp/core/data/resource/File.hpp oatpp/core/data/resource/InMemoryData.cpp oatpp/core/data/resource/InMemoryData.hpp oatpp/core/data/resource/Resource.hpp oatpp/core/data/resource/TemporaryFile.cpp oatpp/core/data/resource/TemporaryFile.hpp oatpp/core/data/share/LazyStringMap.hpp oatpp/core/data/share/MemoryLabel.cpp oatpp/core/data/share/MemoryLabel.hpp oatpp/core/data/share/StringTemplate.cpp oatpp/core/data/share/StringTemplate.hpp oatpp/core/data/stream/BufferStream.cpp oatpp/core/data/stream/BufferStream.hpp oatpp/core/data/stream/FIFOStream.cpp oatpp/core/data/stream/FIFOStream.hpp oatpp/core/data/stream/FileStream.cpp oatpp/core/data/stream/FileStream.hpp oatpp/core/data/stream/Stream.cpp oatpp/core/data/stream/Stream.hpp oatpp/core/data/stream/StreamBufferedProxy.cpp oatpp/core/data/stream/StreamBufferedProxy.hpp oatpp/core/data/Bundle.cpp oatpp/core/data/Bundle.hpp oatpp/core/macro/basic.hpp oatpp/core/macro/codegen.hpp oatpp/core/macro/component.hpp oatpp/core/parser/Caret.cpp oatpp/core/parser/Caret.hpp oatpp/core/parser/ParsingError.cpp oatpp/core/parser/ParsingError.hpp oatpp/core/provider/Invalidator.hpp oatpp/core/provider/Pool.hpp oatpp/core/provider/Provider.hpp oatpp/core/utils/Binary.cpp oatpp/core/utils/Binary.hpp oatpp/core/utils/ConversionUtils.cpp oatpp/core/utils/ConversionUtils.hpp oatpp/core/utils/Random.cpp oatpp/core/utils/Random.hpp oatpp/core/utils/String.cpp oatpp/core/utils/String.hpp oatpp/encoding/Base64.cpp oatpp/encoding/Base64.hpp oatpp/encoding/Hex.cpp oatpp/encoding/Hex.hpp oatpp/encoding/Unicode.cpp oatpp/encoding/Unicode.hpp oatpp/network/monitor/ConnectionInactivityChecker.cpp oatpp/network/monitor/ConnectionInactivityChecker.hpp oatpp/network/monitor/ConnectionMaxAgeChecker.cpp oatpp/network/monitor/ConnectionMaxAgeChecker.hpp oatpp/network/monitor/ConnectionMonitor.cpp oatpp/network/monitor/ConnectionMonitor.hpp oatpp/network/monitor/MetricsChecker.hpp oatpp/network/monitor/StatCollector.hpp oatpp/network/tcp/client/ConnectionProvider.cpp oatpp/network/tcp/client/ConnectionProvider.hpp oatpp/network/tcp/server/ConnectionProvider.cpp oatpp/network/tcp/server/ConnectionProvider.hpp oatpp/network/tcp/Connection.cpp oatpp/network/tcp/Connection.hpp oatpp/network/virtual_/Interface.cpp oatpp/network/virtual_/Interface.hpp oatpp/network/virtual_/Pipe.cpp oatpp/network/virtual_/Pipe.hpp oatpp/network/virtual_/Socket.cpp oatpp/network/virtual_/Socket.hpp oatpp/network/virtual_/client/ConnectionProvider.cpp oatpp/network/virtual_/client/ConnectionProvider.hpp oatpp/network/virtual_/server/ConnectionProvider.cpp oatpp/network/virtual_/server/ConnectionProvider.hpp oatpp/network/Address.cpp oatpp/network/Address.hpp oatpp/network/ConnectionHandler.hpp oatpp/network/ConnectionPool.cpp oatpp/network/ConnectionPool.hpp oatpp/network/ConnectionProvider.cpp oatpp/network/ConnectionProvider.hpp oatpp/network/ConnectionProviderSwitch.cpp oatpp/network/ConnectionProviderSwitch.hpp oatpp/network/Server.cpp oatpp/network/Server.hpp oatpp/network/Url.cpp oatpp/network/Url.hpp oatpp/orm/Connection.hpp oatpp/orm/DbClient.cpp oatpp/orm/DbClient.hpp oatpp/orm/Executor.cpp oatpp/orm/Executor.hpp oatpp/orm/QueryResult.cpp oatpp/orm/QueryResult.hpp oatpp/orm/SchemaMigration.cpp oatpp/orm/SchemaMigration.hpp oatpp/orm/Transaction.cpp oatpp/orm/Transaction.hpp oatpp/parser/json/Beautifier.cpp oatpp/parser/json/Beautifier.hpp oatpp/parser/json/Utils.cpp oatpp/parser/json/Utils.hpp oatpp/parser/json/mapping/Deserializer.cpp oatpp/parser/json/mapping/Deserializer.hpp oatpp/parser/json/mapping/ObjectMapper.cpp oatpp/parser/json/mapping/ObjectMapper.hpp oatpp/parser/json/mapping/Serializer.cpp oatpp/parser/json/mapping/Serializer.hpp oatpp/web/client/ApiClient.cpp oatpp/web/client/ApiClient.hpp oatpp/web/client/HttpRequestExecutor.cpp oatpp/web/client/HttpRequestExecutor.hpp oatpp/web/client/RequestExecutor.cpp oatpp/web/client/RequestExecutor.hpp oatpp/web/client/RetryPolicy.cpp oatpp/web/client/RetryPolicy.hpp oatpp/web/mime/multipart/FileProvider.cpp oatpp/web/mime/multipart/FileProvider.hpp oatpp/web/mime/multipart/InMemoryDataProvider.cpp oatpp/web/mime/multipart/InMemoryDataProvider.hpp oatpp/web/mime/multipart/Multipart.cpp oatpp/web/mime/multipart/Multipart.hpp oatpp/web/mime/multipart/Part.cpp oatpp/web/mime/multipart/Part.hpp oatpp/web/mime/multipart/PartList.cpp oatpp/web/mime/multipart/PartList.hpp oatpp/web/mime/multipart/PartReader.cpp oatpp/web/mime/multipart/PartReader.hpp oatpp/web/mime/multipart/Reader.cpp oatpp/web/mime/multipart/Reader.hpp oatpp/web/mime/multipart/StatefulParser.cpp oatpp/web/mime/multipart/StatefulParser.hpp oatpp/web/mime/multipart/TemporaryFileProvider.cpp oatpp/web/mime/multipart/TemporaryFileProvider.hpp oatpp/web/protocol/CommunicationError.cpp oatpp/web/protocol/CommunicationError.hpp oatpp/web/protocol/http/Http.cpp oatpp/web/protocol/http/Http.hpp oatpp/web/protocol/http/incoming/BodyDecoder.cpp oatpp/web/protocol/http/incoming/BodyDecoder.hpp oatpp/web/protocol/http/incoming/Request.cpp oatpp/web/protocol/http/incoming/Request.hpp oatpp/web/protocol/http/incoming/RequestHeadersReader.cpp oatpp/web/protocol/http/incoming/RequestHeadersReader.hpp oatpp/web/protocol/http/incoming/Response.cpp oatpp/web/protocol/http/incoming/Response.hpp oatpp/web/protocol/http/incoming/ResponseHeadersReader.cpp oatpp/web/protocol/http/incoming/ResponseHeadersReader.hpp oatpp/web/protocol/http/incoming/SimpleBodyDecoder.cpp oatpp/web/protocol/http/incoming/SimpleBodyDecoder.hpp oatpp/web/protocol/http/outgoing/Body.cpp oatpp/web/protocol/http/outgoing/Body.hpp oatpp/web/protocol/http/outgoing/BufferBody.cpp oatpp/web/protocol/http/outgoing/BufferBody.hpp oatpp/web/protocol/http/outgoing/MultipartBody.cpp oatpp/web/protocol/http/outgoing/MultipartBody.hpp oatpp/web/protocol/http/outgoing/StreamingBody.cpp oatpp/web/protocol/http/outgoing/StreamingBody.hpp oatpp/web/protocol/http/outgoing/Request.cpp oatpp/web/protocol/http/outgoing/Request.hpp oatpp/web/protocol/http/outgoing/Response.cpp oatpp/web/protocol/http/outgoing/Response.hpp oatpp/web/protocol/http/outgoing/ResponseFactory.cpp oatpp/web/protocol/http/outgoing/ResponseFactory.hpp oatpp/web/protocol/http/encoding/Chunked.cpp oatpp/web/protocol/http/encoding/Chunked.hpp oatpp/web/protocol/http/encoding/ProviderCollection.cpp oatpp/web/protocol/http/encoding/ProviderCollection.hpp oatpp/web/protocol/http/encoding/EncoderProvider.hpp oatpp/web/protocol/http/utils/CommunicationUtils.cpp oatpp/web/protocol/http/utils/CommunicationUtils.hpp oatpp/web/server/AsyncHttpConnectionHandler.cpp oatpp/web/server/AsyncHttpConnectionHandler.hpp oatpp/web/server/HttpConnectionHandler.cpp oatpp/web/server/HttpConnectionHandler.hpp oatpp/web/server/HttpProcessor.cpp oatpp/web/server/HttpProcessor.hpp oatpp/web/server/HttpRequestHandler.hpp oatpp/web/server/HttpRouter.cpp oatpp/web/server/HttpRouter.hpp oatpp/web/server/api/ApiController.cpp oatpp/web/server/api/ApiController.hpp oatpp/web/server/api/Endpoint.cpp oatpp/web/server/api/Endpoint.hpp oatpp/web/server/handler/AuthorizationHandler.cpp oatpp/web/server/handler/AuthorizationHandler.hpp oatpp/web/server/handler/ErrorHandler.cpp oatpp/web/server/handler/ErrorHandler.hpp oatpp/web/server/interceptor/AllowCorsGlobal.cpp oatpp/web/server/interceptor/AllowCorsGlobal.hpp oatpp/web/server/interceptor/RequestInterceptor.hpp oatpp/web/server/interceptor/ResponseInterceptor.hpp oatpp/web/url/mapping/Pattern.cpp oatpp/web/url/mapping/Pattern.hpp oatpp/web/url/mapping/Router.hpp ) set_target_properties(oatpp PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) if (MSVC) target_compile_options(oatpp PRIVATE /permissive-) endif() set(CMAKE_THREAD_PREFER_PTHREAD ON) find_package(Threads REQUIRED) ####################################################################################################### ## Link external libraries SET(OATPP_ADD_LINK_LIBS "") if(MSVC OR MINGW) SET(OATPP_ADD_LINK_LIBS wsock32 ws2_32) elseif(NOT APPLE AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") if(OATPP_LINK_ATOMIC) SET(OATPP_ADD_LINK_LIBS atomic) endif() endif() message("OATPP_ADD_LINK_LIBS=${OATPP_ADD_LINK_LIBS}") target_link_libraries(oatpp PUBLIC ${CMAKE_THREAD_LIBS_INIT} ${OATPP_ADD_LINK_LIBS} ) target_include_directories(oatpp PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> ) ####################################################################################################### ## oatpp-test if(OATPP_LINK_TEST_LIBRARY) add_library(oatpp-test oatpp-test/Checker.cpp oatpp-test/Checker.hpp oatpp-test/UnitTest.cpp oatpp-test/UnitTest.hpp oatpp-test/web/ClientServerTestRunner.hpp ) set_target_properties(oatpp-test PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) if (MSVC) target_compile_options(oatpp-test PRIVATE /permissive-) endif() target_link_libraries(oatpp-test PUBLIC oatpp) target_include_directories(oatpp-test PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> ) add_dependencies(oatpp-test oatpp) endif() ####################################################################################################### ## Install targets if(OATPP_INSTALL) include("../cmake/module-install.cmake") endif()
vincent-in-black-sesame/oat
src/CMakeLists.txt
CMake
apache-2.0
15,263
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Checker.hpp" namespace oatpp { namespace test { PerformanceChecker::PerformanceChecker(const char* tag) : m_tag(tag) , m_ticks(oatpp::base::Environment::getMicroTickCount()) {} PerformanceChecker::~PerformanceChecker(){ v_int64 elapsedTicks = oatpp::base::Environment::getMicroTickCount() - m_ticks; OATPP_LOGD(m_tag, "%d(micro)", elapsedTicks); } v_int64 PerformanceChecker::getElapsedTicks(){ return oatpp::base::Environment::getMicroTickCount() - m_ticks; } ThreadLocalObjectsChecker::ThreadLocalObjectsChecker(const char* tag) : m_tag(tag) , m_objectsCount(oatpp::base::Environment::getThreadLocalObjectsCount()) , m_objectsCreated(oatpp::base::Environment::getThreadLocalObjectsCreated()) { } ThreadLocalObjectsChecker::~ThreadLocalObjectsChecker(){ v_counter leakingObjects = base::Environment::getThreadLocalObjectsCount() - m_objectsCount; v_counter objectsCreatedPerTest = base::Environment::getThreadLocalObjectsCreated() - m_objectsCreated; if(leakingObjects == 0){ OATPP_LOGE(m_tag, "OK:\n created(obj): %d", objectsCreatedPerTest); }else{ OATPP_LOGE(m_tag, "FAILED, leakingObjects = %d", leakingObjects); OATPP_ASSERT(false); } } }}
vincent-in-black-sesame/oat
src/oatpp-test/Checker.cpp
C++
apache-2.0
2,209
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_Checker_hpp #define oatpp_test_Checker_hpp #include "oatpp/core/base/Environment.hpp" namespace oatpp { namespace test { /** * Helper class to check performance of code block. */ class PerformanceChecker { private: const char* m_tag; v_int64 m_ticks; public: /** * Constructor. * @param tag - log tag. */ PerformanceChecker(const char* tag); /** * Non virtual destructor. * Will print time elapsed ticks on destruction. */ ~PerformanceChecker(); /** * Get elapsed time from checker creation. * @return - ticks in microseconds. */ v_int64 getElapsedTicks(); }; /** * Helper class to check block of code on memory leaks. * Checks &id:oatpp::base::Countable; objects, and objects allocated on memory pools. */ class ThreadLocalObjectsChecker { private: class MemoryPoolData { public: const char* name; v_int64 size; v_int64 objectsCount; }; private: const char* m_tag; v_counter m_objectsCount; v_counter m_objectsCreated; public: /** * Constructor. * @param tag - log tag. */ ThreadLocalObjectsChecker(const char* tag); /** * Non virtual destructor. * Will halt program execution if memory leaks detected. */ ~ThreadLocalObjectsChecker(); }; }} #endif /* Checker_hpp */
vincent-in-black-sesame/oat
src/oatpp-test/Checker.hpp
C++
apache-2.0
2,299
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnitTest.hpp" #include <chrono> namespace oatpp { namespace test { void UnitTest::run(v_int32 times) { OATPP_LOGI(TAG, "\033[1mSTART\033[0m..."); v_counter objectsCount = base::Environment::getObjectsCount(); v_counter objectsCreated = base::Environment::getObjectsCreated(); before(); v_int64 ticks = base::Environment::getMicroTickCount(); for(v_int32 i = 0; i < times; i++){ onRun(); } v_int64 millis = base::Environment::getMicroTickCount() - ticks; after(); v_counter leakingObjects = base::Environment::getObjectsCount() - objectsCount; v_counter objectsCreatedPerTest = base::Environment::getObjectsCreated() - objectsCreated; if(leakingObjects == 0){ OATPP_LOGI(TAG, "\033[1mFINISHED\033[0m - \033[1;32msuccess!\033[0m"); OATPP_LOGI(TAG, "\033[33m%d(micro), %d(objs)\033[0m\n", millis, objectsCreatedPerTest); }else{ OATPP_LOGE(TAG, "\033[1mFINISHED\033[0m - \033[1;31mfailed\033[0m, leakingObjects = %d", leakingObjects); exit(EXIT_FAILURE); } } }}
vincent-in-black-sesame/oat
src/oatpp-test/UnitTest.cpp
C++
apache-2.0
2,045
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_UnitTest_hpp #define oatpp_test_UnitTest_hpp #include <functional> #include "oatpp/core/base/Environment.hpp" #include "oatpp/core/macro/basic.hpp" namespace oatpp { namespace test { /** * Base class for unit tests. */ class UnitTest{ protected: const char* const TAG; public: /** * Constructor. * @param testTAG - tag used for logs. */ UnitTest(const char* testTAG) : TAG(testTAG) {} /** * Default virtual destructor. */ virtual ~UnitTest() = default; /** * Run this test repeatedly for specified number of times. * @param times - number of times to run this test. */ void run(v_int32 times); /** * Run this test. */ void run(){ run(1); } /** * Override this method. It should contain test logic. */ virtual void onRun() = 0; /** * Optionally override this method. It should contain logic run before all test iterations. */ virtual void before(){}; /** * Optionally override this method. It should contain logic run after all test iterations. */ virtual void after(){}; /** * Run this test repeatedly for specified number of times. * @tparam T - Test class. * @param times - number of times to run this test. */ template<class T> static void runTest(v_int32 times){ T test; test.run(times); } }; #define OATPP_RUN_TEST_0(TEST) \ oatpp::test::UnitTest::runTest<TEST>(1) #define OATPP_RUN_TEST_1(TEST, N) \ oatpp::test::UnitTest::runTest<TEST>(N) /** * Convenience macro to run test. <br> * Usage Example:<br> * `OATPP_RUN_TEST(oatpp::test::web::FullTest);` * Running the test 10 times: * `OATPP_RUN_TEST(oatpp::test::web::FullTest, 10);` */ #define OATPP_RUN_TEST(...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_RUN_TEST_, (__VA_ARGS__)) (__VA_ARGS__)) }} #endif /* oatpp_test_UnitTest_hpp */
vincent-in-black-sesame/oat
src/oatpp-test/UnitTest.hpp
C++
apache-2.0
2,869
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_web_ClientServerTestRunner_hpp #define oatpp_test_web_ClientServerTestRunner_hpp #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/network/Server.hpp" #include "oatpp/network/ConnectionProvider.hpp" #include "oatpp/core/macro/component.hpp" #include <list> #include <chrono> #include <mutex> #include <condition_variable> #include <thread> namespace oatpp { namespace test { namespace web { /** * Helper class to run Client-Server tests */ class ClientServerTestRunner { public: typedef oatpp::web::server::HttpRouter HttpRouter; typedef oatpp::web::server::api::ApiController ApiController; private: std::shared_ptr<oatpp::network::Server> m_server; std::list<std::shared_ptr<ApiController>> m_controllers; OATPP_COMPONENT(std::shared_ptr<HttpRouter>, m_router); OATPP_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, m_connectionProvider); OATPP_COMPONENT(std::shared_ptr<oatpp::network::ConnectionHandler>, m_connectionHandler); public: std::shared_ptr<HttpRouter> getRouter() { return m_router; } /** * Add controller's endpoints to router * @param controller */ void addController(const std::shared_ptr<ApiController>& controller) { m_router->route(controller->getEndpoints()); m_controllers.push_back(controller); } std::shared_ptr<oatpp::network::Server> getServer() { return m_server; } /** * Start server, execute code block passed as lambda, stop server. * @tparam Lambda * @param lambda * @param timeout */ template<typename Lambda> void run( const Lambda& lambda, const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::hours(12) ) { auto startTime = std::chrono::system_clock::now(); std::atomic<bool> running(true); std::mutex timeoutMutex; std::condition_variable timeoutCondition; bool runConditionForLambda = true; m_server = std::make_shared<oatpp::network::Server>(m_connectionProvider, m_connectionHandler); OATPP_LOGD("\033[1;34mClientServerTestRunner\033[0m", "\033[1;34mRunning server on port %s. Timeout %lld(micro)\033[0m", m_connectionProvider->getProperty("port").toString()->c_str(), timeout.count()); std::function<bool()> condition = [&runConditionForLambda](){ return runConditionForLambda; }; std::thread serverThread([&condition, this]{ m_server->run(condition); }); std::thread clientThread([&runConditionForLambda, this, &lambda]{ lambda(); // m_server->stop(); runConditionForLambda = false; m_connectionHandler->stop(); m_connectionProvider->stop(); }); std::thread timerThread([&timeout, &startTime, &running, &timeoutMutex, &timeoutCondition]{ std::unique_lock<std::mutex> lock(timeoutMutex); while(running) { timeoutCondition.wait_for(lock, std::chrono::seconds(1)); auto elapsed = std::chrono::system_clock::now() - startTime; OATPP_ASSERT("ClientServerTestRunner: Error. Timeout." && elapsed < timeout); } }); serverThread.join(); clientThread.join(); auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - startTime); OATPP_LOGD("\033[1;34mClientServerTestRunner\033[0m", "\033[1;34mFinished with time %lld(micro). Stopping server...\033[0m", elapsed.count()); running = false; timeoutCondition.notify_one(); timerThread.join(); } }; }}} #endif //oatpp_test_web_ClientServerTestRunner_hpp
vincent-in-black-sesame/oat
src/oatpp-test/web/ClientServerTestRunner.hpp
C++
apache-2.0
4,611
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CRC.hpp" namespace oatpp { namespace algorithm { const p_uint32 CRC32::TABLE_04C11DB7 = generateTable(0x04C11DB7); v_uint32 CRC32::bitReverse(v_uint32 poly) { v_uint32 result = 0; for(v_int32 i = 0; i < 32; i ++) { if((poly & (1 << i)) > 0) { result |= 1 << (31 - i); } } return result; } p_uint32 CRC32::generateTable(v_uint32 poly) { p_uint32 result = new v_uint32[256]; v_uint32 polyReverse = bitReverse(poly); v_uint32 value; for(v_int32 i = 0; i < 256; i++) { value = i; for (v_int32 bit = 0; bit < 8; bit++) { if (value & 1) { value = (value >> 1) ^ polyReverse; } else { value = (value >> 1); } } result[i] = value; } return result; } v_uint32 CRC32::calc(const void *buffer, v_buff_size size, v_uint32 crc, v_uint32 initValue, v_uint32 xorOut, p_uint32 table) { p_uint8 data = (p_uint8) buffer; crc = crc ^ initValue; for(v_buff_size i = 0; i < size; i++) { crc = table[(crc & 0xFF) ^ data[i]] ^ (crc >> 8); } return crc ^ xorOut; } }}
vincent-in-black-sesame/oat
src/oatpp/algorithm/CRC.cpp
C++
apache-2.0
2,095
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_algorithm_CRC_hpp #define oatpp_algorithm_CRC_hpp #include "oatpp/core/base/Environment.hpp" #include "oatpp/encoding/Hex.hpp" namespace oatpp { namespace algorithm { /** * Implementation of CRC-32. Cyclic redundancy check algorithm. */ class CRC32 { public: /** * Precalculated table */ static const p_uint32 TABLE_04C11DB7; public: static v_uint32 bitReverse(v_uint32 poly); /** * Generates v_uint32 table[256] for polynomial */ static p_uint32 generateTable(v_uint32 poly); /** * Calculate CRC32 value for buffer of defined size * @param buffer * @param size * @param crc * @param initValue * @param xorOut * @param table * @return - CRC32 value (v_uint32) */ static v_uint32 calc(const void *buffer, v_buff_size size, v_uint32 crc = 0, v_uint32 initValue = 0xFFFFFFFF, v_uint32 xorOut = 0xFFFFFFFF, p_uint32 table = TABLE_04C11DB7); }; }} #endif /* oatpp_algorithm_CRC_hpp */
vincent-in-black-sesame/oat
src/oatpp/algorithm/CRC.hpp
C++
apache-2.0
1,965
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for ApiClient code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiClient) * ... * // Generated API-Calls. * ... * #include OATPP_CODEGEN_END(ApiClient) * ``` * * * *For details see:* * <ul> * <li>[ApiClient component](https://oatpp.io/docs/components/api-client/)</li> * <li>&id:oatpp::web::client::ApiClient;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #define OATPP_MACRO_API_CLIENT_PARAM_MACRO(MACRO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CLIENT_PARAM_TYPE(MACRO, TYPE, PARAM_LIST) const TYPE& #define OATPP_MACRO_API_CLIENT_PARAM_NAME(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_API_CLIENT_PARAM_TYPE_STR(MACRO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_API_CLIENT_PARAM_NAME_STR(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_API_CLIENT_PARAM(MACRO, TYPE, PARAM_LIST) (MACRO, TYPE, PARAM_LIST) #define HEADER(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_HEADER, TYPE, (__VA_ARGS__)) #define PATH(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_PATH, TYPE, (__VA_ARGS__)) #define QUERY(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_QUERY, TYPE, (__VA_ARGS__)) #define BODY(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY, TYPE, (__VA_ARGS__)) #define BODY_DTO(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY_DTO, TYPE, (__VA_ARGS__)) #define BODY_STRING(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_BODY_STRING, TYPE, (__VA_ARGS__)) #define AUTHORIZATION(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_AUTHORIZATION, TYPE, (__VA_ARGS__)) #define AUTHORIZATION_BASIC(TYPE, ...) OATPP_MACRO_API_CLIENT_PARAM(OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC, TYPE, (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // INIT /** * Codegen macro to be used in classes extending &id:oatpp::web::client::ApiClient; to generate required fields/methods/constructors for ApiClient. * @param NAME - name of the ApiClient class. */ #define API_CLIENT_INIT(NAME) \ public: \ NAME(const std::shared_ptr<oatpp::web::client::RequestExecutor>& requestExecutor, \ const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper) \ : oatpp::web::client::ApiClient(requestExecutor, objectMapper) \ {} \ public: \ static std::shared_ptr<NAME> createShared(const std::shared_ptr<oatpp::web::client::RequestExecutor>& requestExecutor, \ const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper){ \ return std::make_shared<NAME>(requestExecutor, objectMapper); \ } // HEADER MACRO #define OATPP_MACRO_API_CLIENT_HEADER_1(TYPE, NAME) \ __headers.put_LockFree(#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)); #define OATPP_MACRO_API_CLIENT_HEADER_2(TYPE, NAME, QUALIFIER) \ __headers.put_LockFree(QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)); #define OATPP_MACRO_API_CLIENT_HEADER(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_HEADER_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PATH MACRO #define OATPP_MACRO_API_CLIENT_PATH_1(TYPE, NAME) \ __pathParams.insert({#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_PATH_2(TYPE, NAME, QUALIFIER) \ __pathParams.insert({QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_PATH(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_PATH_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // QUERY MACRO #define OATPP_MACRO_API_CLIENT_QUERY_1(TYPE, NAME) \ __queryParams.insert({#NAME, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_QUERY_2(TYPE, NAME, QUALIFIER) \ __queryParams.insert({QUALIFIER, ApiClient::TypeInterpretation<TYPE>::toString(#TYPE, NAME)}); #define OATPP_MACRO_API_CLIENT_QUERY(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_QUERY_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // BODY MACRO #define OATPP_MACRO_API_CLIENT_BODY(TYPE, PARAM_LIST) \ __body = OATPP_MACRO_FIRSTARG PARAM_LIST; // BODY_DTO MACRO #define OATPP_MACRO_API_CLIENT_BODY_DTO(TYPE, PARAM_LIST) \ __body = oatpp::web::protocol::http::outgoing::BufferBody::createShared( \ m_objectMapper->writeToString(OATPP_MACRO_FIRSTARG PARAM_LIST), \ m_objectMapper->getInfo().http_content_type \ ); // BODY_STRING MACRO #define OATPP_MACRO_API_CLIENT_BODY_STRING(TYPE, PARAM_LIST) \ __body = oatpp::web::protocol::http::outgoing::BufferBody::createShared(OATPP_MACRO_FIRSTARG PARAM_LIST); // AUTHORIZATION MACRO #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_2(TYPE, TOKEN, SCHEME) \ __headers.put_LockFree("Authorization", String(SCHEME " ") + String(TOKEN)); #define OATPP_MACRO_API_CLIENT_AUTHORIZATION(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_AUTHORIZATION_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // AUTHORIZATION_BASIC MACRO #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_1(TYPE, TOKEN) \ __headers.put_LockFree("Authorization", String("Basic ") + oatpp::encoding::Base64::encode(TOKEN)); #define OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CLIENT_MACRO_SELECTOR(OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // FOR EACH #define OATPP_MACRO_API_CLIENT_PARAM_DECL(INDEX, COUNT, X) \ OATPP_MACRO_API_CLIENT_PARAM_TYPE X OATPP_MACRO_API_CLIENT_PARAM_NAME X, #define OATPP_MACRO_API_CLIENT_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_API_CLIENT_PARAM_MACRO X // API_CALL MACRO #define OATPP_API_CALL_0(NAME, METHOD, PATH) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ std::shared_ptr<oatpp::web::protocol::http::incoming::Response> NAME( \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> body; \ return executeRequest(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ {}, \ {}, \ body, \ __connectionHandle); \ } #define OATPP_API_CALL_1(NAME, METHOD, PATH, ...) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ std::shared_ptr<oatpp::web::protocol::http::incoming::Response> NAME(\ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_DECL, __VA_ARGS__) \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::unordered_map<oatpp::String, oatpp::String> __pathParams; \ std::unordered_map<oatpp::String, oatpp::String> __queryParams; \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> __body; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_PUT, __VA_ARGS__) \ return executeRequest(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ __pathParams, \ __queryParams, \ __body, \ __connectionHandle); \ } // Chooser #define OATPP_API_CALL_MACRO_0(METHOD, PATH, NAME) \ OATPP_API_CALL_0(NAME, METHOD, PATH) #define OATPP_API_CALL_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_API_CALL_1(NAME, METHOD, PATH, __VA_ARGS__) /** * Codegen macro to be used in `oatpp::web::client::ApiClient` to generate REST API-Calls. * @param METHOD - Http method ("GET", "POST", "PUT", etc.) * @param PATH - Path to endpoint (without host) * @param NAME - Name of the generated method * @return - std::shared_ptr to &id:oatpp::web::protocol::http::incoming::Response; */ #define API_CALL(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_API_CALL_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) // API_CALL_ASYNC MACRO #define OATPP_API_CALL_ASYNC_0(NAME, METHOD, PATH) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::incoming::Response>&> NAME( \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> body; \ return executeRequestAsync(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ {}, \ {}, \ body, \ __connectionHandle); \ } #define OATPP_API_CALL_ASYNC_1(NAME, METHOD, PATH, ...) \ const oatpp::data::share::StringTemplate Z_PATH_TEMPLATE_##NAME = parsePathTemplate(#NAME, PATH); \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, ...) { \ (void) headers; \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::incoming::Response>&> NAME(\ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_DECL, __VA_ARGS__) \ const std::shared_ptr<oatpp::web::client::RequestExecutor::ConnectionHandle>& __connectionHandle = nullptr \ ) { \ oatpp::web::client::ApiClient::Headers __headers; \ Z_ADD_HEADERS_##NAME(__headers, 1); \ std::unordered_map<oatpp::String, oatpp::String> __pathParams; \ std::unordered_map<oatpp::String, oatpp::String> __queryParams; \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Body> __body; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CLIENT_PARAM_PUT, __VA_ARGS__) \ return executeRequestAsync(METHOD, \ Z_PATH_TEMPLATE_##NAME, \ __headers, \ __pathParams, \ __queryParams, \ __body, \ __connectionHandle); \ } #define OATPP_API_CALL_ASYNC_MACRO_0(METHOD, PATH, NAME) \ OATPP_API_CALL_ASYNC_0(NAME, METHOD, PATH) #define OATPP_API_CALL_ASYNC_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_API_CALL_ASYNC_1(NAME, METHOD, PATH, __VA_ARGS__) /** * Codegen macro to be used in `oatpp::web::client::ApiClient` to generate Asynchronous REST API-Calls. * @param METHOD - Http method ("GET", "POST", "PUT", etc.) * @param PATH - Path to endpoint (without host) * @param NAME - Name of the generated method * @return - &id:oatpp::async::CoroutineStarterForResult;<const std::shared_ptr<&id:oatpp::web::protocol::http::incoming::Response;>&>. */ #define API_CALL_ASYNC(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_API_CALL_ASYNC_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) /** * Codegen macro to add default headers to API_CALL */ #define API_CALL_HEADERS(NAME) \ \ static void Z_ADD_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers, int) { \ Z_ADD_HEADERS_##NAME(headers); /* call first method */ \ Z_ADD_DEFAULT_HEADERS_##NAME(headers); \ } \ \ static void Z_ADD_DEFAULT_HEADERS_##NAME(oatpp::web::client::ApiClient::Headers& headers)
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiClient_define.hpp
C++
apache-2.0
13,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for ApiClient code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiClient) * ... * // Generated API-Calls. * ... * #include OATPP_CODEGEN_END(ApiClient) * ``` * * * *For details see:* * <ul> * <li>[ApiClient component](https://oatpp.io/docs/components/api-client/)</li> * <li>&id:oatpp::web::client::ApiClient;</li> * </ul> */ #undef OATPP_MACRO_API_CLIENT_PARAM_MACRO #undef OATPP_MACRO_API_CLIENT_PARAM_TYPE #undef OATPP_MACRO_API_CLIENT_PARAM_NAME #undef OATPP_MACRO_API_CLIENT_PARAM_TYPE_STR #undef OATPP_MACRO_API_CLIENT_PARAM_NAME_STR #undef OATPP_MACRO_API_CLIENT_PARAM #undef HEADER #undef PATH #undef QUERY #undef BODY #undef BODY_DTO #undef BODY_STRING #undef AUTHORIZATION #undef AUTHORIZATION_BASIC // #undef OATPP_MACRO_API_CLIENT_MACRO_SELECTOR // INIT #undef API_CLIENT_INIT // HEADER MACRO #undef OATPP_MACRO_API_CLIENT_HEADER_1 #undef OATPP_MACRO_API_CLIENT_HEADER_2 #undef OATPP_MACRO_API_CLIENT_HEADER // PATH MACRO #undef OATPP_MACRO_API_CLIENT_PATH_1 #undef OATPP_MACRO_API_CLIENT_PATH_2 #undef OATPP_MACRO_API_CLIENT_PATH // QUERY MACRO #undef OATPP_MACRO_API_CLIENT_QUERY_1 #undef OATPP_MACRO_API_CLIENT_QUERY_2 #undef OATPP_MACRO_API_CLIENT_QUERY // BODY MACRO #undef OATPP_MACRO_API_CLIENT_BODY // BODY_DTO MACRO #undef OATPP_MACRO_API_CLIENT_BODY_DTO // BODY_STRING MACRO #undef OATPP_MACRO_API_CLIENT_BODY_STRING // AUTHORIZATION MACRO #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_2 #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION // AUTHORIZATION_BASIC MACRO #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC_1 #undef OATPP_MACRO_API_CLIENT_AUTHORIZATION_BASIC // FOR EACH #undef OATPP_MACRO_API_CLIENT_PARAM_DECL #undef OATPP_MACRO_API_CLIENT_PARAM_PUT // API_CALL MACRO #undef OATPP_API_CALL_0 #undef OATPP_API_CALL_1 #undef OATPP_API_CALL_MACRO_0 #undef OATPP_API_CALL_MACRO_1 #undef API_CALL // API_CALL_ASYNC MACRO #undef OATPP_API_CALL_ASYNC_0 #undef OATPP_API_CALL_ASYNC_1 #undef OATPP_API_CALL_ASYNC_MACRO_0 #undef OATPP_API_CALL_ASYNC_MACRO_1 #undef API_CALL_ASYNC #undef API_CALL_HEADERS
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiClient_undef.hpp
C++
apache-2.0
3,149
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for ApiController code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiController) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(ApiController) * ``` * * * *For details see:* * <ul> * <li>[ApiController component](https://oatpp.io/docs/components/api-controller/)</li> * <li>&id:oatpp::web::server::api::ApiController;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #include "./api_controller/base_define.hpp" #include "./api_controller/auth_define.hpp" #include "./api_controller/bundle_define.hpp" #include "./api_controller/cors_define.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiController_define.hpp
C++
apache-2.0
1,706
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for ApiController code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(ApiController) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(ApiController) * ``` * * * *For details see:* * <ul> * <li>[ApiController component](https://oatpp.io/docs/components/api-controller/)</li> * <li>&id:oatpp::web::server::api::ApiController;</li> * </ul> */ #include "./api_controller/base_undef.hpp" #include "./api_controller/auth_undef.hpp" #include "./api_controller/bundle_undef.hpp" #include "./api_controller/cors_undef.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/ApiController_undef.hpp
C++
apache-2.0
1,622
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "defines" for DTO code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(DTO) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(DTO) * ``` * * * *For details see:* * <ul> * <li>[Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/)</li> * <li>&id:oatpp::data::mapping::type::Object;</li> * </ul> */ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #include "./dto/base_define.hpp" #include "./dto/enum_define.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/DTO_define.hpp
C++
apache-2.0
1,561
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ /**[info] * This file contains "undefs" for DTO code generating macro. <br> * Usage:<br> * * ```cpp * #include OATPP_CODEGEN_BEGIN(DTO) * ... * // Generated Endpoints. * ... * #include OATPP_CODEGEN_END(DTO) * ``` * * * *For details see:* * <ul> * <li>[Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/)</li> * <li>&id:oatpp::data::mapping::type::Object;</li> * </ul> */ #include "./dto/base_undef.hpp" #include "./dto/enum_undef.hpp"
vincent-in-black-sesame/oat
src/oatpp/codegen/DTO_undef.hpp
C++
apache-2.0
1,479
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #define OATPP_MACRO_DB_CLIENT_PARAM_TYPE(MACRO, TYPE, PARAM_LIST) TYPE #define OATPP_MACRO_DB_CLIENT_PARAM_NAME(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_DB_CLIENT_PARAM_TYPE_STR(MACRO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_DB_CLIENT_PARAM_NAME_STR(MACRO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_DB_CLIENT_PARAM_MACRO(MACRO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PREPARE_MACRO(MACRO, VAL) MACRO(VAL) #define OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE(MACRO, TYPE, PARAM_LIST) MACRO ##_TYPE(TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PARAM(MACRO, TYPE, PARAM_LIST) (MACRO, TYPE, PARAM_LIST) #define OATPP_MACRO_DB_CLIENT_PREPARE(MACRO, VAL) (MACRO, VAL) #define PARAM(TYPE, ...) OATPP_MACRO_DB_CLIENT_PARAM(OATPP_MACRO_DB_CLIENT_PARAM_PARAM, TYPE, (__VA_ARGS__)) #define PREPARE(VAL) OATPP_MACRO_DB_CLIENT_PREPARE(OATPP_MACRO_DB_CLIENT_PARAM_PREPARE, VAL) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // PARAM MACRO USE-CASE #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_DECL(X) \ const OATPP_MACRO_DB_CLIENT_PARAM_TYPE X & OATPP_MACRO_DB_CLIENT_PARAM_NAME X, #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_TYPE(X) \ OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE X #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_BODY(X) \ OATPP_MACRO_DB_CLIENT_PARAM_MACRO X // PARAM MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_1(TYPE, NAME) \ __params.insert({#NAME, NAME}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_2(TYPE, NAME, QUALIFIER) \ __params.insert({QUALIFIER, NAME}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM(TYPE, PARAM_LIST) \ OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(OATPP_MACRO_DB_CLIENT_PARAM_PARAM_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PARAM_TYPE MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_1(TYPE, NAME) \ map.insert({#NAME, TYPE::Class::getType()}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_2(TYPE, NAME, QUALIFIER) \ map.insert({QUALIFIER, TYPE::Class::getType()}); #define OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE(TYPE, PARAM_LIST) \ OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR(OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PREPARE MACRO USE-CASE #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_DECL(X) #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_TYPE(X) \ OATPP_MACRO_DB_CLIENT_PREPARE_MACRO X #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_BODY(X) // PREPARE MACRO #define OATPP_MACRO_DB_CLIENT_PARAM_PREPARE(VAL) \ __prepare = VAL; // PARAMS USE-CASE #define OATPP_MACRO_PARAM_USECASE_DECL(MACRO, ...) MACRO ## _PUT_DECL((MACRO, __VA_ARGS__)) #define OATPP_MACRO_PARAM_USECASE_TYPE(MACRO, ...) MACRO ## _PUT_TYPE((MACRO, __VA_ARGS__)) #define OATPP_MACRO_PARAM_USECASE_BODY(MACRO, ...) MACRO ## _PUT_BODY((MACRO, __VA_ARGS__)) // FOR EACH #define OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_DECL X #define OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_TYPE X #define OATPP_MACRO_DB_CLIENT_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_PARAM_USECASE_BODY X // QUERY MACRO #define OATPP_QUERY_0(NAME, QUERY_TEXT) \ const oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_##NAME = \ this->parseQueryTemplate(#NAME, QUERY_TEXT, {}, false); \ \ std::shared_ptr<oatpp::orm::QueryResult> NAME(const oatpp::provider::ResourceHandle<oatpp::orm::Connection>& connection = nullptr) { \ std::unordered_map<oatpp::String, oatpp::Void> __params; \ return this->execute(Z_QUERY_TEMPLATE_##NAME, __params, connection); \ } #define OATPP_QUERY_1(NAME, QUERY_TEXT, ...) \ \ oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_CREATOR_##NAME() { \ bool __prepare = false; \ oatpp::orm::Executor::ParamsTypeMap map; \ \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE, __VA_ARGS__) \ \ return this->parseQueryTemplate(#NAME, QUERY_TEXT, map, __prepare); \ } \ \ const oatpp::data::share::StringTemplate Z_QUERY_TEMPLATE_##NAME = Z_QUERY_TEMPLATE_CREATOR_##NAME(); \ \ std::shared_ptr<oatpp::orm::QueryResult> NAME( \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL, __VA_ARGS__) \ const oatpp::provider::ResourceHandle<oatpp::orm::Connection>& connection = nullptr \ ) { \ std::unordered_map<oatpp::String, oatpp::Void> __params; \ OATPP_MACRO_FOREACH(OATPP_MACRO_DB_CLIENT_PARAM_PUT, __VA_ARGS__) \ return this->execute(Z_QUERY_TEMPLATE_##NAME, __params, connection); \ } // Chooser #define OATPP_QUERY_MACRO_0(NAME, QUERY_TEXT) \ OATPP_QUERY_0(NAME, QUERY_TEXT) #define OATPP_QUERY_MACRO_1(NAME, QUERY_TEXT, ...) \ OATPP_QUERY_1(NAME, QUERY_TEXT, __VA_ARGS__) #define QUERY(NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_QUERY_MACRO_, (__VA_ARGS__)) (NAME, __VA_ARGS__))
vincent-in-black-sesame/oat
src/oatpp/codegen/DbClient_define.hpp
C++
apache-2.0
6,164
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef OATPP_MACRO_DB_CLIENT_PARAM_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_NAME #undef OATPP_MACRO_DB_CLIENT_PARAM_TYPE_STR #undef OATPP_MACRO_DB_CLIENT_PARAM_NAME_STR #undef OATPP_MACRO_DB_CLIENT_PARAM_MACRO #undef OATPP_MACRO_DB_CLIENT_PREPARE_MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_MACRO_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM #undef OATPP_MACRO_DB_CLIENT_PREPARE #undef PARAM #undef PREPARE ////////////////////////////////////////////////////////////////////////// #undef OATPP_MACRO_DB_CLIENT_MACRO_SELECTOR ////////////////////////////////////////////////////////////////////////// // PARAM MACRO USE-CASE #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_PUT_BODY // PARAM MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_1 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_2 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM // PARAM_TYPE MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_1 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE_2 #undef OATPP_MACRO_DB_CLIENT_PARAM_PARAM_TYPE // PREPARE MACRO USE-CASE #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE_PUT_BODY // PREPARE MACRO #undef OATPP_MACRO_DB_CLIENT_PARAM_PREPARE // PARAMS USE-CASE #undef OATPP_MACRO_PARAM_USECASE_DECL #undef OATPP_MACRO_PARAM_USECASE_TYPE #undef OATPP_MACRO_PARAM_USECASE_BODY // FOR EACH #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT_DECL #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT_TYPE #undef OATPP_MACRO_DB_CLIENT_PARAM_PUT // QUERY MACRO #undef OATPP_QUERY_0 #undef OATPP_QUERY_1 // Chooser #undef OATPP_QUERY_MACRO_0 #undef OATPP_QUERY_MACRO_1 #undef QUERY
vincent-in-black-sesame/oat
src/oatpp/codegen/DbClient_undef.hpp
C++
apache-2.0
2,755
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define AUTHORIZATION(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION, OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO, TYPE, (__VA_ARGS__)) // AUTHORIZATION MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_1(TYPE, NAME) \ auto __param_str_val_##NAME = __request->getHeader(oatpp::web::protocol::http::Header::AUTHORIZATION); \ std::shared_ptr<oatpp::web::server::handler::AuthorizationObject> __param_aosp_val_##NAME = ApiController::handleDefaultAuthorization(__param_str_val_##NAME); \ TYPE NAME = std::static_pointer_cast<TYPE::element_type>(__param_aosp_val_##NAME); #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_2(TYPE, NAME, AUTH_HANDLER) \ auto __param_str_val_##NAME = __request->getHeader(oatpp::web::protocol::http::Header::AUTHORIZATION); \ std::shared_ptr<oatpp::web::server::handler::AuthorizationHandler> __auth_handler_##NAME = AUTH_HANDLER; \ std::shared_ptr<oatpp::web::server::handler::AuthorizationObject> __param_aosp_val_##NAME = __auth_handler_##NAME->handleAuthorization(__param_str_val_##NAME); \ TYPE NAME = std::static_pointer_cast<TYPE::element_type>(__param_aosp_val_##NAME); #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_1(TYPE, NAME) \ auto __param_obj_##NAME = ApiController::getDefaultAuthorizationHandler(); \ if(__param_obj_##NAME) { \ info->headers.add(oatpp::web::protocol::http::Header::AUTHORIZATION, oatpp::String::Class::getType()); \ info->headers[oatpp::web::protocol::http::Header::AUTHORIZATION].description = __param_obj_##NAME ->getScheme(); \ info->authorization = __param_obj_##NAME ->getScheme(); \ } else { \ throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "No authorization handler set up in controller before controller was added to router or swagger-doc."); \ } #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_2(TYPE, NAME, AUTH_HANDLER) \ std::shared_ptr<oatpp::web::server::handler::AuthorizationHandler> __auth_handler_##NAME = AUTH_HANDLER; \ if(__auth_handler_##NAME) { \ info->headers.add(oatpp::web::protocol::http::Header::AUTHORIZATION, oatpp::String::Class::getType()); \ info->headers[oatpp::web::protocol::http::Header::AUTHORIZATION].description = __auth_handler_##NAME->getScheme(); \ info->authorization = __auth_handler_##NAME->getScheme(); \ } else { \ throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "Invalid authorization handler given (or not set up) in AUTHORIZATION(TYPE, NAME, AUTH_HANDLER) before controller was added to router or swagger-doc."); \ } #define OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST)
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/auth_define.hpp
C++
apache-2.0
4,013
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef AUTHORIZATION // AUTHORIZATION MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_1 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_2 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION // __INFO #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_AUTHORIZATION_INFO
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/auth_undef.hpp
C++
apache-2.0
1,421
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define OATPP_MACRO_API_CONTROLLER_PARAM_MACRO(MACRO, INFO, TYPE, PARAM_LIST) MACRO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_PARAM_INFO(MACRO, INFO, TYPE, PARAM_LIST) INFO(TYPE, PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_PARAM_TYPE(MACRO, INFO, TYPE, PARAM_LIST) const TYPE& #define OATPP_MACRO_API_CONTROLLER_PARAM_NAME(MACRO, INFO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG PARAM_LIST #define OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR(MACRO, INFO, TYPE, PARAM_LIST) #TYPE #define OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR(MACRO, INFO, TYPE, PARAM_LIST) OATPP_MACRO_FIRSTARG_STR PARAM_LIST #define OATPP_MACRO_API_CONTROLLER_PARAM(MACRO, INFO, TYPE, PARAM_LIST) (MACRO, INFO, TYPE, PARAM_LIST) #define REQUEST(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_REQUEST, OATPP_MACRO_API_CONTROLLER_REQUEST_INFO, TYPE, (__VA_ARGS__)) #define HEADER(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_HEADER, OATPP_MACRO_API_CONTROLLER_HEADER_INFO, TYPE, (__VA_ARGS__)) #define PATH(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_PATH, OATPP_MACRO_API_CONTROLLER_PATH_INFO, TYPE, (__VA_ARGS__)) #define QUERIES(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_QUERIES, OATPP_MACRO_API_CONTROLLER_QUERIES_INFO, TYPE, (__VA_ARGS__)) #define QUERY(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_QUERY, OATPP_MACRO_API_CONTROLLER_QUERY_INFO, TYPE, (__VA_ARGS__)) #define BODY_STRING(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BODY_STRING, OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO, TYPE, (__VA_ARGS__)) #define BODY_DTO(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BODY_DTO, OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO, TYPE, (__VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// #define OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(MACRO, TYPE, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_SELECTOR(MACRO, (__VA_ARGS__)) (TYPE, __VA_ARGS__)) ////////////////////////////////////////////////////////////////////////// // REQUEST MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_REQUEST(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request; #define OATPP_MACRO_API_CONTROLLER_REQUEST_INFO(TYPE, PARAM_LIST) // HEADER MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_HEADER_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getHeader(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing HEADER parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid HEADER parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_HEADER_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getHeader(QUALIFIER); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, oatpp::String("Missing HEADER parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid HEADER parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_HEADER(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_HEADER_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1(TYPE, NAME) \ info->headers.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2(TYPE, NAME, QUALIFIER) \ info->headers.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_HEADER_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_HEADER_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // PATH MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_PATH_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getPathVariable(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing PATH parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid PATH parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_PATH_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getPathVariable(QUALIFIER); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Missing PATH parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid PATH parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_PATH(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_PATH_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_PATH_INFO_1(TYPE, NAME) \ info->pathParams.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_PATH_INFO_2(TYPE, NAME, QUALIFIER) \ info->pathParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_PATH_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_PATH_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // QUERIES MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_QUERIES(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request->getQueryParameters(); #define OATPP_MACRO_API_CONTROLLER_QUERIES_INFO(TYPE, PARAM_LIST) // QUERY MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_QUERY_1(TYPE, NAME) \ const auto& __param_str_val_##NAME = __request->getQueryParameter(#NAME); \ if(!__param_str_val_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing QUERY parameter '" #NAME "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Invalid QUERY parameter '" #NAME "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_QUERY_2(TYPE, NAME, QUALIFIER) \ const auto& __param_str_val_##NAME = __request->getQueryParameter(QUALIFIER); \ if(!__param_str_val_##NAME) \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Missing QUERY parameter '") + QUALIFIER + "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ bool __param_validation_check_##NAME; \ const auto& NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid QUERY parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } #define OATPP_MACRO_API_CONTROLLER_QUERY_3(TYPE, NAME, QUALIFIER, DEFAULT) \ TYPE NAME = DEFAULT; \ const auto& __param_str_val_##NAME = __request->getQueryParameter(QUALIFIER); \ if(__param_str_val_##NAME) { \ bool __param_validation_check_##NAME; \ NAME = ApiController::TypeInterpretation<TYPE>::fromString(#TYPE, __param_str_val_##NAME, __param_validation_check_##NAME); \ if(!__param_validation_check_##NAME){ \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, \ oatpp::String("Invalid QUERY parameter '") + \ QUALIFIER + \ "'. Expected type is '" #TYPE "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ } #define OATPP_MACRO_API_CONTROLLER_QUERY(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_QUERY_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // __INFO #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1(TYPE, NAME) \ info->queryParams.add(#NAME, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2(TYPE, NAME, QUALIFIER) \ info->queryParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO_3(TYPE, NAME, QUALIFIER, DEFAULT) \ info->queryParams.add(QUALIFIER, TYPE::Class::getType()); #define OATPP_MACRO_API_CONTROLLER_QUERY_INFO(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_QUERY_INFO_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) // BODY_STRING MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BODY_STRING(TYPE, PARAM_LIST) \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = __request->readBodyToString(); // __INFO #define OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO(TYPE, PARAM_LIST) \ info->body.name = OATPP_MACRO_FIRSTARG_STR PARAM_LIST; \ info->body.required = true; \ info->body.type = oatpp::data::mapping::type::__class::String::getType(); \ if(getDefaultObjectMapper()) { \ info->bodyContentType = getDefaultObjectMapper()->getInfo().http_content_type; \ } // BODY_DTO MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BODY_DTO(TYPE, PARAM_LIST) \ if(!getDefaultObjectMapper()) { \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_500, "ObjectMapper was NOT set. Can't deserialize the request body."); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } \ const auto& OATPP_MACRO_FIRSTARG PARAM_LIST = \ __request->readBodyToDto<TYPE>(getDefaultObjectMapper().get()); \ if(!OATPP_MACRO_FIRSTARG PARAM_LIST) { \ auto httpError = oatpp::web::protocol::http::HttpError(Status::CODE_400, "Missing valid body parameter '" OATPP_MACRO_FIRSTARG_STR PARAM_LIST "'"); \ auto eptr = std::make_exception_ptr(httpError); \ return ApiController::handleError(eptr); \ } // __INFO #define OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO(TYPE, PARAM_LIST) \ info->body.name = OATPP_MACRO_FIRSTARG_STR PARAM_LIST; \ info->body.required = true; \ info->body.type = TYPE::Class::getType(); \ if(getDefaultObjectMapper()) { \ info->bodyContentType = getDefaultObjectMapper()->getInfo().http_content_type; \ } // FOR EACH // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_FIRST(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_TYPE X OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_REST(INDEX, COUNT, X) \ , OATPP_MACRO_API_CONTROLLER_PARAM_TYPE X OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_MACRO X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_FIRST(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_REST(INDEX, COUNT, X) \ , OATPP_MACRO_API_CONTROLLER_PARAM_NAME X #define OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO(INDEX, COUNT, X) \ OATPP_MACRO_API_CONTROLLER_PARAM_INFO X // ENDPOINT_INFO MACRO // ------------------------------------------------------ #define ENDPOINT_INFO(NAME) \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__ENDPOINT_CREATE_ADDITIONAL_INFO_##NAME() { \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ Z__ENDPOINT_ADD_INFO_##NAME(info); \ return info; \ } \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__ENDPOINT_ADDITIONAL_INFO_##NAME = Z__ENDPOINT_CREATE_ADDITIONAL_INFO_##NAME(); \ \ void Z__ENDPOINT_ADD_INFO_##NAME(const std::shared_ptr<oatpp::web::server::api::Endpoint::Info>& info) // ENDPOINT MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ \ template<class T> \ static typename std::shared_ptr<Handler<T>> Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(T* controller) { \ auto handler = std::static_pointer_cast<Handler<T>>(controller->getEndpointHandler(#NAME)); \ if(!handler) { \ handler = Handler<T>::createShared(controller, &T::Z__PROXY_METHOD_##NAME, nullptr); \ controller->setEndpointHandler(#NAME, handler); \ } \ return handler; \ } \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__EDNPOINT_INFO_GET_INSTANCE_##NAME() { \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> info = getEndpointInfo(#NAME); \ if(!info){ \ info = oatpp::web::server::api::Endpoint::Info::createShared(); \ setEndpointInfo(#NAME, info); \ } \ return info; \ } #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0(NAME, METHOD, PATH) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = ((m_routerPrefix != nullptr) ? m_routerPrefix + PATH : PATH); \ info->method = METHOD; \ if (info->path == "") { \ info->path = "/"; \ } \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_0(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0(NAME, METHOD, PATH) \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ (void)__request; \ return NAME(); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> NAME() //////////////////// #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1(NAME, METHOD, PATH, ...) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = ((m_routerPrefix != nullptr) ? m_routerPrefix + PATH : PATH); \ info->method = METHOD; \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO, __VA_ARGS__) \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_1(NAME, METHOD, PATH, ...) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1(NAME, METHOD, PATH, __VA_ARGS__) \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ OATPP_MACRO_FOREACH(OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT, __VA_ARGS__) \ return NAME( \ OATPP_MACRO_FOREACH_FIRST_AND_REST( \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_FIRST, \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL_REST, \ __VA_ARGS__ \ ) \ ); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> NAME(\ OATPP_MACRO_FOREACH_FIRST_AND_REST( \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_FIRST, \ OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL_REST, \ __VA_ARGS__ \ ) \ ) // Chooser #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0(METHOD, PATH, NAME) \ OATPP_MACRO_EXPAND(OATPP_MACRO_API_CONTROLLER_ENDPOINT_0(NAME, METHOD, PATH)) #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1(METHOD, PATH, NAME, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_API_CONTROLLER_ENDPOINT_1(NAME, METHOD, PATH, __VA_ARGS__)) /** * Codegen macro to be used in `oatpp::web::server::api::ApiController` to generate Endpoint. * @param METHOD - Http method ("GET", "POST", "PUT", etc.). * @param PATH - Path to endpoint (without host). * @param NAME - Name of the generated method. * @return - std::shared_ptr to &id:oatpp::web::protocol::http::outgoing::Response;. */ #define ENDPOINT(METHOD, PATH, ...) \ OATPP_MACRO_EXPAND(OATPP_MACRO_MACRO_BINARY_SELECTOR(OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_, (__VA_ARGS__)) (METHOD, PATH, __VA_ARGS__)) /** * Endpoint interceptor */ #define ENDPOINT_INTERCEPTOR(ENDPOINT_NAME, NAME) \ \ Handler<oatpp::web::server::api::ApiController>::Method \ Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME = Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME(this); \ \ template<class T> \ Handler<oatpp::web::server::api::ApiController>::Method Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME (T* controller) { \ return static_cast<Handler<oatpp::web::server::api::ApiController>::Method>( \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##ENDPOINT_NAME(controller)->setMethod(&T::Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME) \ ); \ } \ \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request) { \ return Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(this, request); \ } \ \ template<class T> \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ T*, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) { \ auto intercepted = static_cast<typename Handler<T>::Method>(Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME); \ return Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME <T> (intercepted, request); \ } \ \ template<class T> \ std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> \ Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ typename Handler<T>::Method intercepted, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) // ENDPOINT ASYNC MACRO // ------------------------------------------------------ /* * 1 - Method to obtain endpoint call function ptr * 2 - Endpoint info singleton */ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS(NAME, METHOD, PATH) \ \ template<class T> \ static typename std::shared_ptr<Handler<T>> Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(T* controller) { \ auto handler = std::static_pointer_cast<Handler<T>>(controller->getEndpointHandler(#NAME)); \ if(!handler) { \ handler = Handler<T>::createShared(controller, nullptr, &T::Z__PROXY_METHOD_##NAME); \ controller->setEndpointHandler(#NAME, handler); \ } \ return handler; \ } \ \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> Z__EDNPOINT_INFO_GET_INSTANCE_##NAME() { \ std::shared_ptr<oatpp::web::server::api::Endpoint::Info> info = getEndpointInfo(#NAME); \ if(!info){ \ info = oatpp::web::server::api::Endpoint::Info::createShared(); \ setEndpointInfo(#NAME, info); \ } \ return info; \ } /* * 1 - Endpoint info instance * 2 - Endpoint instance */ #define OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL(NAME, METHOD, PATH) \ \ EndpointInfoBuilder Z__CREATE_ENDPOINT_INFO_##NAME = [this](){ \ auto info = Z__EDNPOINT_INFO_GET_INSTANCE_##NAME(); \ info->name = #NAME; \ info->path = PATH; \ info->method = METHOD; \ return info; \ }; \ \ const std::shared_ptr<oatpp::web::server::api::Endpoint> Z__ENDPOINT_##NAME = createEndpoint(m_endpoints, \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##NAME(this), \ Z__CREATE_ENDPOINT_INFO_##NAME); /** * Codegen macro to be used in `oatpp::web::server::api::ApiController` to generate Asynchronous Endpoint. * @param METHOD - Http method ("GET", "POST", "PUT", etc.). * @param PATH - Path to endpoint (without host). * @param NAME - Name of the generated method. * @return - &id:oatpp::async::Action;. */ #define ENDPOINT_ASYNC(METHOD, PATH, NAME) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS(NAME, METHOD, PATH) \ OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL(NAME, METHOD, PATH) \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__PROXY_METHOD_##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& __request) \ { \ return NAME::startForResult(this, __request); \ } \ \ class NAME : public HandlerCoroutine<NAME, __ControllerType> /** * Auxiliary codegen macro for `ENDPOINT_ASYNC` to generate correct constructor for Asynchronous Endpoint Coroutine. * @NAME - Name of the endpoint. Exact the same name as was passed to `ENDPOINT_ASYNC` macro. */ #define ENDPOINT_ASYNC_INIT(NAME) \ public: \ \ NAME(__ControllerType* pController, \ const std::shared_ptr<IncomingRequest>& pRequest) \ : HandlerCoroutine(pController, pRequest) \ {} /** * Endpoint interceptor */ #define ENDPOINT_INTERCEPTOR_ASYNC(ENDPOINT_NAME, NAME) \ \ Handler<oatpp::web::server::api::ApiController>::MethodAsync \ Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME = Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME(this); \ \ template<class T> \ Handler<oatpp::web::server::api::ApiController>::MethodAsync Z__INTERCEPTOR_METHOD_SET_##ENDPOINT_NAME ##_ ##NAME (T* controller) { \ return static_cast<Handler<oatpp::web::server::api::ApiController>::MethodAsync>( \ Z__ENDPOINT_HANDLER_GET_INSTANCE_##ENDPOINT_NAME(controller)->setMethodAsync(&T::Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME) \ ); \ } \ \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request) { \ return Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME(this, request); \ } \ \ template<class T> \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__USER_PROXY_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ T*, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ ) { \ auto intercepted = static_cast<typename Handler<T>::MethodAsync>(Z__INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME); \ return Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME <T> (intercepted, request); \ } \ \ template<class T> \ oatpp::async::CoroutineStarterForResult<const std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>&> \ Z__USER_INTERCEPTOR_METHOD_##ENDPOINT_NAME ##_ ##NAME( \ typename Handler<T>::MethodAsync intercepted, \ const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>& request \ )
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/base_define.hpp
C++
apache-2.0
27,070
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef OATPP_MACRO_API_CONTROLLER_PARAM_MACRO #undef OATPP_MACRO_API_CONTROLLER_PARAM_INFO #undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE #undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME #undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR #undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR #undef OATPP_MACRO_API_CONTROLLER_PARAM #undef REQUEST #undef HEADER #undef PATH #undef QUERIES #undef QUERY #undef BODY_STRING #undef BODY_DTO // INIT // ------------------------------------------------------ #undef REST_CONTROLLER_INIT #undef OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR // REQUEST MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_REQUEST #undef OATPP_MACRO_API_CONTROLLER_REQUEST_INFO // HEADER MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_HEADER_1 #undef OATPP_MACRO_API_CONTROLLER_HEADER_2 #undef OATPP_MACRO_API_CONTROLLER_HEADER // __INFO #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO // PATH MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_PATH_1 #undef OATPP_MACRO_API_CONTROLLER_PATH_2 #undef OATPP_MACRO_API_CONTROLLER_PATH // __INFO #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_PATH_INFO // QUERIES MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_QUERIES #undef OATPP_MACRO_API_CONTROLLER_QUERIES_INFO // QUERY MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_QUERY_1 #undef OATPP_MACRO_API_CONTROLLER_QUERY_2 #undef OATPP_MACRO_API_CONTROLLER_QUERY // __INFO #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1 #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2 #undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO // BODY_STRING MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_BODY_STRING // __INFO #undef OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO // BODY_DTO MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_BODY_DTO // __INFO #undef OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO // FOR EACH // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL #undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO // ENDPOINT_INFO MACRO // ------------------------------------------------------ #undef ENDPOINT_INFO // ENDPOINT MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_1 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0 #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1 #undef ENDPOINT #undef ENDPOINT_INTERCEPTOR // ENDPOINT ASYNC MACRO // ------------------------------------------------------ #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS #undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL #undef ENDPOINT_ASYNC #undef ENDPOINT_ASYNC_INIT #undef ENDPOINT_INTERCEPTOR_ASYNC
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/base_undef.hpp
C++
apache-2.0
4,471
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #define BUNDLE(TYPE, ...) \ OATPP_MACRO_API_CONTROLLER_PARAM(OATPP_MACRO_API_CONTROLLER_BUNDLE, OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO, TYPE, (__VA_ARGS__)) // BUNDLE MACRO // ------------------------------------------------------ #define OATPP_MACRO_API_CONTROLLER_BUNDLE_1(TYPE, NAME) \ TYPE NAME = __request->getBundleData<TYPE>(#NAME); #define OATPP_MACRO_API_CONTROLLER_BUNDLE_2(TYPE, NAME, QUALIFIER) \ TYPE NAME = __request->getBundleData<TYPE>(QUALIFIER); #define OATPP_MACRO_API_CONTROLLER_BUNDLE(TYPE, PARAM_LIST) \ OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR(OATPP_MACRO_API_CONTROLLER_BUNDLE_, TYPE, OATPP_MACRO_UNFOLD_VA_ARGS PARAM_LIST) #define OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO(TYPE, PARAM_LIST)
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/bundle_define.hpp
C++
apache-2.0
1,787
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #undef BUNDLE #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_1 #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_2 #undef OATPP_MACRO_API_CONTROLLER_BUNDLE #undef OATPP_MACRO_API_CONTROLLER_BUNDLE_INFO
vincent-in-black-sesame/oat
src/oatpp/codegen/api_controller/bundle_undef.hpp
C++
apache-2.0
1,257
End of preview. Expand in Data Studio

Gitee Code Dataset

Dataset Description

This dataset was compiled from code repositories hosted on Gitee, China's largest code hosting platform and a leading alternative to GitHub in the Chinese developer community. Gitee is widely used by Chinese developers, enterprises, and open-source projects, making this dataset particularly valuable for training code models with strong Chinese language understanding and Chinese coding conventions.

Dataset Summary

Statistic Value
Total Files 819,472,785
Total Repositories 3,105,923
Total Size 536 GB (compressed Parquet)
Programming Languages 554
File Format Parquet with Zstd compression (468 files)

Key Features

  • Large-scale Chinese code corpus: Contains code from over 3 million repositories, many featuring Chinese comments, documentation, and variable names
  • Diverse language coverage: Spans 554 programming languages identified by go-enry (based on GitHub Linguist rules)
  • Rich metadata: Includes repository name, file path, detected language, license information, and file size
  • Enterprise and open-source projects: Includes code from both individual developers and Chinese enterprises
  • Quality filtered: Extensive filtering to remove vendor code, build artifacts, generated files, and low-quality content

Languages

The dataset includes 554 programming languages. The top 30 languages by file count:

Rank Language File Count
1 Java 293,439,777
2 JavaScript 77,715,425
3 C 62,836,721
4 C++ 49,134,251
5 HTML 46,191,063
6 Vue 40,468,646
7 PHP 37,132,954
8 C# 33,842,369
9 Python 25,192,704
10 CSS 20,802,464
11 TypeScript 20,122,528
12 Go 16,176,561
13 Shell 8,371,429
14 Makefile 6,341,964
15 Java Server Pages 6,224,523
16 TSX 5,768,542
17 CMake 5,581,774
18 SCSS 5,291,031
19 Objective-C 4,922,736
20 Less 4,669,672
21 Ruby 3,027,385
22 Kotlin 2,986,211
23 Scala 2,869,640
24 Rust 2,466,122
25 Starlark 2,027,514
26 Dart 2,010,079
27 Unix Assembly 1,900,320
28 Fluent 1,882,380
29 HTML+Razor 1,863,914
30 Swift 1,607,477

Licenses

The dataset includes files from repositories with various licenses. Repositories with restrictive licenses (CC-BY-ND variants, Commons Clause, SSPL) were excluded:

License File Count
apache-2.0 273,706,950
mit 201,880,040
unknown 195,868,240
agpl-3.0 60,181,320
bsd 30,013,190
gpl-2.0 27,831,530
lgpl-3.0 11,746,750
lgpl-2.1 4,807,600
bsd-3-clause 4,442,480
cc0-1.0 3,144,920
gpl-3.0 1,631,590
unlicense 1,181,930
bsd-2-clause 1,154,300
epl-1.0 1,045,470
Other licenses ~5,800,000

Dataset Structure

Data Fields

Field Type Description
code string Content of the source file (UTF-8 encoded)
repo_name string Name of the Gitee repository (format: username/repo)
path string Path of the file within the repository (relative to repo root)
language string Programming language as identified by go-enry
license string License of the repository (SPDX identifier or "unknown")
size int64 Size of the source file in bytes

Data Format

  • Format: Apache Parquet with Zstd compression
  • File Structure: 468 files (gitee_0000.parquet to gitee_0467.parquet)

Data Splits

All examples are in the train split. There is no validation or test split.

Example Data Point

{
    'code': 'package com.example.demo;\n\nimport org.springframework.boot.SpringApplication;\n...',
    'repo_name': 'username/spring-demo',
    'path': 'src/main/java/com/example/demo/Application.java',
    'language': 'Java',
    'license': 'apache-2.0',
    'size': 1234
}

Dataset Creation

Pipeline Overview

The dataset was created through a multi-stage pipeline:

  1. Repository Discovery
  2. Branch Selection: Selecting the main branch for each repository (priority: master > main > develop > dev > first branch)
  3. Repository Downloading
  4. Content Extraction: Extracting and filtering source code files
  5. Parquet Generation: Writing filtered records to Parquet shards with Zstd compression

Language Detection

Programming languages are detected using go-enry, a Go port of GitHub's Linguist library. Only files classified as Programming or Markup language types are included (Data and Prose types are excluded).

License Detection

Licenses are detected by:

  1. Scanning for license files (LICENSE, LICENSE.txt, LICENSE.md, COPYING, etc.)
  2. Matching license text against known patterns (MIT, Apache 2.0, GPL variants, BSD, Creative Commons, etc.)
  3. Defaulting to "unknown" if no license can be detected

Blocked Licenses: The following restrictive licenses are excluded from the dataset:

  • cc-by-nd, cc-by-nd-2.0, cc-by-nd-3.0, cc-by-nd-4.0 (Creative Commons No-Derivatives)
  • commons-clause
  • sspl, sspl-1.0 (Server Side Public License)

File Filtering

Extensive filtering is applied to ensure data quality:

Size Limits

Limit Value
Max repository ZIP size 48 MB
Max single file size 1 MB
Max line length 1,000 characters

Excluded Directories

  • Configuration: .git/, .github/, .gitlab/, .vscode/, .idea/, .vs/, .settings/, .eclipse/, .project/, .metadata/
  • Vendor/Dependencies: node_modules/, bower_components/, jspm_packages/, vendor/, third_party/, 3rdparty/, external/, packages/, deps/, lib/vendor/, target/dependency/, Pods/
  • Build Output: build/, dist/, out/, bin/, target/, release/, debug/, .next/, .nuxt/, _site/, _build/, __pycache__/, .pytest_cache/, cmake-build-*, .gradle/, .maven/

Excluded Files

  • Lock Files: package-lock.json, yarn.lock, pnpm-lock.yaml, Gemfile.lock, Cargo.lock, poetry.lock, Pipfile.lock, composer.lock, go.sum, mix.lock
  • Minified Files: Any file containing .min. in the name
  • Binary Files: .exe, .dll, .so, .dylib, .a, .lib, .o, .obj, .jar, .war, .ear, .class, .pyc, .pyo, .wasm, .bin, .dat, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .zip, .tar, .gz, .bz2, .7z, .rar, .jpg, .jpeg, .png, .gif, .bmp, .ico, .svg, .mp3, .mp4, .avi, .mov, .wav, .flac, .ttf, .otf, .woff, .woff2, .eot
  • System Files: .DS_Store, thumbs.db

Content Filtering

  • UTF-8 Validation: Files must be valid UTF-8 encoded text
  • Binary Detection: Files detected as binary by go-enry are excluded
  • Generated Files: Files with generation markers in the first 500 bytes are excluded:
    • generated by, do not edit, auto-generated, autogenerated, automatically generated, code generator, generated code, this file is generated, @generated, <auto-generated
  • Empty Files: Files that are empty or contain only whitespace are excluded
  • Long Lines: Files with any line exceeding 1,000 characters are excluded
  • go-enry Filters: Additional filtering using go-enry's IsVendor(), IsImage(), IsDotFile(), IsTest(), and IsGenerated() functions
  • Documentation-only Repos: Repositories containing only documentation files (no actual code) are skipped

Source Data

All data originates from public repositories hosted on Gitee.

Considerations for Using the Data

Personal and Sensitive Information

The dataset may contain:

  • Email addresses in code comments or configuration files
  • API keys or credentials that were accidentally committed
  • Personal information in comments or documentation

Users should exercise caution and implement appropriate filtering when using this data.

Licensing Information

This dataset is a collection of source code from repositories with various licenses. Any use of all or part of the code gathered in this dataset must abide by the terms of the original licenses, including attribution clauses when relevant. The license field in each data point indicates the license of the source repository.

Downloads last month
216

Collection including nyuuzyou/gitee-code