Search in sources :

Example 16 with UserDevfile

use of org.eclipse.che.api.core.model.workspace.devfile.UserDevfile in project devspaces-images by redhat-developer.

the class UserDevfileDaoTest method shouldNotUpdateWorkspaceWhichDoesNotExist.

@Test
public void shouldNotUpdateWorkspaceWhichDoesNotExist() throws Exception {
    // given
    final UserDevfileImpl userDevfile = devfiles[0];
    userDevfile.setId("non-existing-devfile");
    // when
    Optional<UserDevfile> result = userDevfileDaoDao.update(userDevfile);
    // then
    assertFalse(result.isPresent());
}
Also used : UserDevfile(org.eclipse.che.api.core.model.workspace.devfile.UserDevfile) TestObjectGenerator.createUserDevfile(org.eclipse.che.api.devfile.server.TestObjectGenerator.createUserDevfile) UserDevfileImpl(org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl) Test(org.testng.annotations.Test)

Example 17 with UserDevfile

use of org.eclipse.che.api.core.model.workspace.devfile.UserDevfile in project devspaces-images by redhat-developer.

the class UserDevfileDaoTest method shouldBeAbleToGetAvailableToUserDevfilesWithFilterAndLimit.

@Test
public void shouldBeAbleToGetAvailableToUserDevfilesWithFilterAndLimit() throws ServerException, NotFoundException, ConflictException {
    // given
    final UserDevfileImpl update = devfiles[0];
    update.setName("New345Name");
    userDevfileDaoDao.update(update);
    // when
    final Page<UserDevfile> result = userDevfileDaoDao.getDevfiles(12, 0, ImmutableList.of(new Pair<>("name", "like:devfileName%")), Collections.emptyList());
    // then
    assertEquals(result.getItems().size(), 9);
}
Also used : UserDevfile(org.eclipse.che.api.core.model.workspace.devfile.UserDevfile) TestObjectGenerator.createUserDevfile(org.eclipse.che.api.devfile.server.TestObjectGenerator.createUserDevfile) UserDevfileImpl(org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl) Pair(org.eclipse.che.commons.lang.Pair) Test(org.testng.annotations.Test)

Example 18 with UserDevfile

use of org.eclipse.che.api.core.model.workspace.devfile.UserDevfile in project devspaces-images by redhat-developer.

the class UserDevfileManager method updateUserDevfile.

/**
 * Updates an existing user devfile in accordance to the new configuration.
 *
 * <p>Note: Replace strategy is used for user devfile update, it means that existing devfile data
 * will be replaced with given {@code update}.
 *
 * @param update user devfile update
 * @return updated user devfile
 * @throws NullPointerException when {@code update} is null
 * @throws ConflictException when any conflict occurs.
 * @throws NotFoundException when user devfile with given id not found
 * @throws ServerException when any server error occurs
 */
public UserDevfile updateUserDevfile(UserDevfile update) throws ConflictException, NotFoundException, ServerException {
    requireNonNull(update);
    Optional<UserDevfile> result = userDevfileDao.update(update);
    UserDevfile devfile = result.orElseThrow(() -> new NotFoundException(format("Devfile with id '%s' doesn't exist", update.getId())));
    LOG.debug("UserDevfile '{}' with id '{}' update by user '{}'", devfile.getName(), devfile.getId(), EnvironmentContext.getCurrent().getSubject().getUserName());
    eventService.publish(new DevfileUpdatedEvent(devfile));
    return devfile;
}
Also used : UserDevfile(org.eclipse.che.api.core.model.workspace.devfile.UserDevfile) NotFoundException(org.eclipse.che.api.core.NotFoundException) DevfileUpdatedEvent(org.eclipse.che.api.devfile.shared.event.DevfileUpdatedEvent)

Example 19 with UserDevfile

use of org.eclipse.che.api.core.model.workspace.devfile.UserDevfile in project devspaces-images by redhat-developer.

the class JpaUserDevfileDao method doGetDevfiles.

