Search in sources :

Example 6 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType 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 7 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType 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 8 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project junit-servers by mjeanroy.

the class OkHttpResponseBuilder method build.

@SuppressWarnings("deprecation")
@Override
public Response build() {
    Request request = new Request.Builder().url("http://localhost:8080").build();
    Protocol protocol = Protocol.HTTP_1_0;
    Response.Builder builder = new Response.Builder().request(request).protocol(protocol).code(status);
    if (body != null) {
        MediaType mediaType = MediaType.parse("plain/text");
        String content = body == null ? "" : body;
        builder.body(ResponseBody.create(mediaType, content));
    }
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            builder.addHeader(headerName, headerValue);
        }
    }
    builder.message("OK");
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) MediaType(okhttp3.MediaType) List(java.util.List) Protocol(okhttp3.Protocol) Map(java.util.Map)

Example 9 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project junit-servers by mjeanroy.

the class OkHttpRequest method createBody.

/**
 * Create the OkHttp request body.
 *
 * @return OkHttp {@link RequestBody} instance.
 * @see RequestBody#create(MediaType, String)
 * @see FormBody
 */
@SuppressWarnings("deprecation")
private RequestBody createBody() throws IOException {
    if (body == null) {
        return null;
    }
    log.debug("Creating OkHTTP request body from: {}", body);
    String rawContentType = body.getContentType();
    MediaType mediaType = rawContentType == null ? null : MediaType.parse(rawContentType);
    return RequestBody.create(mediaType, body.getBody());
}
Also used : MediaType(okhttp3.MediaType)

Example 10 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project media by androidx.

the class OkHttpDataSource method open.

@Override
public long open(DataSpec dataSpec) throws HttpDataSourceException {
    this.dataSpec = dataSpec;
    bytesRead = 0;
    bytesToRead = 0;
    transferInitializing(dataSpec);
    Request request = makeRequest(dataSpec);
    Response response;
    ResponseBody responseBody;
    try {
        this.response = callFactory.newCall(request).execute();
        response = this.response;
        responseBody = Assertions.checkNotNull(response.body());
        responseByteStream = responseBody.byteStream();
    } catch (IOException e) {
        throw HttpDataSourceException.createForIOException(e, dataSpec, HttpDataSourceException.TYPE_OPEN);
    }
    int responseCode = response.code();
    // Check for a valid response code.
    if (!response.isSuccessful()) {
        if (responseCode == 416) {
            long documentSize = HttpUtil.getDocumentSize(response.headers().get(HttpHeaders.CONTENT_RANGE));
            if (dataSpec.position == documentSize) {
                opened = true;
                transferStarted(dataSpec);
                return dataSpec.length != C.LENGTH_UNSET ? dataSpec.length : 0;
            }
        }
        byte[] errorResponseBody;
        try {
            errorResponseBody = Util.toByteArray(Assertions.checkNotNull(responseByteStream));
        } catch (IOException e) {
            errorResponseBody = Util.EMPTY_BYTE_ARRAY;
        }
        Map<String, List<String>> headers = response.headers().toMultimap();
        closeConnectionQuietly();
        @Nullable IOException cause = responseCode == 416 ? new DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE) : null;
        throw new InvalidResponseCodeException(responseCode, response.message(), cause, headers, dataSpec, errorResponseBody);
    }
    // Check for a valid content type.
    @Nullable MediaType mediaType = responseBody.contentType();
    String contentType = mediaType != null ? mediaType.toString() : "";
    if (contentTypePredicate != null && !contentTypePredicate.apply(contentType)) {
        closeConnectionQuietly();
        throw new InvalidContentTypeException(contentType, dataSpec);
    }
    // If we requested a range starting from a non-zero position and received a 200 rather than a
    // 206, then the server does not support partial requests. We'll need to manually skip to the
    // requested position.
    long bytesToSkip = responseCode == 200 && dataSpec.position != 0 ? dataSpec.position : 0;
    // Determine the length of the data to be read, after skipping.
    if (dataSpec.length != C.LENGTH_UNSET) {
        bytesToRead = dataSpec.length;
    } else {
        long contentLength = responseBody.contentLength();
        bytesToRead = contentLength != -1 ? (contentLength - bytesToSkip) : C.LENGTH_UNSET;
    }
    opened = true;
    transferStarted(dataSpec);
    try {
        skipFully(bytesToSkip, dataSpec);
    } catch (HttpDataSourceException e) {
        closeConnectionQuietly();
        throw e;
    }
    return bytesToRead;
}
Also used : Request(okhttp3.Request) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) DataSourceException(androidx.media3.datasource.DataSourceException) MediaType(okhttp3.MediaType) List(java.util.List) Nullable(androidx.annotation.Nullable)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21