Search in sources :

Example 1 with ServiceError

use of org.eclipse.che.api.core.rest.shared.dto.ServiceError in project che by eclipse.

the class FactoryServiceTest method shouldThrowServerExceptionWhenProvidedFactoryDataInvalid.

@Test
public void shouldThrowServerExceptionWhenProvidedFactoryDataInvalid() throws Exception {
    final String errMessage = "eof";
    doThrow(new IOException(errMessage)).when(factoryBuilderSpy).build(any(InputStream.class));
    final Response response = given().auth().basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD).multiPart("factory", "any content", FACTORY_IMAGE_MIME_TYPE).expect().statusCode(500).when().post(SERVICE_PATH);
    final ServiceError err = getFromResponse(response, ServiceError.class);
    assertEquals(err.getMessage(), errMessage);
}
Also used : Response(com.jayway.restassured.response.Response) ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) Test(org.testng.annotations.Test)

Example 2 with ServiceError

use of org.eclipse.che.api.core.rest.shared.dto.ServiceError in project che by eclipse.

the class FactoryServiceTest method shouldThrowBadRequestExceptionWhenInvalidFactorySectionProvided.

@Test
public void shouldThrowBadRequestExceptionWhenInvalidFactorySectionProvided() throws Exception {
    doThrow(new JsonSyntaxException("Invalid json")).when(factoryBuilderSpy).build(any(InputStream.class));
    final Response response = given().auth().basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD).multiPart("factory", "invalid content", FACTORY_IMAGE_MIME_TYPE).expect().statusCode(400).when().post(SERVICE_PATH);
    final ServiceError err = getFromResponse(response, ServiceError.class);
    assertEquals(err.getMessage(), "Invalid JSON value of the field 'factory' provided");
}
Also used : Response(com.jayway.restassured.response.Response) ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStream(java.io.InputStream) Test(org.testng.annotations.Test)

Example 3 with ServiceError

use of org.eclipse.che.api.core.rest.shared.dto.ServiceError in project che by eclipse.

the class DefaultHttpJsonRequest method doRequest.

/**
     * Makes this request using {@link HttpURLConnection}.
     *
     * <p>Uses {@link HttpHeaders#AUTHORIZATION} header with value from {@link EnvironmentContext}.
     * <br>uses {@link HttpHeaders#ACCEPT} header with "application/json" value.
     * <br>Encodes query parameters in "UTF-8".
     *
     * @param timeout
     *         request timeout, used only if it is greater than 0
     * @param url
     *         request url
     * @param method
     *         request method
     * @param body
     *         request body, must be instance of {@link JsonSerializable}
     * @param parameters
     *         query parameters, may be null
     * @param authorizationHeaderValue
     *         value of authorization header, may be null
     * @return response to this request
     * @throws IOException
     *         when connection content type is not "application/json"
     * @throws ServerException
     *         when response code is 500 or it is different from 400, 401, 403, 404, 409
     * @throws ForbiddenException
     *         when response code is 403
     * @throws NotFoundException
     *         when response code is 404
     * @throws UnauthorizedException
     *         when response code is 401
     * @throws ConflictException
     *         when response code is 409
     * @throws BadRequestException
     *         when response code is 400
     */
