Search in sources :

Example 11 with ConflictException

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

the class UserDaoTest method shouldNotCreateUserWhenSubscriberThrowsExceptionOnUserStoring.

@Test(dependsOnMethods = "shouldThrowNotFoundExceptionWhenGettingNonExistingUserById", expectedExceptions = NotFoundException.class)
public void shouldNotCreateUserWhenSubscriberThrowsExceptionOnUserStoring() throws Exception {
    final UserImpl newUser = new UserImpl("user123", "user123@eclipse.org", "user_name", "password", asList("google:user123", "github:user123"));
    CascadeEventSubscriber<PostUserPersistedEvent> subscriber = mockCascadeEventSubscriber();
    doThrow(new ConflictException("error")).when(subscriber).onCascadeEvent(any());
    eventService.subscribe(subscriber, PostUserPersistedEvent.class);
    try {
        userDao.create(newUser);
        fail("UserDao#create had to throw conflict exception");
    } catch (ConflictException ignored) {
    }
    eventService.unsubscribe(subscriber, PostUserPersistedEvent.class);
    userDao.getById(newUser.getId());
}
Also used : PostUserPersistedEvent(org.eclipse.che.api.user.server.event.PostUserPersistedEvent) ConflictException(org.eclipse.che.api.core.ConflictException) UserImpl(org.eclipse.che.api.user.server.model.impl.UserImpl) Test(org.testng.annotations.Test)

Example 12 with ConflictException

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

the class ProjectManager method createBatchProjects.

/**
     * Create batch of projects according to their configurations.
     * <p/>
     * Notes: - a project will be created by importing when project configuration contains {@link SourceStorage} object,
     * otherwise this one will be created corresponding its {@link NewProjectConfig}:
     * <li> - {@link NewProjectConfig} object contains only one mandatory {@link NewProjectConfig#setPath(String)} field.
     * In this case Project will be created as project of {@link BaseProjectType} type </li>
     * <li> - a project will be created as project of {@link BaseProjectType} type with {@link Problem#code} = 12
     * when declared primary project type is not registered, </li>
     * <li> - a project will be created with {@link Problem#code} = 12 and without mixin project type
     * when declared mixin project type is not registered</li>
     * <li> - for creating a project by generator {@link NewProjectConfig#getOptions()} should be specified.</li>
     *
     * @param projectConfigList
     *         the list of configurations to create projects
     * @param rewrite
     *         whether rewrite or not (throw exception otherwise) if such a project exists
     * @return the list of new projects
     * @throws BadRequestException
     *         when {@link NewProjectConfig} object not contains mandatory {@link NewProjectConfig#setPath(String)} field.
     * @throws ConflictException
     *         when the same path project exists and {@code rewrite} is {@code false}
     * @throws ForbiddenException
     *         when trying to overwrite the project and this one contains at least one locked file
     * @throws NotFoundException
     *         when parent folder does not exist
     * @throws UnauthorizedException
     *         if user isn't authorized to access to location at importing source code
     * @throws ServerException
     *         if other error occurs
     */
