Java Code Examples for org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl#getConfig()

The following examples show how to use org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl#getConfig() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LimitsCheckingWorkspaceManager.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public WorkspaceImpl startWorkspace(
    String workspaceId, @Nullable String envName, @Nullable Map<String, String> options)
    throws NotFoundException, ServerException, ConflictException {
  WorkspaceImpl workspace = this.getWorkspace(workspaceId);
  String accountId = workspace.getAccount().getId();
  WorkspaceConfigImpl config = workspace.getConfig();

  try (@SuppressWarnings("unused")
      Unlocker u = resourcesLocks.lock(accountId)) {
    checkRuntimeResourceAvailability(accountId);
    if (config != null) {
      checkRamResourcesAvailability(accountId, workspace.getNamespace(), config, envName);
    }

    return super.startWorkspace(workspaceId, envName, options);
  }
}
 
Example 2
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@DELETE
@Path("/{id}/environment/{name}")
@ApiOperation(
    value = "Remove the environment from the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The environment successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access remove the environment"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void deleteEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the environment") @PathParam("name") String envName)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  if (workspace.getConfig().getEnvironments().remove(envName) != null) {
    doUpdate(id, workspace);
  }
}
 
Example 3
Source File: MultiuserJpaWorkspaceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected WorkspaceImpl doUpdate(WorkspaceImpl update) throws NotFoundException {
  EntityManager manager = managerProvider.get();
  if (manager.find(WorkspaceImpl.class, update.getId()) == null) {
    throw new NotFoundException(format("Workspace with id '%s' doesn't exist", update.getId()));
  }
  if (update.getConfig() != null) {
    update.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
  }
  WorkspaceImpl merged = manager.merge(update);
  manager.flush();
  return merged;
}
 
Example 4
Source File: WorkspaceManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Updates an existing workspace with a new configuration.
 *
 * <p>
 *
 * <p>Replace strategy is used for workspace update, it means that existing workspace data will be
 * replaced with given {@code update}.
 *
 * @param update workspace update
 * @return updated instance of the workspace
 * @throws NullPointerException when either {@code workspaceId} or {@code update} is null
 * @throws NotFoundException when workspace with given id doesn't exist
 * @throws ConflictException when any conflict occurs (e.g Workspace with such name already exists
 *     in {@code namespace})
 * @throws ServerException when any other error occurs
 */
public WorkspaceImpl updateWorkspace(String id, Workspace update)
    throws ConflictException, ServerException, NotFoundException, ValidationException {
  requireNonNull(id, "Required non-null workspace id");
  requireNonNull(update, "Required non-null workspace update");
  checkArgument(
      update.getConfig() != null ^ update.getDevfile() != null,
      "Required non-null workspace configuration or devfile update but not both");
  if (update.getConfig() != null) {
    validator.validateConfig(update.getConfig());
  }
  WorkspaceImpl workspace = workspaceDao.get(id);

  validator.validateUpdateAttributes(workspace.getAttributes(), update.getAttributes());

  if (workspace.getConfig() != null) {
    workspace.setConfig(new WorkspaceConfigImpl(update.getConfig()));
  }
  if (workspace.getDevfile() != null) {
    workspace.setDevfile(new DevfileImpl(update.getDevfile()));
  }

  workspace.setAttributes(update.getAttributes());

  workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis()));
  workspace.setTemporary(update.isTemporary());

  return normalizeState(workspaceDao.update(workspace), true);
}
 