@Transactional(rollbackOn = { ServerException.class })
protected Page<UserDevfile> doGetDevfiles(int maxItems, int skipCount, List<Pair<String, String>> filter, List<Pair<String, String>> order, Supplier<UserDevfileSearchQueryBuilder> queryBuilderSupplier) throws ServerException {
    if (filter != null && !filter.isEmpty()) {
        List<Pair<String, String>> invalidFilter = filter.stream().filter(p -> !VALID_SEARCH_FIELDS.contains(p.first.toLowerCase())).collect(toList());
        if (!invalidFilter.isEmpty()) {
            throw new IllegalArgumentException("Filtering allowed only by " + VALID_SEARCH_FIELDS + " but got: " + invalidFilter);
        }
    }
    List<Pair<String, String>> effectiveOrder = DEFAULT_ORDER;
    if (order != null && !order.isEmpty()) {
        List<Pair<String, String>> invalidOrder = order.stream().filter(p -> !VALID_ORDER_FIELDS.contains(p.first.toLowerCase())).collect(toList());
        if (!invalidOrder.isEmpty()) {
            throw new IllegalArgumentException("Order allowed only by " + VALID_ORDER_FIELDS + "¬ but got: " + invalidOrder);
        }
        List<Pair<String, String>> invalidSortOrder = order.stream().filter(p -> !p.second.equalsIgnoreCase("asc") && !p.second.equalsIgnoreCase("desc")).collect(Collectors.toList());
        if (!invalidSortOrder.isEmpty()) {
            throw new IllegalArgumentException("Invalid sort order direction. Possible values are 'asc' or 'desc' but got: " + invalidSortOrder);
        }
        effectiveOrder = order;
    }
    try {
        final long count = queryBuilderSupplier.get().withFilter(filter).buildCountQuery().getSingleResult();
        if (count == 0) {
            return new Page<>(emptyList(), skipCount, maxItems, count);
        }
        List<UserDevfileImpl> result = queryBuilderSupplier.get().withFilter(filter).withOrder(effectiveOrder).withMaxItems(maxItems).withSkipCount(skipCount).buildSelectItemsQuery().getResultList().stream().map(UserDevfileImpl::new).collect(toList());
        return new Page<>(result, skipCount, maxItems, count);
    } catch (RuntimeException x) {
        throw new ServerException(x.getLocalizedMessage(), x);
    }
}
Also used : Provider(javax.inject.Provider) Supplier(com.google.common.base.Supplier) Page(org.eclipse.che.api.core.Page) UserDevfileDao(org.eclipse.che.api.devfile.server.spi.UserDevfileDao) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) TypedQuery(javax.persistence.TypedQuery) UserDevfileImpl(org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl) BeforeDevfileRemovedEvent(org.eclipse.che.api.devfile.server.event.BeforeDevfileRemovedEvent) Transactional(com.google.inject.persist.Transactional) Inject(javax.inject.Inject) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) ConflictException(org.eclipse.che.api.core.ConflictException) Account(org.eclipse.che.account.shared.model.Account) UserDevfile(org.eclipse.che.api.core.model.workspace.devfile.UserDevfile) EventService(org.eclipse.che.api.core.notification.EventService) ImmutableSet(com.google.common.collect.ImmutableSet) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) Pair(org.eclipse.che.commons.lang.Pair) String.format(java.lang.String.format) NotFoundException(org.eclipse.che.api.core.NotFoundException) Beta(com.google.common.annotations.Beta) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) AccountDao(org.eclipse.che.account.spi.AccountDao) ServerException(org.eclipse.che.api.core.ServerException) DuplicateKeyException(org.eclipse.che.core.db.jpa.DuplicateKeyException) IntegrityConstraintViolationException(org.eclipse.che.core.db.jpa.IntegrityConstraintViolationException) StringJoiner(java.util.StringJoiner) Optional(java.util.Optional) UserDevfileSearchQueryBuilder.newBuilder(org.eclipse.che.api.devfile.server.jpa.JpaUserDevfileDao.UserDevfileSearchQueryBuilder.newBuilder) ServerException(org.eclipse.che.api.core.ServerException) UserDevfileImpl(org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl) Page(org.eclipse.che.api.core.Page) Pair(org.eclipse.che.commons.lang.Pair) Transactional(com.google.inject.persist.Transactional)

Example 20 with UserDevfile

use of org.eclipse.che.api.core.model.workspace.devfile.UserDevfile in project devspaces-images by redhat-developer.

the class DevfileService method getUserDevfiles.

