Search in sources :

Example 1 with RequestHeader

use of com.tvd12.ezyhttp.server.core.annotation.RequestHeader in project ezyhttp by youngmonkeys.

the class HttpClient method decorateConnection.

private void decorateConnection(HttpURLConnection connection, DownloadRequest request) {
    int connectTimeout = request.getReadTimeout();
    int readTimeout = request.getReadTimeout();
    connection.setConnectTimeout(connectTimeout > 0 ? connectTimeout : defaultConnectTimeout);
    connection.setReadTimeout(readTimeout > 0 ? readTimeout : defaultReadTimeout);
    MultiValueMap requestHeaders = request.getHeaders();
    if (requestHeaders != null) {
        Map<String, String> encodedHeaders = requestHeaders.toMap();
        for (Entry<String, String> requestHeader : encodedHeaders.entrySet()) {
            connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue());
        }
    }
}
Also used : MultiValueMap(com.tvd12.ezyhttp.core.data.MultiValueMap)

Example 2 with RequestHeader

use of com.tvd12.ezyhttp.server.core.annotation.RequestHeader in project ezyhttp by youngmonkeys.

the class RequestHandlerImplementer method makeHandleRequestMethodContent.

@SuppressWarnings("MethodLength")
protected String makeHandleRequestMethodContent() {
    EzyMethod method = getHandleRequestMethod();
    EzyFunction function = new EzyFunction(method).throwsException();
    EzyBody body = function.body();
    int paramCount = 0;
    int headerCount = 0;
    int parameterCount = 0;
    int pathVariableCount = 0;
    int cookieCount = 0;
    Parameter[] parameters = handlerMethod.getParameters();
    for (Parameter parameter : parameters) {
        Class<?> parameterType = parameter.getType();
        Class<?> genericType = getGenericType(parameter);
        String genericTypeClass = genericType != null ? genericType.getName() + ".class" : "null";
        EzyInstruction instruction = new EzyInstruction("\t", "\n").clazz(parameterType).append(" ").append(PARAMETER_PREFIX).append(paramCount).equal();
        boolean hasAnnotation = false;
        RequestParam requestParamAnno = parameter.getAnnotation(RequestParam.class);
        if (requestParamAnno != null) {
            String paramKey = RequestParamAnnotations.getParamKeyString(requestParamAnno, parameterCount);
            String defaultValue = requestParamAnno.defaultValue();
            String getValueExpression = defaultValue.equals(EzyStrings.NULL) ? "arg0.getParameter(" + paramKey + ")" : "arg0.getParameter(" + paramKey + ", " + quote(defaultValue) + ")";
            String valueExpression = "this.deserializeParameter(" + paramKey + ", " + getValueExpression + ", " + parameterType.getTypeName() + ".class" + ", " + genericTypeClass + ")";
            instruction.cast(parameterType, valueExpression);
            ++parameterCount;
            hasAnnotation = true;
        }
        RequestHeader requestHeaderAnno = parameter.getAnnotation(RequestHeader.class);
        if (requestHeaderAnno != null) {
            String headerKey = RequestHeaderAnnotations.getHeaderKeyString(requestHeaderAnno, headerCount);
            String defaultValue = requestHeaderAnno.defaultValue();
            String getValueExpression = defaultValue.equals(EzyStrings.NULL) ? "arg0.getHeader(" + headerKey + ")" : "arg0.getHeader(" + headerKey + ", " + quote(defaultValue) + ")";
            String valueExpression = "this.deserializeHeader(" + headerKey + ", " + getValueExpression + ", " + parameterType.getTypeName() + ".class" + ", " + genericTypeClass + ")";
            instruction.cast(parameterType, valueExpression);
            ++headerCount;
            hasAnnotation = true;
        }
        PathVariable pathVariableAnno = parameter.getAnnotation(PathVariable.class);
        if (pathVariableAnno != null) {
            String varNameKey = PathVariableAnnotations.getVariableNameKeyString(pathVariableAnno, pathVariableCount);
            String valueExpression = "this.deserializePathVariable(" + varNameKey + ", arg0.getPathVariable(" + varNameKey + ")" + ", " + parameterType.getTypeName() + ".class" + ", " + genericTypeClass + ")";
            instruction.cast(parameterType, valueExpression);
            ++pathVariableCount;
            hasAnnotation = true;
        }
        RequestCookie requestCookieAnno = parameter.getAnnotation(RequestCookie.class);
        if (requestCookieAnno != null) {
            String cookieKey = RequestCookieAnnotations.getCookieKeyString(requestCookieAnno, cookieCount);
            String defaultValue = requestCookieAnno.defaultValue();
            String getValueExpression = defaultValue.equals(EzyStrings.NULL) ? "arg0.getCookieValue(" + cookieKey + ")" : "arg0.getCookieValue(" + cookieKey + ", " + quote(defaultValue) + ")";
            String valueExpression = "this.deserializeCookie(" + cookieKey + ", " + getValueExpression + ", " + parameterType.getTypeName() + ".class" + ", " + genericTypeClass + ")";
            instruction.cast(parameterType, valueExpression);
            ++cookieCount;
            hasAnnotation = true;
        }
        RequestBody requestBodyAnno = parameter.getAnnotation(RequestBody.class);
        if (requestBodyAnno != null) {
            instruction.brackets(parameterType).append("this.deserializeBody(").append("arg0, ").clazz(parameterType, true).append(")");
            hasAnnotation = true;
        }
        if (!hasAnnotation) {
            String valueExpression = "arg0";
            if (parameterType != RequestArguments.class) {
                String argumentKey = RequestParameters.getArgumentKeyString(parameter);
                valueExpression = "arg0.getArgument(" + argumentKey + ")";
            }
            instruction.cast(parameterType, valueExpression);
        }
        body.append(instruction);
        ++paramCount;
    }
    EzyInstruction instruction = new EzyInstruction("\t", "\n");
    Class<?> returnType = handlerMethod.getReturnType();
    if (returnType != void.class) {
        instruction.answer();
    }
    StringBuilder answerExpression = new StringBuilder();
    answerExpression.append("this.controller.").append(handlerMethod.getName()).append("(");
    for (int i = 0; i < paramCount; ++i) {
        answerExpression.append(PARAMETER_PREFIX).append(i);
        if (i < paramCount - 1) {
            answerExpression.append(", ");
        }
    }
    answerExpression.append(")");
    if (returnType != void.class) {
        instruction.valueOf(returnType, answerExpression.toString());
    } else {
        instruction.append(answerExpression);
    }
    body.append(instruction);
    if (returnType == void.class) {
        body.append(new EzyInstruction("\t", "\n").append("return null"));
    }
    return function.toString();
}
Also used : EzyBody(com.tvd12.ezyfox.asm.EzyFunction.EzyBody) RequestParam(com.tvd12.ezyhttp.server.core.annotation.RequestParam) RequestCookie(com.tvd12.ezyhttp.server.core.annotation.RequestCookie) EzyInstruction(com.tvd12.ezyfox.asm.EzyInstruction) Parameter(java.lang.reflect.Parameter) RequestHeader(com.tvd12.ezyhttp.server.core.annotation.RequestHeader) EzyFunction(com.tvd12.ezyfox.asm.EzyFunction) EzyMethod(com.tvd12.ezyfox.reflect.EzyMethod) PathVariable(com.tvd12.ezyhttp.server.core.annotation.PathVariable) RequestBody(com.tvd12.ezyhttp.server.core.annotation.RequestBody)