Example 5
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@DELETE
@Path("/{id}/project/{path:.*}")
@ApiOperation(
    value = "Remove the project from the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The project successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access remove the project"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void deleteProject(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the project to remove") @PathParam("path") String path)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  final String normalizedPath = path.startsWith("/") ? path : '/' + path;
  if (workspace
      .getConfig()
      .getProjects()
      .removeIf(project -> project.getPath().equals(normalizedPath))) {
    doUpdate(id, workspace);
  }
}
 
Example 6
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/project/{path:.*}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Update the workspace project by replacing it with a new one",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The project 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 project"),
  @ApiResponse(code = 404, message = "The workspace or the project not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto updateProject(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The path to the project") @PathParam("path") String path,
    @ApiParam(value = "The project update", required = true) ProjectConfigDto update)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(update, "Project config");
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  final List<ProjectConfigImpl> projects = workspace.getConfig().getProjects();
  final String normalizedPath = path.startsWith("/") ? path : '/' + path;
  if (!projects.removeIf(project -> project.getPath().equals(normalizedPath))) {
    throw new NotFoundException(
        format("Workspace '%s' doesn't contain project with path '%s'", id, normalizedPath));
  }
  projects.add(new ProjectConfigImpl(update));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example 7
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@POST
@Path("/{id}/project")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Adds a new project to the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The project successfully added to the workspace"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to add the project"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 409, message = "Any conflict error occurs"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto addProject(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam(value = "The new project", required = true) ProjectConfigDto newProject)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(newProject, "New project config");
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  workspace.getConfig().getProjects().add(new ProjectConfigImpl(newProject));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example 8
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/environment/{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Update the workspace environment by replacing it with a new one",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The environment 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 environment"),
  @ApiResponse(code = 404, message = "The workspace or the environment not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto updateEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam("The name of the environment") @PathParam("name") String envName,
    @ApiParam(value = "The environment update", required = true) EnvironmentDto update)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(update, "Environment description");
  relativizeRecipeLinks(update);
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  EnvironmentImpl previous =
      workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(update));
  if (previous == null) {
    throw new NotFoundException(
        format("Workspace '%s' doesn't contain environment '%s'", id, envName));
  }
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example 9
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@POST
@Path("/{id}/environment")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Add a new environment to the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 200, message = "The workspace successfully updated"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to add the environment"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 409, message = "Environment with such name already exists"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto addEnvironment(
    @ApiParam("The workspace id") @PathParam("id") String id,
    @ApiParam(value = "The new environment", required = true) EnvironmentDto newEnvironment,
    @ApiParam(value = "The name of the environment", required = true) @QueryParam("name")
        String envName)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  requiredNotNull(newEnvironment, "New environment");
  requiredNotNull(envName, "New environment name");
  relativizeRecipeLinks(newEnvironment);
  WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(newEnvironment));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example 10
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@DELETE
@Path("/{id}/command/{name}")
@ApiOperation(
    value = "Remove the command from the workspace",
    notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
  @ApiResponse(code = 204, message = "The command successfully removed"),
  @ApiResponse(code = 403, message = "The user does not have access delete the command"),
  @ApiResponse(code = 404, message = "The workspace not found"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public void deleteCommand(
    @ApiParam("The id of the workspace") @PathParam("id") String id,
    @ApiParam("The name of the command to remove") @PathParam("name") String commandName)
    throws ServerException, BadRequestException, NotFoundException, ConflictException,
        ForbiddenException {
  WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  if (workspace
      .getConfig()
      .getCommands()
      .removeIf(command -> command.getName().equals(commandName))) {
    doUpdate(id, workspace);
  }
}
 
Example 11
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@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");
  WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
  if (workspace.getConfig() == null) {
    throw new ConflictException(
        "This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
  }
  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));
  return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
 
Example 12
Source File: JpaWorkspaceDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCascadeRemoveObjectsWhenTheyRemovedFromEntity() {
  final AccountImpl account = new AccountImpl("accountId", "namespace", "test");
  final WorkspaceImpl workspace = createWorkspaceFromConfig("id", account, "name");

  // Persist the account
  manager.getTransaction().begin();
  manager.persist(account);
  manager.getTransaction().commit();
  manager.clear();

  // Persist the workspace
  manager.getTransaction().begin();
  manager.persist(workspace);
  manager.getTransaction().commit();
  manager.clear();

  // Cleanup one to many dependencies
  manager.getTransaction().begin();
  final WorkspaceConfigImpl config = workspace.getConfig();
  config.getProjects().clear();
  config.getCommands().clear();
  config.getEnvironments().clear();
  manager.merge(workspace);
  manager.getTransaction().commit();
  manager.clear();

  // If all the One To Many dependencies are removed then all the embedded objects
  // which depend on those object are also removed, which guaranteed by foreign key constraints
  assertEquals(asLong("SELECT COUNT(p) FROM ProjectConfig p"), 0L, "Project configs");
  assertEquals(asLong("SELECT COUNT(c) FROM Command c"), 0L, "Commands");
  assertEquals(asLong("SELECT COUNT(e) FROM Environment e"), 0L, "Environments");
}
 
Example 13
Source File: JpaWorkspaceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected WorkspaceImpl doUpdate(WorkspaceImpl update) throws NotFoundException {
  EntityManager manager = managerProvider.get();
  if (manager.find(WorkspaceImpl.class, update.getId()) == null) {
    throw new NotFoundException(format("Workspace with id '%s' doesn't exist", update.getId()));
  }
  if (update.getConfig() != null) {
    update.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
  }
  WorkspaceImpl merged = manager.merge(update);
  manager.flush();
  return merged;
}
 
Example 14
Source File: JpaWorkspaceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected void doCreate(WorkspaceImpl workspace) {
  if (workspace.getConfig() != null) {
    workspace.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
  }
  EntityManager manager = managerProvider.get();
  manager.persist(workspace);
  manager.flush();
}
 
Example 15
Source File: FactoryService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/workspace/{ws-id}")
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Construct factory from workspace",
    notes = "This call returns a Factory.json that is used to create a factory")