@GET
@Path("search")
@Produces(APPLICATION_JSON)
@Operation(summary = "Get devfiles which user can read. This operation can be performed only by authorized user. " + "It is possible to add additional constraints for the desired devfiles by specifying\n" + "multiple query parameters that is representing fields of the devfile. All constrains\n" + "would be combined with \"And\" condition. Also, it is possible to specify 'like:' prefix\n" + "for the query parameters. In this case instead of an exact match would be used SQL pattern like search.\n" + "Examples id=sdfsdf5&devfile.meta.name=like:%dfdf&", responses = { @ApiResponse(responseCode = "200", description = "The devfiles successfully fetched", content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserDevfileDto.class)))), @ApiResponse(responseCode = "500", description = "Internal server error occurred during devfiles fetching") })
public Response getUserDevfiles(@Parameter(description = "The number of the items to skip") @DefaultValue("0") @QueryParam("skipCount") Integer skipCount, @Parameter(description = "The limit of the items in the response, default is 30, maximum 60") @DefaultValue("30") @QueryParam("maxItems") Integer maxItems, @Parameter(description = "A list of fields and directions of sort. By default items would be sorted by id. Example id:asc,name:desc.") @QueryParam("order") String order) throws ServerException, BadRequestException {
    final Set<String> skip = ImmutableSet.of("token", "skipCount", "maxItems", "order");
    Map<String, Set<String>> queryParams = URLEncodedUtils.parse(uriInfo.getRequestUri());
    final List<Pair<String, String>> query = queryParams.entrySet().stream().filter(param -> !param.getValue().isEmpty()).filter(param -> !skip.contains(param.getKey())).map(entry -> Pair.of(entry.getKey(), entry.getValue().iterator().next())).collect(toList());
    List<Pair<String, String>> searchOrder = Collections.emptyList();
    if (order != null && !order.isEmpty()) {
        try {
            searchOrder = Splitter.on(",").trimResults().omitEmptyStrings().withKeyValueSeparator(":").split(order).entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue())).collect(toList());
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("Invalid `order` query parameter format." + e.getMessage());
        }
    }
    Page<? extends UserDevfile> userDevfilesPage = userDevfileManager.getUserDevfiles(maxItems, skipCount, query, searchOrder);
    List<UserDevfileDto> list = userDevfilesPage.getItems().stream().map(DtoConverter::asDto).map(dto -> linksInjector.injectLinks(asDto(dto), getServiceContext())).collect(toList());
    return Response.ok().entity(list).header("Link", createLinkHeader(userDevfilesPage)).build();
}
Also used : URLEncodedUtils(org.eclipse.che.commons.lang.URLEncodedUtils) DtoConverter.asDto(org.eclipse.che.api.devfile.server.DtoConverter.asDto) DefaultValue(jakarta.ws.rs.DefaultValue) Page(org.eclipse.che.api.core.Page) GET(jakarta.ws.rs.GET) PUT(jakarta.ws.rs.PUT) Path(jakarta.ws.rs.Path) Inject(javax.inject.Inject) Content(io.swagger.v3.oas.annotations.media.Content) DevfileSchemaProvider(org.eclipse.che.api.workspace.server.devfile.schema.DevfileSchemaProvider) Operation(io.swagger.v3.oas.annotations.Operation) Response(jakarta.ws.rs.core.Response) Service(org.eclipse.che.api.core.rest.Service) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) Map(java.util.Map) CURRENT_API_VERSION(org.eclipse.che.api.workspace.server.devfile.Constants.CURRENT_API_VERSION) ConflictException(org.eclipse.che.api.core.ConflictException) Produces(jakarta.ws.rs.Produces) UserDevfile(org.eclipse.che.api.core.model.workspace.devfile.UserDevfile) Splitter(com.google.common.base.Splitter) NameGenerator(org.eclipse.che.commons.lang.NameGenerator) DtoFactory(org.eclipse.che.dto.server.DtoFactory) Schema(io.swagger.v3.oas.annotations.media.Schema) Consumes(jakarta.ws.rs.Consumes) DevfileDto(org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto) ImmutableSet(com.google.common.collect.ImmutableSet) POST(jakarta.ws.rs.POST) Set(java.util.Set) IOException(java.io.IOException) SUPPORTED_VERSIONS(org.eclipse.che.api.workspace.server.devfile.Constants.SUPPORTED_VERSIONS) Pair(org.eclipse.che.commons.lang.Pair) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) Parameter(io.swagger.v3.oas.annotations.Parameter) UserDevfileDto(org.eclipse.che.api.devfile.shared.dto.UserDevfileDto) Collectors.toList(java.util.stream.Collectors.toList) ArraySchema(io.swagger.v3.oas.annotations.media.ArraySchema) List(java.util.List) BadRequestException(org.eclipse.che.api.core.BadRequestException) ServerException(org.eclipse.che.api.core.ServerException) Tag(io.swagger.v3.oas.annotations.tags.Tag) APPLICATION_JSON(jakarta.ws.rs.core.MediaType.APPLICATION_JSON) QueryParam(jakarta.ws.rs.QueryParam) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) DELETE(jakarta.ws.rs.DELETE) PathParam(jakarta.ws.rs.PathParam) Collections(java.util.Collections) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) BadRequestException(org.eclipse.che.api.core.BadRequestException) UserDevfileDto(org.eclipse.che.api.devfile.shared.dto.UserDevfileDto) Pair(org.eclipse.che.commons.lang.Pair) Path(jakarta.ws.rs.Path) Produces(jakarta.ws.rs.Produces) GET(jakarta.ws.rs.GET) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

UserDevfile (org.eclipse.che.api.core.model.workspace.devfile.UserDevfile)34 Test (org.testng.annotations.Test)24 UserDevfileImpl (org.eclipse.che.api.devfile.server.model.impl.UserDevfileImpl)22 TestObjectGenerator.createUserDevfile (org.eclipse.che.api.devfile.server.TestObjectGenerator.createUserDevfile)20 NotFoundException (org.eclipse.che.api.core.NotFoundException)10 Pair (org.eclipse.che.commons.lang.Pair)8 ImmutableSet (com.google.common.collect.ImmutableSet)4 List (java.util.List)4 Map (java.util.Map)4 Set (java.util.Set)4 Collectors.toList (java.util.stream.Collectors.toList)4 Inject (javax.inject.Inject)4 ConflictException (org.eclipse.che.api.core.ConflictException)3 Page (org.eclipse.che.api.core.Page)3 ServerException (org.eclipse.che.api.core.ServerException)3 Beta (com.google.common.annotations.Beta)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 Splitter (com.google.common.base.Splitter)2 Supplier (com.google.common.base.Supplier)2 ImmutableList (com.google.common.collect.ImmutableList)2