Search in sources :

Example 11 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project crate by crate.

the class Messages method sendRowDescription.

/**
     * RowDescription (B)
     * <p>
     * | 'T' | int32 len | int16 numCols
     * <p>
     * For each field:
     * <p>
     * | string name | int32 table_oid | int16 attr_num | int32 oid | int16 typlen | int32 type_modifier | int16 format_code
     * <p>
     * See https://www.postgresql.org/docs/current/static/protocol-message-formats.html
     */
static void sendRowDescription(Channel channel, Collection<Field> columns, @Nullable FormatCodes.FormatCode[] formatCodes) {
    int length = 4 + 2;
    int columnSize = 4 + 2 + 4 + 2 + 4 + 2;
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(// use 10 as an estimate for columnName length
    length + (columns.size() * (10 + columnSize)));
    buffer.writeByte('T');
    // will be set at the end
    buffer.writeInt(0);
    buffer.writeShort(columns.size());
    int idx = 0;
    for (Field column : columns) {
        byte[] nameBytes = column.path().outputName().getBytes(StandardCharsets.UTF_8);
        length += nameBytes.length + 1;
        length += columnSize;
        writeCString(buffer, nameBytes);
        // table_oid
        buffer.writeInt(0);
        // attr_num
        buffer.writeShort(0);
        PGType pgType = PGTypes.get(column.valueType());
        buffer.writeInt(pgType.oid());
        buffer.writeShort(pgType.typeLen());
        buffer.writeInt(pgType.typeMod());
        buffer.writeShort(FormatCodes.getFormatCode(formatCodes, idx).ordinal());
        idx++;
    }
    buffer.setInt(1, length);
    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                LOGGER.trace("sentRowDescription");
            }
        });
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Field(io.crate.analyze.symbol.Field) PGType(io.crate.protocols.postgres.types.PGType) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 12 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project crate by crate.

the class Messages method sendErrorResponse.

/**
     * 'E' | int32 len | char code | str value | \0 | char code | str value | \0 | ... | \0
     * <p>
     * char code / str value -> key-value fields
     * example error fields are: message, detail, hint, error position
     * <p>
     * See https://www.postgresql.org/docs/9.2/static/protocol-error-fields.html for a list of error codes
     */
static void sendErrorResponse(Channel channel, Throwable throwable) {
    final String message = SQLExceptions.messageOf(throwable);
    byte[] msg = message.getBytes(StandardCharsets.UTF_8);
    byte[] severity = "ERROR".getBytes(StandardCharsets.UTF_8);
    byte[] lineNumber = null;
    byte[] fileName = null;
    byte[] methodName = null;
    StackTraceElement[] stackTrace = throwable.getStackTrace();
    if (stackTrace != null && stackTrace.length > 0) {
        StackTraceElement stackTraceElement = stackTrace[0];
        lineNumber = String.valueOf(stackTraceElement.getLineNumber()).getBytes(StandardCharsets.UTF_8);
        if (stackTraceElement.getFileName() != null) {
            fileName = stackTraceElement.getFileName().getBytes(StandardCharsets.UTF_8);
        }
        if (stackTraceElement.getMethodName() != null) {
            methodName = stackTraceElement.getMethodName().getBytes(StandardCharsets.UTF_8);
        }
    }
    // See https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
    // need to add a throwable -> error code mapping later on
    byte[] errorCode;
    if (throwable instanceof IllegalArgumentException || throwable instanceof UnsupportedOperationException) {
        // feature_not_supported
        errorCode = "0A000".getBytes(StandardCharsets.UTF_8);
    } else {
        // internal_error
        errorCode = "XX000".getBytes(StandardCharsets.UTF_8);
    }
    int length = 4 + 1 + (severity.length + 1) + 1 + (msg.length + 1) + 1 + (errorCode.length + 1) + (fileName != null ? 1 + (fileName.length + 1) : 0) + (lineNumber != null ? 1 + (lineNumber.length + 1) : 0) + (methodName != null ? 1 + (methodName.length + 1) : 0) + 1;
    ChannelBuffer buffer = ChannelBuffers.buffer(length + 1);
    buffer.writeByte('E');
    buffer.writeInt(length);
    buffer.writeByte('S');
    writeCString(buffer, severity);
    buffer.writeByte('M');
    writeCString(buffer, msg);
    buffer.writeByte(('C'));
    writeCString(buffer, errorCode);
    if (fileName != null) {
        buffer.writeByte('F');
        writeCString(buffer, fileName);
    }
    if (lineNumber != null) {
        buffer.writeByte('L');
        writeCString(buffer, lineNumber);
    }
    if (methodName != null) {
        buffer.writeByte('R');
        writeCString(buffer, methodName);
    }
    buffer.writeByte(0);
    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                LOGGER.trace("sentErrorResponse msg={}", message);
            }
        });
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 13 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class TestRpcHandler method httpOptionsCORSNotConfigured.

@Test
public void httpOptionsCORSNotConfigured() {
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/api/v1/version");
    req.headers().add(HttpHeaders.ORIGIN, "42.com");
    handleHttpRpc(req, new Answer<ChannelFuture>() {

        public ChannelFuture answer(final InvocationOnMock args) throws Throwable {
            DefaultHttpResponse response = (DefaultHttpResponse) args.getArguments()[0];
            assertEquals(HttpResponseStatus.METHOD_NOT_ALLOWED, response.getStatus());
            assertNull(response.headers().get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
            return null;
        }
    });
    final RpcHandler rpc = new RpcHandler(tsdb, rpc_manager);
    rpc.messageReceived(ctx, message);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 14 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class TestRpcHandler method emptyPathIsBadRequest.

@Test
public void emptyPathIsBadRequest() throws Exception {
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    final Channel mockChan = handleHttpRpc(req, new Answer<ChannelFuture>() {

        public ChannelFuture answer(final InvocationOnMock args) throws Throwable {
            DefaultHttpResponse response = (DefaultHttpResponse) args.getArguments()[0];
            assertEquals(HttpResponseStatus.BAD_REQUEST, response.getStatus());
            return new SucceededChannelFuture((Channel) args.getMock());
        }
    });
    final RpcHandler rpc = new RpcHandler(tsdb, rpc_manager);
    Whitebox.invokeMethod(rpc, "handleHttpQuery", tsdb, mockChan, req);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Channel(org.jboss.netty.channel.Channel) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 15 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class TestRpcHandler method httpOptionsNoCORS.

@Test
public void httpOptionsNoCORS() {
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/api/v1/version");
    handleHttpRpc(req, new Answer<ChannelFuture>() {

        public ChannelFuture answer(final InvocationOnMock args) throws Throwable {
            DefaultHttpResponse response = (DefaultHttpResponse) args.getArguments()[0];
            assertEquals(HttpResponseStatus.METHOD_NOT_ALLOWED, response.getStatus());
            assertNull(response.headers().get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
            return null;
        }
    });
    final RpcHandler rpc = new RpcHandler(tsdb, rpc_manager);
    rpc.messageReceived(ctx, message);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)138 Channel (org.jboss.netty.channel.Channel)40 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)38 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)28 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)26 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)23 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)23 Test (org.junit.Test)15 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)9 Test (org.testng.annotations.Test)8 IOException (java.io.IOException)7 ConnectException (java.net.ConnectException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6