@ApiResponses({
  @ApiResponse(code = 200, message = "Response contains requested factory JSON"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 404, message = "Workspace not found"),
  @ApiResponse(code = 409, message = "Workspace can not be exported as factory"),
  @ApiResponse(code = 500, message = "Internal server error")
})
public Response getFactoryJson(
    @ApiParam(value = "Workspace identifier") @PathParam("ws-id") String wsId,
    @ApiParam(value = "Project path") @QueryParam("path") String path)
    throws BadRequestException, NotFoundException, ServerException, ConflictException {
  final WorkspaceImpl workspace = workspaceManager.getWorkspace(wsId);
  if (workspace.getConfig() == null) {
    throw new ConflictException("Workspace created with Devfile can not be exported as Factory.");
  }
  excludeProjectsWithoutLocation(workspace, path);
  final FactoryDto factoryDto =
      DtoFactory.newDto(FactoryDto.class)
          .withV("4.0")
          .withWorkspace(
              org.eclipse.che.api.workspace.server.DtoConverter.asDto(workspace.getConfig()));
  return Response.ok(factoryDto, APPLICATION_JSON)
      .header(CONTENT_DISPOSITION, "attachment; filename=factory.json")
      .build();
}
 
Example 16
Source File: JpaWorkspaceDaoTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldSyncDbAttributesWhileUpdatingWorkspace() throws Exception {
  final AccountImpl account = new AccountImpl("accountId", "namespace", "test");
  final WorkspaceImpl workspace = createWorkspaceFromConfig("id", account, "name");
  if (workspace.getConfig() != null) {
    workspace.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
  }
  // persist the workspace
  manager.getTransaction().begin();
  manager.persist(account);
  manager.persist(workspace);
  manager.getTransaction().commit();
  manager.clear();

  // put a new attribute
  workspace
      .getConfig()
      .getProjects()
      .get(0)
      .getAttributes()
      .put("new-attr", singletonList("value"));
  WorkspaceImpl result = workspaceDao.update(workspace);

  manager.clear();

  // check it's okay
  assertEquals(result.getConfig().getProjects().get(0).getAttributes().size(), 3);
}
 
Example 17
Source File: MySqlTckModule.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createAll(Collection<? extends WorkspaceImpl> entities)
    throws TckRepositoryException {
  for (WorkspaceImpl entity : entities) {
    if (entity.getConfig() != null) {
      entity.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
    }
  }
  super.createAll(entities);
}
 
