Search in sources :

Example 11 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project cats by Endava.

the class ServiceCaller method callService.

public CatsResponse callService(CatsRequest catsRequest, Set<String> fuzzedFields) throws IOException {
    long startTime = System.currentTimeMillis();
    RequestBody requestBody = null;
    Headers.Builder headers = new Headers.Builder();
    catsRequest.getHeaders().forEach(header -> headers.addUnsafeNonAscii(header.getName(), header.getValue()));
    if (HttpMethod.requiresBody(catsRequest.getHttpMethod())) {
        requestBody = RequestBody.create(catsRequest.getPayload().getBytes(StandardCharsets.UTF_8));
    }
    Response response = okHttpClient.newCall(new Request.Builder().url(catsRequest.getUrl()).headers(headers.build()).method(catsRequest.getHttpMethod(), requestBody).build()).execute();
    long endTime = System.currentTimeMillis();
    LOGGER.complete("Protocol: {}, Method: {}, ReasonPhrase: {}, ResponseCode: {}, ResponseTimeInMs: {}", response.protocol(), catsRequest.getHttpMethod(), response.message(), response.code(), endTime - startTime);
    String responseBody = this.getAsJson(response);
    List<CatsHeader> responseHeaders = response.headers().toMultimap().entrySet().stream().map(header -> CatsHeader.builder().name(header.getKey()).value(header.getValue().get(0)).build()).collect(Collectors.toList());
    return CatsResponse.from(response.code(), responseBody, catsRequest.getHttpMethod(), endTime - startTime, responseHeaders, fuzzedFields);
}
Also used : CatsResponse(com.endava.cats.model.CatsResponse) Response(okhttp3.Response) X509Certificate(java.security.cert.X509Certificate) ADDITIONAL_PROPERTIES(com.endava.cats.dsl.CatsDSLWords.ADDITIONAL_PROPERTIES) JsonObject(com.google.gson.JsonObject) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) CatsGlobalContext(com.endava.cats.model.CatsGlobalContext) CatsDSLWords(com.endava.cats.dsl.CatsDSLWords) TrustManager(javax.net.ssl.TrustManager) HtmlEscapers(com.google.common.html.HtmlEscapers) CatsResponse(com.endava.cats.model.CatsResponse) PrettyLogger(io.github.ludovicianul.prettylogger.PrettyLogger) StringUtils(org.apache.commons.lang3.StringUtils) SecureRandom(java.security.SecureRandom) GeneralSecurityException(java.security.GeneralSecurityException) FilesArguments(com.endava.cats.args.FilesArguments) Map(java.util.Map) ResponseBody(okhttp3.ResponseBody) CatsUtil(com.endava.cats.util.CatsUtil) Request(okhttp3.Request) Set(java.util.Set) KeyStore(java.security.KeyStore) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) AuthArguments(com.endava.cats.args.AuthArguments) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) List(java.util.List) CatsDSLParser(com.endava.cats.dsl.CatsDSLParser) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) CatsRequest(com.endava.cats.model.CatsRequest) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) HttpUrl(okhttp3.HttpUrl) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) WordUtils(com.endava.cats.util.WordUtils) PrettyLoggerFactory(io.github.ludovicianul.prettylogger.PrettyLoggerFactory) HashMap(java.util.HashMap) RateLimiter(com.google.common.util.concurrent.RateLimiter) Headers(okhttp3.Headers) TreeSet(java.util.TreeSet) RequestBody(okhttp3.RequestBody) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) Inject(javax.inject.Inject) NOT_SET(com.endava.cats.model.util.JsonUtils.NOT_SET) Response(okhttp3.Response) ProcessingArguments(com.endava.cats.args.ProcessingArguments) FuzzingStrategy(com.endava.cats.model.FuzzingStrategy) ApiArguments(com.endava.cats.args.ApiArguments) TestCaseListener(com.endava.cats.report.TestCaseListener) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JsonUtils(com.endava.cats.model.util.JsonUtils) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) HttpMethod(com.endava.cats.http.HttpMethod) X509TrustManager(javax.net.ssl.X509TrustManager) DryRun(com.endava.cats.annotations.DryRun) ConnectionPool(okhttp3.ConnectionPool) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) CatsHeader(com.endava.cats.model.CatsHeader) InputStream(java.io.InputStream) Headers(okhttp3.Headers) RequestBody(okhttp3.RequestBody) CatsHeader(com.endava.cats.model.CatsHeader)