Example 3 with RequestHeader

use of com.tvd12.ezyhttp.server.core.annotation.RequestHeader in project ezyhttp by youngmonkeys.

the class HttpClient method request.

@SuppressWarnings("MethodLength")
public ResponseEntity request(HttpMethod method, String url, RequestEntity entity, Map<Integer, Class<?>> responseTypes, int connectTimeout, int readTimeout) throws Exception {
    if (url == null) {
        throw new IllegalArgumentException("url can not be null");
    }
    logger.debug("start: {} - {} - {}", method, url, entity != null ? entity.getHeaders() : null);
    HttpURLConnection connection = connect(url);
    try {
        connection.setConnectTimeout(connectTimeout > 0 ? connectTimeout : defaultConnectTimeout);
        connection.setReadTimeout(readTimeout > 0 ? readTimeout : defaultReadTimeout);
        connection.setRequestMethod(method.toString());
        connection.setDoInput(true);
        connection.setDoOutput(method.hasOutput());
        connection.setInstanceFollowRedirects(method == HttpMethod.GET);
        MultiValueMap requestHeaders = entity != null ? entity.getHeaders() : null;
        if (requestHeaders != null) {
            Map<String, String> encodedHeaders = requestHeaders.toMap();
            for (Entry<String, String> requestHeader : encodedHeaders.entrySet()) {
                connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue());
            }
        }
        Object requestBody = null;
        if (method != HttpMethod.GET && entity != null) {
            requestBody = entity.getBody();
        }
        byte[] requestBodyBytes = null;
        if (requestBody != null) {
            String requestContentType = connection.getRequestProperty(Headers.CONTENT_TYPE);
            if (requestContentType == null) {
                requestContentType = ContentTypes.APPLICATION_JSON;
                connection.setRequestProperty(Headers.CONTENT_TYPE, ContentTypes.APPLICATION_JSON);
            }
            requestBodyBytes = serializeRequestBody(requestContentType, requestBody);
            int requestContentLength = requestBodyBytes.length;
            connection.setFixedLengthStreamingMode(requestContentLength);
        }
        connection.connect();
        if (requestBodyBytes != null) {
            if (method.hasOutput()) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(requestBodyBytes);
                outputStream.flush();
                outputStream.close();
            } else {
                throw new IllegalArgumentException(method + " method can not have a payload body");
            }
        }
        int responseCode = connection.getResponseCode();
        Map<String, List<String>> headerFields = connection.getHeaderFields();
        MultiValueMap responseHeaders = MultiValueMap.of(headerFields);
        String responseContentType = responseHeaders.getValue(Headers.CONTENT_TYPE);
        if (responseContentType == null) {
            responseContentType = ContentTypes.APPLICATION_JSON;
        }
        InputStream inputStream = responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream();
        Object responseBody = null;
        if (inputStream != null) {
            try {
                int responseContentLength = connection.getContentLength();
                Class<?> responseType = responseTypes.get(responseCode);
                responseBody = deserializeResponseBody(responseContentType, responseContentLength, inputStream, responseType);
            } finally {
                inputStream.close();
            }
        }
        logger.debug("end: {} - {} - {} - {}", method, url, responseCode, responseHeaders);
        return new ResponseEntity(responseCode, responseHeaders, responseBody);
    } finally {
        connection.disconnect();
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ResponseEntity(com.tvd12.ezyhttp.core.response.ResponseEntity) HttpURLConnection(java.net.HttpURLConnection) ArrayList(java.util.ArrayList) List(java.util.List) MultiValueMap(com.tvd12.ezyhttp.core.data.MultiValueMap)

Aggregations

MultiValueMap (com.tvd12.ezyhttp.core.data.MultiValueMap)2 EzyFunction (com.tvd12.ezyfox.asm.EzyFunction)1 EzyBody (com.tvd12.ezyfox.asm.EzyFunction.EzyBody)1 EzyInstruction (com.tvd12.ezyfox.asm.EzyInstruction)1 EzyMethod (com.tvd12.ezyfox.reflect.EzyMethod)1 ResponseEntity (com.tvd12.ezyhttp.core.response.ResponseEntity)1 PathVariable (com.tvd12.ezyhttp.server.core.annotation.PathVariable)1 RequestBody (com.tvd12.ezyhttp.server.core.annotation.RequestBody)1 RequestCookie (com.tvd12.ezyhttp.server.core.annotation.RequestCookie)1 RequestHeader (com.tvd12.ezyhttp.server.core.annotation.RequestHeader)1 RequestParam (com.tvd12.ezyhttp.server.core.annotation.RequestParam)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Parameter (java.lang.reflect.Parameter)1 HttpURLConnection (java.net.HttpURLConnection)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1