use of org.eclipse.che.api.core.BadRequestException 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();
}
}
use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.
the class WsAgentLauncher method launch.
@Override
public void launch(Instance machine, Agent agent) throws ServerException {
final HttpJsonRequest wsAgentPingRequest;
try {
wsAgentPingRequest = createPingRequest(machine);
} catch (ServerException e) {
throw new MachineException(e.getServiceError());
}
String script = agent.getScript() + "\n" + firstNonNull(wsAgentRunCommand, DEFAULT_WS_AGENT_RUN_COMMAND);
final String wsAgentPingUrl = wsAgentPingRequest.getUrl();
try {
// for server side type of command mean nothing
// but we will use it as marker on
// client side for track this command
CommandImpl command = new CommandImpl(getAgentId(), script, WS_AGENT_PROCESS_NAME);
machineProcessManagerProvider.get().exec(machine.getWorkspaceId(), machine.getId(), command, getWsAgentProcessOutputChannel(machine.getWorkspaceId()));
final long pingStartTimestamp = System.currentTimeMillis();
LOG.debug("Starts pinging ws agent. Workspace ID:{}. Url:{}. Timestamp:{}", machine.getWorkspaceId(), wsAgentPingUrl, pingStartTimestamp);
while (System.currentTimeMillis() - pingStartTimestamp < wsAgentMaxStartTimeMs) {
if (pingWsAgent(wsAgentPingRequest)) {
return;
} else {
Thread.sleep(wsAgentPingDelayMs);
}
}
} catch (BadRequestException | ServerException | NotFoundException e) {
throw new ServerException(e.getServiceError());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ServerException("Ws agent pinging is interrupted");
}
LOG.error("Fail pinging ws agent. Workspace ID:{}. Url:{}. Timestamp:{}", machine.getWorkspaceId(), wsAgentPingUrl);
throw new ServerException(pingTimedOutErrorMessage);
}
use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.
the class FactoryService method getFactoryByAttribute.
@GET
@Path("/find")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Get factory by attribute, " + "the attribute must match one of the Factory model fields with type 'String', " + "e.g. (factory.name, factory.creator.name)", notes = "If specify more than one value for a single query parameter then will be taken the first one")
@ApiResponses({ @ApiResponse(code = 200, message = "Response contains list requested factories"), @ApiResponse(code = 400, message = "When query does not contain at least one attribute to search for"), @ApiResponse(code = 500, message = "Internal server error") })
public List<FactoryDto> getFactoryByAttribute(@DefaultValue("0") @QueryParam("skipCount") Integer skipCount, @DefaultValue("30") @QueryParam("maxItems") Integer maxItems, @Context UriInfo uriInfo) throws BadRequestException, ServerException {
final Set<String> skip = ImmutableSet.of("token", "skipCount", "maxItems");
final List<Pair<String, String>> query = URLEncodedUtils.parse(uriInfo.getRequestUri()).entrySet().stream().filter(param -> !skip.contains(param.getKey()) && !param.getValue().isEmpty()).map(entry -> Pair.of(entry.getKey(), entry.getValue().iterator().next())).collect(toList());
checkArgument(!query.isEmpty(), "Query must contain at least one attribute");
final List<FactoryDto> factories = new ArrayList<>();
for (Factory factory : factoryManager.getByAttribute(maxItems, skipCount, query)) {
factories.add(injectLinks(asDto(factory), null));
}
return factories;
}
use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.
the class DefaultWorkspaceValidator method validateConfig.
@Override
public void validateConfig(WorkspaceConfig config) throws BadRequestException, ServerException {
// configuration object itself
checkNotNull(config.getName(), "Workspace name required");
checkArgument(WS_NAME.matcher(config.getName()).matches(), "Incorrect workspace name, it must be between 3 and 20 characters and may contain digits, " + "latin letters, underscores, dots, dashes and should start and end only with digits, " + "latin letters or underscores");
//environments
checkArgument(!isNullOrEmpty(config.getDefaultEnv()), "Workspace default environment name required");
checkNotNull(config.getEnvironments(), "Workspace should contain at least one environment");
checkArgument(config.getEnvironments().containsKey(config.getDefaultEnv()), "Workspace default environment configuration required");
for (Map.Entry<String, ? extends Environment> envEntry : config.getEnvironments().entrySet()) {
try {
environmentValidator.validate(envEntry.getKey(), envEntry.getValue());
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getLocalizedMessage());
}
}
//commands
for (Command command : config.getCommands()) {
checkArgument(!isNullOrEmpty(command.getName()), "Workspace %s contains command with null or empty name", config.getName());
checkArgument(!isNullOrEmpty(command.getCommandLine()), "Command line required for command '%s' in workspace '%s'", command.getName(), config.getName());
}
//projects
//TODO
}
use of org.eclipse.che.api.core.BadRequestException in project che by eclipse.
the class WorkspaceService method updateCommand.
@PUT
@Path("/{id}/command/{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Update the workspace command by replacing the command with a new one", notes = "This operation can be performed only by the workspace owner")
@ApiResponses({ @ApiResponse(code = 200, message = "The command successfully updated"), @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"), @ApiResponse(code = 403, message = "The user does not have access to update the workspace"), @ApiResponse(code = 404, message = "The workspace or the command not found"), @ApiResponse(code = 409, message = "The Command with such name already exists"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public WorkspaceDto updateCommand(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The name of the command") @PathParam("name") String cmdName, @ApiParam(value = "The command update", required = true) CommandDto update) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException {
requiredNotNull(update, "Command update");
final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
final List<CommandImpl> commands = workspace.getConfig().getCommands();
if (!commands.removeIf(cmd -> cmd.getName().equals(cmdName))) {
throw new NotFoundException(format("Workspace '%s' doesn't contain command '%s'", id, cmdName));
}
commands.add(new CommandImpl(update));
validator.validateConfig(workspace.getConfig());
return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(workspace.getId(), workspace)), getServiceContext());
}
Aggregations