Example 12 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project xray-maven-plugin by Xray-App.

the class XrayResultsImporter method submitStandardCloud.

public String submitStandardCloud(String format, String reportFile) throws Exception {
    OkHttpClient client = CommonUtils.getHttpClient(useInternalTestProxy, ignoreSslErrors, this.timeout);
    String authenticationPayload = "{ \"client_id\": \"" + clientId + "\", \"client_secret\": \"" + clientSecret + "\" }";
    RequestBody body = RequestBody.create(authenticationPayload, MEDIA_TYPE_JSON);
    Request request = new Request.Builder().url(xrayCloudAuthenticateUrl).post(body).build();
    Response response = null;
    String authToken = null;
    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            authToken = responseBody.replace("\"", "");
        } else {
            throw new IOException("failed to authenticate " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
    String credentials = "Bearer " + authToken;
    String[] supportedFormats = new String[] { XRAY_FORMAT, JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT, CUCUMBER_FORMAT };
    if (!Arrays.asList(supportedFormats).contains(format)) {
        throw new Exception("unsupported report format: " + format);
    }
    MediaType mediaType;
    String[] xmlBasedFormats = new String[] { JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT };
    if (Arrays.asList(xmlBasedFormats).contains(format)) {
        mediaType = MEDIA_TYPE_XML;
    } else {
        mediaType = MEDIA_TYPE_JSON;
    }
    String endpointUrl;
    if (XRAY_FORMAT.equals(format)) {
        endpointUrl = xrayCloudApiBaseUrl + "/import/execution";
    } else {
        endpointUrl = xrayCloudApiBaseUrl + "/import/execution/" + format;
    }
    RequestBody requestBody = null;
    try {
        String reportContent = new String(Files.readAllBytes(Paths.get(reportFile)));
        requestBody = RequestBody.create(reportContent, mediaType);
    } catch (Exception e1) {
        e1.printStackTrace();
        throw e1;
    }
    HttpUrl url = HttpUrl.get(endpointUrl);
    HttpUrl.Builder builder = url.newBuilder();
    if (projectKey != null) {
        builder.addQueryParameter("projectKey", this.projectKey);
    }
    if (fixVersion != null) {
        builder.addQueryParameter("fixVersion", this.fixVersion);
    }
    if (revision != null) {
        builder.addQueryParameter("revision", this.revision);
    }
    if (testPlanKey != null) {
        builder.addQueryParameter("testPlanKey", this.testPlanKey);
    }
    if (testExecKey != null) {
        builder.addQueryParameter("testExecKey", this.testExecKey);
    }
    if (testEnvironment != null) {
        builder.addQueryParameter("testEnvironment", this.testEnvironment);
    }
    request = new Request.Builder().url(builder.build()).post(requestBody).addHeader("Authorization", credentials).build();
    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            JSONObject responseObj = new JSONObject(responseBody);
            // System.out.println("Test Execution: "+((JSONObject)(responseObj.get("testExecIssue"))).get("key"));
            return (responseBody);
        } else {
            // System.err.println(responseBody);
            throw new IOException("Unexpected HTTP code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) JSONObject(org.json.JSONObject) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 13 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project xray-maven-plugin by Xray-App.

the class XrayResultsImporter method submitMultipartCloud.

public String submitMultipartCloud(String format, String reportFile, JSONObject testExecInfo, JSONObject testInfo) throws Exception {
    OkHttpClient client = CommonUtils.getHttpClient(this.useInternalTestProxy, this.ignoreSslErrors, this.timeout);
    String authenticationPayload = "{ \"client_id\": \"" + clientId + "\", \"client_secret\": \"" + clientSecret + "\" }";
    RequestBody body = RequestBody.create(authenticationPayload, MEDIA_TYPE_JSON);
    Request request = new Request.Builder().url(xrayCloudAuthenticateUrl).post(body).build();
    Response response = null;
    String authToken = null;
    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            authToken = responseBody.replace("\"", "");
        } else {
            throw new IOException("failed to authenticate " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
    String credentials = "Bearer " + authToken;
    String[] supportedFormats = new String[] { XRAY_FORMAT, JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT, CUCUMBER_FORMAT };
    if (!Arrays.asList(supportedFormats).contains(format)) {
        throw new Exception("unsupported report format: " + format);
    }
    MediaType mediaType;
    String[] xmlBasedFormats = new String[] { JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT };
    if (Arrays.asList(xmlBasedFormats).contains(format)) {
        mediaType = MEDIA_TYPE_XML;
    } else {
        mediaType = MEDIA_TYPE_JSON;
    }
    String endpointUrl;
    if ("xray".equals(format)) {
        endpointUrl = xrayCloudApiBaseUrl + "/import/execution/multipart";
    } else {
        endpointUrl = xrayCloudApiBaseUrl + "/import/execution/" + format + "/multipart";
    }
    HttpUrl url = HttpUrl.get(endpointUrl);
    HttpUrl.Builder builder = url.newBuilder();
    MultipartBody requestBody = null;
    try {
        requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("results", reportFile, RequestBody.create(new File(reportFile), mediaType)).addFormDataPart("info", "info.json", RequestBody.create(testExecInfo.toString(), MEDIA_TYPE_JSON)).build();
    } catch (Exception e1) {
        e1.printStackTrace();
        throw e1;
    }
    request = new Request.Builder().url(builder.build()).post(requestBody).addHeader("Authorization", credentials).build();
    response = null;
    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            JSONObject responseObj = new JSONObject(responseBody);
            // System.out.println("Test Execution: "+responseObj.get("key"));
            return responseBody;
        } else {
            // System.err.println(responseBody);
            throw new IOException("Unexpected HTTP code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) JSONObject(org.json.JSONObject) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 14 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project xray-maven-plugin by Xray-App.

the class XrayResultsImporter method submitStandardServerDC.

public String submitStandardServerDC(String format, String reportFile) throws Exception {
    OkHttpClient client = CommonUtils.getHttpClient(this.useInternalTestProxy, this.ignoreSslErrors, this.timeout);
    String credentials;
    if (jiraPersonalAccessToken != null) {
        credentials = "Bearer " + jiraPersonalAccessToken;
    } else {
        credentials = Credentials.basic(jiraUsername, jiraPassword);
    }
    String[] supportedFormats = new String[] { XRAY_FORMAT, JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT, CUCUMBER_FORMAT, BEHAVE_FORMAT };
    if (!Arrays.asList(supportedFormats).contains(format)) {
        throw new Exception("unsupported report format: " + format);
    }
    MediaType mediaType;
    String[] xmlBasedFormats = new String[] { JUNIT_FORMAT, TESTNG_FORMAT, ROBOT_FORMAT, NUNIT_FORMAT, XUNIT_FORMAT };
    if (Arrays.asList(xmlBasedFormats).contains(format)) {
        mediaType = MEDIA_TYPE_XML;
    } else {
        mediaType = MEDIA_TYPE_JSON;
    }
    String endpointUrl;
    if (XRAY_FORMAT.equals(format)) {
        endpointUrl = jiraBaseUrl + "/rest/raven/2.0/import/execution";
    } else {
        endpointUrl = jiraBaseUrl + "/rest/raven/2.0/import/execution/" + format;
    }
    Request request;
    HttpUrl url = HttpUrl.get(endpointUrl);
    HttpUrl.Builder builder = url.newBuilder();
    // for cucumber and behave reports send the report directly on the body
    try {
        if (XRAY_FORMAT.equals(format) || CUCUMBER_FORMAT.equals(format) || BEHAVE_FORMAT.equals(format)) {
            String reportContent = new String(Files.readAllBytes(Paths.get(reportFile)));
            RequestBody requestBody = RequestBody.create(reportContent, mediaType);
            request = new Request.Builder().url(builder.build()).post(requestBody).addHeader("Authorization", credentials).build();
        } else {
            MultipartBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", reportFile, RequestBody.create(new File(reportFile), mediaType)).build();
            // for cucumber and behave formats, these URL parameters are not yet available
            if (projectKey != null) {
                builder.addQueryParameter("projectKey", this.projectKey);
            }
            if (fixVersion != null) {
                builder.addQueryParameter("fixVersion", this.fixVersion);
            }
            if (revision != null) {
                builder.addQueryParameter("revision", this.revision);
            }
            if (testPlanKey != null) {
                builder.addQueryParameter("testPlanKey", this.testPlanKey);
            }
            if (testExecKey != null) {
                builder.addQueryParameter("testExecKey", this.testExecKey);
            }
            if (testEnvironment != null) {
                builder.addQueryParameter("testEnvironment", this.testEnvironment);
            }
            request = new Request.Builder().url(builder.build()).post(requestBody).addHeader("Authorization", credentials).build();
        }
    } catch (Exception e1) {
        e1.printStackTrace();
        throw e1;
    }
    Response response = null;
    try {
        response = client.newCall(request).execute();
        String responseBody = response.body().string();
        if (response.isSuccessful()) {
            JSONObject responseObj = new JSONObject(responseBody);
            // System.out.println("Test Execution: "+((JSONObject)(responseObj.get("testExecIssue"))).get("key"));
            return (responseBody);
        } else {
            // System.err.println(responseBody);
            throw new IOException("Unexpected HTTP code " + response);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) JSONObject(org.json.JSONObject) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 15 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project xdagj by XDagger.

the class Web3HttpServerTest method sendJsonRpcMessage.

private Response sendJsonRpcMessage(int port, String contentType, String host) throws IOException {
    Map<String, JsonNode> jsonRpcRequestProperties = new HashMap<>();
    jsonRpcRequestProperties.put("jsonrpc", JSON_NODE_FACTORY.textNode("2.0"));
    jsonRpcRequestProperties.put("id", JSON_NODE_FACTORY.numberNode(13));
    jsonRpcRequestProperties.put("method", JSON_NODE_FACTORY.textNode("web3_sha3"));
    jsonRpcRequestProperties.put("params", JSON_NODE_FACTORY.arrayNode().add("value"));
    RequestBody requestBody = RequestBody.Companion.create(JSON_NODE_FACTORY.objectNode().setAll(jsonRpcRequestProperties).toString(), MediaType.parse(contentType));
    URL url = new URL("http", "localhost", port, "/");
    Request request = new Request.Builder().url(url).addHeader("Host", host).post(requestBody).build();
    return getUnsafeOkHttpClient().newCall(request).execute();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) JsonNode(com.fasterxml.jackson.databind.JsonNode) URL(java.net.URL) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)1358 Request (okhttp3.Request)785 Response (okhttp3.Response)598 IOException (java.io.IOException)420 Test (org.junit.Test)235 OkHttpClient (okhttp3.OkHttpClient)216 MultipartBody (okhttp3.MultipartBody)213 MediaType (okhttp3.MediaType)204 Call (okhttp3.Call)198 JSONObject (org.json.JSONObject)183 ResponseBody (okhttp3.ResponseBody)177 Callback (okhttp3.Callback)115 FormBody (okhttp3.FormBody)106 Buffer (okio.Buffer)98 File (java.io.File)92 Map (java.util.Map)90 JsonObject (io.vertx.core.json.JsonObject)89 Headers (okhttp3.Headers)88 HashMap (java.util.HashMap)83 HttpUrl (okhttp3.HttpUrl)80