Search in sources :

Example 6 with BadRequestException

use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.

the class FactoryServiceTest method checkValidateResolver.

@Test
public void checkValidateResolver() throws Exception {
    final FactoryParametersResolver dummyResolver = Mockito.mock(FactoryParametersResolver.class);
    factoryParametersResolvers.add(dummyResolver);
    // invalid factory
    final String invalidFactoryMessage = "invalid factory";
    doThrow(new BadRequestException(invalidFactoryMessage)).when(acceptValidator).validateOnAccept(any());
    // create factory
    final FactoryDto expectFactory = DTO.createDto(FactoryDto.class).withV("4.0").withName("matchingResolverFactory");
    // accept resolver
    when(dummyResolver.accept(anyMapOf(String.class, String.class))).thenReturn(true);
    when(dummyResolver.createFactory(anyMapOf(String.class, String.class))).thenReturn(expectFactory);
    // when
    final Map<String, String> map = new HashMap<>();
    final Response response = given().contentType(ContentType.JSON).when().body(map).queryParam(VALIDATE_QUERY_PARAMETER, valueOf(true)).post(SERVICE_PATH + "/resolver");
    // then check we have a not found
    assertEquals(response.getStatusCode(), BAD_REQUEST.getStatusCode());
    assertTrue(response.getBody().prettyPrint().contains(invalidFactoryMessage));
    // check we call resolvers
    verify(dummyResolver).accept(anyMapOf(String.class, String.class));
    verify(dummyResolver).createFactory(anyMapOf(String.class, String.class));
    // check we call validator
    verify(acceptValidator).validateOnAccept(any());
}
Also used : Response(com.jayway.restassured.response.Response) HashMap(java.util.HashMap) FactoryDto(org.eclipse.che.api.factory.shared.dto.FactoryDto) BadRequestException(org.eclipse.che.api.core.BadRequestException) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 7 with BadRequestException

use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.

the class FactoryBaseValidator method validateCurrentTimeAfterSinceUntil.

/**
     * Validates correct valid since and until times are used (on factory creation)
     *
     * @param factory
     *         factory to validate
     * @throws BadRequestException
     *         if since date greater or equal than until date
     * @throws BadRequestException
     *         if since date less than current date
     * @throws BadRequestException
     *         if until date less than current date
     */
protected void validateCurrentTimeAfterSinceUntil(FactoryDto factory) throws BadRequestException {
    final PoliciesDto policies = factory.getPolicies();
    if (policies == null) {
        return;
    }
    final Long since = policies.getSince() == null ? 0L : policies.getSince();
    final Long until = policies.getUntil() == null ? 0L : policies.getUntil();
    if (since != 0 && until != 0 && since >= until) {
        throw new BadRequestException(FactoryConstants.INVALID_SINCEUNTIL_MESSAGE);
    }
    if (since != 0 && currentTimeMillis() > since) {
        throw new BadRequestException(FactoryConstants.INVALID_SINCE_MESSAGE);
    }
    if (until != 0 && currentTimeMillis() > until) {
        throw new BadRequestException(FactoryConstants.INVALID_UNTIL_MESSAGE);
    }
}
Also used : BadRequestException(org.eclipse.che.api.core.BadRequestException) PoliciesDto(org.eclipse.che.api.factory.shared.dto.PoliciesDto)

Example 8 with BadRequestException

use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.

the class SshService method createPair.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@GenerateLink(rel = Constants.LINK_REL_CREATE_PAIR)
public Response createPair(Iterator<FileItem> formData) throws BadRequestException, ServerException, ConflictException {
    String service = null;
    String name = null;
    String privateKey = null;
    String publicKey = null;
    while (formData.hasNext()) {
        FileItem item = formData.next();
        String fieldName = item.getFieldName();
        switch(fieldName) {
            case "service":
                service = item.getString();
                break;
            case "name":
                name = item.getString();
                break;
            case "privateKey":
                privateKey = item.getString();
                break;
            case "publicKey":
                publicKey = item.getString();
                break;
            default:
        }
    }
    requiredNotNull(service, "Service name required");
    requiredNotNull(name, "Name required");
    if (privateKey == null && publicKey == null) {
        throw new BadRequestException("Key content was not provided.");
    }
    sshManager.createPair(new SshPairImpl(getCurrentUserId(), service, name, publicKey, privateKey));
    // through specific of html form that doesn't invoke complete submit handler
    return Response.ok("", MediaType.TEXT_HTML).build();
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) SshPairImpl(org.eclipse.che.api.ssh.server.model.impl.SshPairImpl) BadRequestException(org.eclipse.che.api.core.BadRequestException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink)