Example 18
Source File: RamResourceUsageTracker.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Optional<Resource> getUsedResource(String accountId)
    throws NotFoundException, ServerException {
  final Account account = accountManager.getById(accountId);
  List<WorkspaceImpl> activeWorkspaces =
      Pages.stream(
              (maxItems, skipCount) ->
                  workspaceManagerProvider
                      .get()
                      .getByNamespace(account.getName(), true, maxItems, skipCount))
          .filter(ws -> STOPPED != ws.getStatus())
          .collect(Collectors.toList());
  long currentlyUsedRamMB = 0;
  for (WorkspaceImpl activeWorkspace : activeWorkspaces) {
    if (WorkspaceStatus.STARTING.equals(activeWorkspace.getStatus())) {
      // starting workspace may not have all machine in runtime
      // it is need to calculate ram from environment config
      WorkspaceConfigImpl config = activeWorkspace.getConfig();

      if (config != null) {
        final EnvironmentImpl startingEnvironment =
            config.getEnvironments().get(activeWorkspace.getRuntime().getActiveEnv());
        if (startingEnvironment != null) {
          currentlyUsedRamMB += environmentRamCalculator.calculate(startingEnvironment);
        }
      }
      // Estimation of memory for starting workspace with Devfile is not implemented yet
      // just ignore such
    } else {
      currentlyUsedRamMB += environmentRamCalculator.calculate(activeWorkspace.getRuntime());
    }
  }

  if (currentlyUsedRamMB > 0) {
    return Optional.of(
        new ResourceImpl(RamResourceType.ID, currentlyUsedRamMB, RamResourceType.UNIT));
  } else {
    return Optional.empty();
  }
}
 
Example 19
Source File: MultiuserJpaWorkspaceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected void doCreate(WorkspaceImpl workspace) {
  if (workspace.getConfig() != null) {
    workspace.getConfig().getProjects().forEach(ProjectConfigImpl::prePersistAttributes);
  }
  EntityManager manager = managerProvider.get();
  manager.persist(workspace);
  manager.flush();
}
 
Example 20
Source File: WorkspaceRuntimes.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Validates the specified workspace configuration.
 *
 * <p>The typical usage of this method is performing validating before asynchronous start of
 * workspace.
 *
 * @param workspace workspace config that contains environment or devfile to start
 * @param envName environment to start. Default will be used if null.
 * @throws NotFoundException if workspace does not have environment with the specified name
 * @throws NotFoundException if workspace has environment with type that is not supported
 * @throws ValidationException if environment is not a valid and can not be run
 * @throws ServerException if any other issue occurred during validation
 */
public void validate(WorkspaceImpl workspace, @Nullable String envName)
    throws ValidationException, NotFoundException, ServerException {
  WorkspaceConfigImpl config = workspace.getConfig();
  if (workspace.getDevfile() != null) {
    config = devfileConverter.convert(workspace.getDevfile());
  }

  if (envName != null && !config.getEnvironments().containsKey(envName)) {
    throw new NotFoundException(
        format(
            "Workspace '%s:%s' doesn't contain environment '%s'",
            workspace.getNamespace(), config.getName(), envName));
  }

  if (envName == null) {
    // use default environment if it is not defined
    envName = config.getDefaultEnv();
  }

  if (envName == null
      && SidecarToolingWorkspaceUtil.isSidecarBasedWorkspace(config.getAttributes())) {
    // Sidecar-based workspaces are allowed not to have any environments
    return;
  }

  // validate environment in advance
  if (envName == null) {
    throw new NotFoundException(
        format(
            "Workspace %s:%s can't use null environment",
            workspace.getNamespace(), config.getName()));
  }

  Environment environment = config.getEnvironments().get(envName);

  if (environment == null) {
    throw new NotFoundException(
        format(
            "Workspace does not have environment with name %s that specified to be run",
            envName));
  }

  String type = environment.getRecipe().getType();
  if (!infrastructure.getRecipeTypes().contains(type)) {
    throw new NotFoundException("Infrastructure not found for type: " + type);
  }

  // try to create internal environment to check if the specified environment is valid
  try {
    createInternalEnvironment(environment, emptyMap(), emptyList(), config.getDevfile());
  } catch (InfrastructureException e) {
    throw new ServerException(e.getMessage(), e);
  }
}