public List<RegisteredProject> createBatchProjects(List<? extends NewProjectConfig> projectConfigList, boolean rewrite, ProjectOutputLineConsumerFactory lineConsumerFactory) throws BadRequestException, ConflictException, ForbiddenException, NotFoundException, ServerException, UnauthorizedException, IOException {
    fileWatcherManager.suspend();
    try {
        final List<RegisteredProject> projects = new ArrayList<>(projectConfigList.size());
        validateProjectConfigurations(projectConfigList, rewrite);
        final List<NewProjectConfig> sortedConfigList = projectConfigList.stream().sorted((config1, config2) -> config1.getPath().compareTo(config2.getPath())).collect(Collectors.toList());
        for (NewProjectConfig projectConfig : sortedConfigList) {
            RegisteredProject registeredProject;
            final String pathToProject = projectConfig.getPath();
            //creating project(by config or by importing source code)
            try {
                final SourceStorage sourceStorage = projectConfig.getSource();
                if (sourceStorage != null && !isNullOrEmpty(sourceStorage.getLocation())) {
                    doImportProject(pathToProject, sourceStorage, rewrite, lineConsumerFactory.setProjectName(projectConfig.getPath()));
                } else if (!isVirtualFileExist(pathToProject)) {
                    registeredProject = doCreateProject(projectConfig, projectConfig.getOptions());
                    projects.add(registeredProject);
                    continue;
                }
            } catch (Exception e) {
                if (!isVirtualFileExist(pathToProject)) {
                    //project folder is absent
                    rollbackCreatingBatchProjects(projects);
                    throw e;
                }
            }
            //update project
            if (isVirtualFileExist(pathToProject)) {
                try {
                    registeredProject = updateProject(projectConfig);
                } catch (Exception e) {
                    registeredProject = projectRegistry.putProject(projectConfig, asFolder(pathToProject), true, false);
                    final Problem problem = new Problem(NOT_UPDATED_PROJECT, "The project is not updated, caused by " + e.getLocalizedMessage());
                    registeredProject.getProblems().add(problem);
                }
            } else {
                registeredProject = projectRegistry.putProject(projectConfig, null, true, false);
            }
            projects.add(registeredProject);
        }
        return projects;
    } finally {
        fileWatcherManager.resume();
    }
}
Also used : LineConsumerFactory(org.eclipse.che.api.core.util.LineConsumerFactory) VirtualFileSystemProvider(org.eclipse.che.api.vfs.VirtualFileSystemProvider) Path(org.eclipse.che.api.vfs.Path) LoggerFactory(org.slf4j.LoggerFactory) ProjectTypeRegistry(org.eclipse.che.api.project.server.type.ProjectTypeRegistry) FileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.FileWatcherNotificationHandler) ProjectHandlerRegistry(org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry) PreDestroy(javax.annotation.PreDestroy) FileWatcherManager(org.eclipse.che.api.vfs.watcher.FileWatcherManager) CreateProjectHandler(org.eclipse.che.api.project.server.handlers.CreateProjectHandler) Map(java.util.Map) PathMatcher(java.nio.file.PathMatcher) LoggingUncaughtExceptionHandler(org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) NOT_UPDATED_PROJECT(org.eclipse.che.api.core.ErrorCodes.NOT_UPDATED_PROJECT) SourceStorage(org.eclipse.che.api.core.model.project.SourceStorage) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) List(java.util.List) BadRequestException(org.eclipse.che.api.core.BadRequestException) ProjectConfig(org.eclipse.che.api.core.model.project.ProjectConfig) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) ProjectTypeResolution(org.eclipse.che.api.project.server.type.ProjectTypeResolution) BaseProjectType(org.eclipse.che.api.project.server.type.BaseProjectType) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) ProjectImporterRegistry(org.eclipse.che.api.project.server.importer.ProjectImporterRegistry) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) FileTreeWatcher(org.eclipse.che.api.vfs.impl.file.FileTreeWatcher) Inject(javax.inject.Inject) AttributeValue(org.eclipse.che.api.project.server.type.AttributeValue) VirtualFile(org.eclipse.che.api.vfs.VirtualFile) Searcher(org.eclipse.che.api.vfs.search.Searcher) FileWatcherEventType(org.eclipse.che.api.project.shared.dto.event.FileWatcherEventType) ConflictException(org.eclipse.che.api.core.ConflictException) SearcherProvider(org.eclipse.che.api.vfs.search.SearcherProvider) ProjectTypeDef(org.eclipse.che.api.project.server.type.ProjectTypeDef) VirtualFileSystem(org.eclipse.che.api.vfs.VirtualFileSystem) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) ProjectImporter(org.eclipse.che.api.project.server.importer.ProjectImporter) IOException(java.io.IOException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ProjectType(org.eclipse.che.api.core.model.project.type.ProjectType) ServerException(org.eclipse.che.api.core.ServerException) Problem(org.eclipse.che.api.project.server.RegisteredProject.Problem) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) NewProjectConfig(org.eclipse.che.api.core.model.project.NewProjectConfig) FileWatcherNotificationListener(org.eclipse.che.api.vfs.impl.file.FileWatcherNotificationListener) SourceStorage(org.eclipse.che.api.core.model.project.SourceStorage) ArrayList(java.util.ArrayList) Problem(org.eclipse.che.api.project.server.RegisteredProject.Problem) NewProjectConfig(org.eclipse.che.api.core.model.project.NewProjectConfig) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) BadRequestException(org.eclipse.che.api.core.BadRequestException) ConflictException(org.eclipse.che.api.core.ConflictException) IOException(java.io.IOException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ServerException(org.eclipse.che.api.core.ServerException) ForbiddenException(org.eclipse.che.api.core.ForbiddenException)

Example 13 with ConflictException

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

the class ProjectRegistry method setProjectType.

/*  ------------------------------------------ */
/*   to use from extension                     */
/*  ------------------------------------------ */
/**
     * Extension writer should call this method to apply changes which (supposedly) change
     * Attributes defined with particular Project Type
     * If incoming Project Type is primary and:
     * - If the folder located on projectPath is a Project, its Primary PT will be converted to incoming PT
     * - If the folder located on projectPath is NOT a Project the folder will be converted to "detected" Project with incoming Primary PT
     * If incoming Project Type is mixin and:
     * - If the folder located on projectPath is a Project, this PT will be added (if not already there) to its Mixin PTs
     * - If the folder located on projectPath is NOT a Project - ConflictException will be thrown
     * For example:
     * - extension code knows that particular file content is used by Value Provider
     * so this method should be called when content of this file changed to check
     * and update attributes.
     * OR
     * If Extension writer wants to force initializing folder to be Project
     * For example:
     * - extension code knows that particular folder inside should (or may) be treated
     * as sub-project of same as "parent" project type
     *
     * @param projectPath
     *         absolute project path
     * @param type
     *         type to be updated or added
     * @param asMixin
     *         whether the type supposed to be mixin (true) or primary (false)
     * @return refreshed project
     * @throws ConflictException
     * @throws NotFoundException
     * @throws ServerException
     */
public RegisteredProject setProjectType(String projectPath, String type, boolean asMixin) throws ConflictException, NotFoundException, ServerException {
    final RegisteredProject project = getProject(projectPath);
    final NewProjectConfig conf;
    List<String> newMixins = new ArrayList<>();
    if (project == null) {
        if (asMixin) {
            throw new ConflictException("Can not assign as mixin type '" + type + "' since the " + projectPath + " is not a project.");
        } else {
            final String path = absolutizePath(projectPath);
            final String name = Path.of(projectPath).getName();
            conf = new NewProjectConfigImpl(path, type, newMixins, name, name, null, null, null);
            return putProject(conf, root.getChildFolder(path), true, true);
        }
    } else {
        newMixins = project.getMixins();
        String newType = project.getType();
        if (asMixin) {
            if (!newMixins.contains(type)) {
                newMixins.add(type);
            }
        } else {
            newType = type;
        }
        conf = new NewProjectConfigImpl(project.getPath(), newType, newMixins, project.getName(), project.getDescription(), project.getAttributes(), null, project.getSource());
        return putProject(conf, project.getBaseFolder(), true, project.isDetected());
    }
}
Also used : ConflictException(org.eclipse.che.api.core.ConflictException) ArrayList(java.util.ArrayList) NewProjectConfig(org.eclipse.che.api.core.model.project.NewProjectConfig)

Example 14 with ConflictException

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

the class ProjectService method uploadFile.

/* --------------------------------------------------------------------------- */
/* TODO check "upload" methods below, they were copied from old VFS as is      */
/* --------------------------------------------------------------------------- */
private static Response uploadFile(VirtualFile parent, Iterator<FileItem> formData) throws ForbiddenException, ConflictException, ServerException {
    try {
        FileItem contentItem = null;
        String name = null;
        boolean overwrite = false;
        while (formData.hasNext()) {
            FileItem item = formData.next();
            if (!item.isFormField()) {
                if (contentItem == null) {
                    contentItem = item;
                } else {
                    throw new ServerException("More then one upload file is found but only one should be. ");
                }
            } else if ("name".equals(item.getFieldName())) {
                name = item.getString().trim();
            } else if ("overwrite".equals(item.getFieldName())) {
                overwrite = Boolean.parseBoolean(item.getString().trim());
            }
        }
        if (contentItem == null) {
            throw new ServerException("Cannot find file for upload. ");
        }
        if (name == null || name.isEmpty()) {
            name = contentItem.getName();
        }
        try {
            try {
                parent.createFile(name, contentItem.getInputStream());
            } catch (ConflictException e) {
                if (!overwrite) {
                    throw new ConflictException("Unable upload file. Item with the same name exists. ");
                }
                parent.getChild(org.eclipse.che.api.vfs.Path.of(name)).updateContent(contentItem.getInputStream(), null);
            }
        } catch (IOException ioe) {
            throw new ServerException(ioe.getMessage(), ioe);
        }
        return Response.ok("", MediaType.TEXT_HTML).build();
    } catch (ForbiddenException | ConflictException | ServerException e) {
        HtmlErrorFormatter.sendErrorAsHTML(e);
        // never thrown
        throw e;
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) IOException(java.io.IOException)

Example 15 with ConflictException

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

the class ProjectService method search.

@GET
@Path("/search/{path:.*}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Search for resources", notes = "Search for resources applying a number of search filters as query parameters", response = ItemReference.class, responseContainer = "List")
@ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "User not authorized to call this operation"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 409, message = "Conflict error"), @ApiResponse(code = 500, message = "Internal Server Error") })
public List<ItemReference> search(@ApiParam(value = "Path to resource, i.e. where to search?", required = true) @PathParam("path") String path, @ApiParam(value = "Resource name") @QueryParam("name") String name, @ApiParam(value = "Search keywords") @QueryParam("text") String text, @ApiParam(value = "Maximum items to display. If this parameter is dropped, there are no limits") @QueryParam("maxItems") @DefaultValue("-1") int maxItems, @ApiParam(value = "Skip count") @QueryParam("skipCount") int skipCount) throws NotFoundException, ForbiddenException, ConflictException, ServerException {
    final Searcher searcher;
    try {
        searcher = projectManager.getSearcher();
    } catch (NotFoundException e) {
        LOG.warn(e.getLocalizedMessage());
        return Collections.emptyList();
    }
    if (skipCount < 0) {
        throw new ConflictException(String.format("Invalid 'skipCount' parameter: %d.", skipCount));
    }
    final QueryExpression expr = new QueryExpression().setPath(path.startsWith("/") ? path : ('/' + path)).setName(name).setText(text).setMaxItems(maxItems).setSkipCount(skipCount);
    final SearchResult result = searcher.search(expr);
    final List<SearchResultEntry> searchResultEntries = result.getResults();
    final List<ItemReference> items = new ArrayList<>(searchResultEntries.size());
    final FolderEntry root = projectManager.getProjectsRoot();
    for (SearchResultEntry searchResultEntry : searchResultEntries) {
        final VirtualFileEntry child = root.getChild(searchResultEntry.getFilePath());
        if (child != null && child.isFile()) {
            items.add(injectFileLinks(asDto((FileEntry) child)));
        }
    }
    return items;
}
Also used : ItemReference(org.eclipse.che.api.project.shared.dto.ItemReference) ConflictException(org.eclipse.che.api.core.ConflictException) Searcher(org.eclipse.che.api.vfs.search.Searcher) ArrayList(java.util.ArrayList) NotFoundException(org.eclipse.che.api.core.NotFoundException) SearchResult(org.eclipse.che.api.vfs.search.SearchResult) QueryExpression(org.eclipse.che.api.vfs.search.QueryExpression) SearchResultEntry(org.eclipse.che.api.vfs.search.SearchResultEntry) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

ConflictException (org.eclipse.che.api.core.ConflictException)81 VirtualFile (org.eclipse.che.api.vfs.VirtualFile)28 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)25 ServerException (org.eclipse.che.api.core.ServerException)24 Test (org.junit.Test)24 NotFoundException (org.eclipse.che.api.core.NotFoundException)17 Path (org.eclipse.che.api.vfs.Path)12 IOException (java.io.IOException)10 NewProjectConfig (org.eclipse.che.api.core.model.project.NewProjectConfig)8 Unlocker (org.eclipse.che.commons.lang.concurrent.Unlocker)8 ArrayList (java.util.ArrayList)7 BadRequestException (org.eclipse.che.api.core.BadRequestException)7 MachineException (org.eclipse.che.api.machine.server.exception.MachineException)7 File (java.io.File)6 ProjectConfig (org.eclipse.che.api.core.model.project.ProjectConfig)6 CommandImpl (org.eclipse.che.api.machine.server.model.impl.CommandImpl)6 List (java.util.List)5 Map (java.util.Map)5 WorkspaceImpl (org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl)5 String.format (java.lang.String.format)4