Example 9 with BadRequestException

use of org.eclipse.che.api.core.BadRequestException 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 10 with BadRequestException

use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.

the class FactoryBaseValidator method validateProjectActions.

/**
     * Validates IDE actions
     *
     * @param factory
     *         factory to validate
     * @throws BadRequestException
     *         when factory actions is invalid
     */
protected void validateProjectActions(FactoryDto factory) throws BadRequestException {
    final IdeDto ide = factory.getIde();
    if (ide == null) {
        return;
    }
    final List<IdeActionDto> applicationActions = new ArrayList<>();
    if (ide.getOnAppClosed() != null) {
        applicationActions.addAll(ide.getOnAppClosed().getActions());
    }
    if (ide.getOnAppLoaded() != null) {
        applicationActions.addAll(ide.getOnAppLoaded().getActions());
    }
    for (IdeActionDto applicationAction : applicationActions) {
        String id = applicationAction.getId();
        if ("openFile".equals(id) || "findReplace".equals(id) || "runCommand".equals(id) || "newTerminal".equals(id)) {
            throw new BadRequestException(format(FactoryConstants.INVALID_ACTION_SECTION, id));
        }
    }
    final OnAppLoadedDto onAppLoaded = ide.getOnAppLoaded();
    if (onAppLoaded != null) {
        for (IdeActionDto action : onAppLoaded.getActions()) {
            final Map<String, String> properties = action.getProperties();
            if ("openWelcomePage".equals(action.getId()) && isNullOrEmpty(properties.get("greetingContentUrl"))) {
                throw new BadRequestException(FactoryConstants.INVALID_WELCOME_PAGE_ACTION);
            }
        }
    }
    final OnProjectsLoadedDto onLoaded = ide.getOnProjectsLoaded();
    if (onLoaded != null) {
        final List<IdeActionDto> onProjectOpenedActions = onLoaded.getActions();
        for (IdeActionDto applicationAction : onProjectOpenedActions) {
            final String id = applicationAction.getId();
            final Map<String, String> properties = applicationAction.getProperties();
            switch(id) {
                case "openFile":
                    if (isNullOrEmpty(properties.get("file"))) {
                        throw new BadRequestException(FactoryConstants.INVALID_OPENFILE_ACTION);
                    }
                    break;
                case "runCommand":
                    if (isNullOrEmpty(properties.get("name"))) {
                        throw new BadRequestException(FactoryConstants.INVALID_RUNCOMMAND_ACTION);
                    }
                    break;
                case "findReplace":
                    if (isNullOrEmpty(properties.get("in")) || isNullOrEmpty(properties.get("find")) || isNullOrEmpty(properties.get("replace"))) {
                        throw new BadRequestException(FactoryConstants.INVALID_FIND_REPLACE_ACTION);
                    }
                    break;
            }
        }
    }
}
Also used : OnAppLoadedDto(org.eclipse.che.api.factory.shared.dto.OnAppLoadedDto) IdeDto(org.eclipse.che.api.factory.shared.dto.IdeDto) IdeActionDto(org.eclipse.che.api.factory.shared.dto.IdeActionDto) ArrayList(java.util.ArrayList) BadRequestException(org.eclipse.che.api.core.BadRequestException) OnProjectsLoadedDto(org.eclipse.che.api.factory.shared.dto.OnProjectsLoadedDto)

Aggregations

BadRequestException (org.eclipse.che.api.core.BadRequestException)20 ServerException (org.eclipse.che.api.core.ServerException)9 ConflictException (org.eclipse.che.api.core.ConflictException)7 NotFoundException (org.eclipse.che.api.core.NotFoundException)7 Consumes (javax.ws.rs.Consumes)6 POST (javax.ws.rs.POST)6 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)6 ApiOperation (io.swagger.annotations.ApiOperation)5 ApiResponses (io.swagger.annotations.ApiResponses)5 IOException (java.io.IOException)5 Map (java.util.Map)5 Produces (javax.ws.rs.Produces)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 GenerateLink (org.eclipse.che.api.core.rest.annotations.GenerateLink)4 Api (io.swagger.annotations.Api)3 ApiParam (io.swagger.annotations.ApiParam)3 ApiResponse (io.swagger.annotations.ApiResponse)3 String.format (java.lang.String.format)3 Collectors.toList (java.util.stream.Collectors.toList)3