protected DefaultHttpJsonResponse doRequest(int timeout, String url, String method, Object body, List<Pair<String, ?>> parameters, String authorizationHeaderValue) throws IOException, ServerException, ForbiddenException, NotFoundException, UnauthorizedException, ConflictException, BadRequestException {
    final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
    final boolean hasQueryParams = parameters != null && !parameters.isEmpty();
    if (hasQueryParams || authToken != null) {
        final UriBuilder ub = UriBuilder.fromUri(url);
        //remove sensitive information from url.
        ub.replaceQueryParam("token", EMPTY_ARRAY);
        if (hasQueryParams) {
            for (Pair<String, ?> parameter : parameters) {
                ub.queryParam(parameter.first, parameter.second);
            }
        }
        url = ub.build().toString();
    }
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
    conn.setReadTimeout(timeout > 0 ? timeout : 60000);
    try {
        conn.setRequestMethod(method);
        //drop a hint for server side that we want to receive application/json
        conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        if (!isNullOrEmpty(authorizationHeaderValue)) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authorizationHeaderValue);
        } else if (authToken != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
        }
        if (body != null) {
            conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
            conn.setDoOutput(true);
            if (HttpMethod.DELETE.equals(method)) {
                //to avoid jdk bug described here http://bugs.java.com/view_bug.do?bug_id=7157360
                conn.setRequestMethod(HttpMethod.POST);
                conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
            }
            try (OutputStream output = conn.getOutputStream()) {
                output.write(DtoFactory.getInstance().toJson(body).getBytes());
            }
        }
        final int responseCode = conn.getResponseCode();
        if ((responseCode / 100) != 2) {
            InputStream in = conn.getErrorStream();
            if (in == null) {
                in = conn.getInputStream();
            }
            final String str;
            try (Reader reader = new InputStreamReader(in)) {
                str = CharStreams.toString(reader);
            }
            final String contentType = conn.getContentType();
            if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
                final ServiceError serviceError = DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
                if (serviceError.getMessage() != null) {
                    if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
                        throw new ForbiddenException(serviceError);
                    } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
                        throw new NotFoundException(serviceError);
                    } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
                        throw new UnauthorizedException(serviceError);
                    } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
                        throw new ConflictException(serviceError);
                    } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
                        throw new ServerException(serviceError);
                    } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
                        throw new BadRequestException(serviceError);
                    }
                    throw new ServerException(serviceError);
                }
            }
            // Can't parse content as json or content has format other we expect for error.
            throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s", UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
        }
        final String contentType = conn.getContentType();
        if (contentType != null && !contentType.startsWith(MediaType.APPLICATION_JSON)) {
            throw new IOException(conn.getResponseMessage());
        }
        try (Reader reader = new InputStreamReader(conn.getInputStream())) {
            return new DefaultHttpJsonResponse(CharStreams.toString(reader), responseCode);
        }
    } finally {
        conn.disconnect();
    }
}
Also used : ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ServerException(org.eclipse.che.api.core.ServerException) InputStreamReader(java.io.InputStreamReader) ConflictException(org.eclipse.che.api.core.ConflictException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) NotFoundException(org.eclipse.che.api.core.NotFoundException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) BadRequestException(org.eclipse.che.api.core.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 4 with ServiceError

use of org.eclipse.che.api.core.rest.shared.dto.ServiceError in project che by eclipse.

the class RuntimeExceptionMapper method toResponse.

@Override
public Response toResponse(RuntimeException exception) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = dateFormat.format(new Date());
    final String errorMessage = format("Internal Server Error occurred, error time: %s", utcTime);
    LOG.error(errorMessage, exception);
    ServiceError serviceError = DtoFactory.newDto(ServiceError.class).withMessage(errorMessage);
    return Response.serverError().entity(DtoFactory.getInstance().toJson(serviceError)).type(MediaType.APPLICATION_JSON).build();
}
Also used : ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 5 with ServiceError

use of org.eclipse.che.api.core.rest.shared.dto.ServiceError in project che by eclipse.

the class FactoryServiceTest method shouldThrowBadRequestExceptionWhenNoFactorySectionProvided.

@Test
public void shouldThrowBadRequestExceptionWhenNoFactorySectionProvided() throws Exception {
    final Response response = given().auth().basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD).multiPart("some data", "some content", FACTORY_IMAGE_MIME_TYPE).expect().statusCode(400).when().post(SERVICE_PATH);
    final ServiceError err = getFromResponse(response, ServiceError.class);
    assertEquals(err.getMessage(), "factory configuration required");
}
Also used : Response(com.jayway.restassured.response.Response) ServiceError(org.eclipse.che.api.core.rest.shared.dto.ServiceError) Test(org.testng.annotations.Test)

Aggregations

ServiceError (org.eclipse.che.api.core.rest.shared.dto.ServiceError)5 Response (com.jayway.restassured.response.Response)3 InputStream (java.io.InputStream)3 Test (org.testng.annotations.Test)3 IOException (java.io.IOException)2 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 Reader (java.io.Reader)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 UriBuilder (javax.ws.rs.core.UriBuilder)1 BadRequestException (org.eclipse.che.api.core.BadRequestException)1 ConflictException (org.eclipse.che.api.core.ConflictException)1 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)1 NotFoundException (org.eclipse.che.api.core.NotFoundException)1 ServerException (org.eclipse.che.api.core.ServerException)1 UnauthorizedException (org.eclipse.che.api.core.UnauthorizedException)1