Search in sources :

Example 71 with ConflictException

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

the class WorkspaceManager method startMachine.

/**
     * Starts machine in running workspace
     *
     * @param machineConfig
     *         configuration of machine to start
     * @param workspaceId
     *         id of workspace in which machine should be started
     * @throws NotFoundException
     *         if machine type from recipe is unsupported
     * @throws NotFoundException
     *         if no instance provider implementation found for provided machine type
     * @throws ConflictException
     *         if machine with given name already exists
     * @throws ConflictException
     *         if workspace is not in RUNNING state
     * @throws BadRequestException
     *         if machine name is invalid
     * @throws ServerException
     *         if any other exception occurs during starting
     */
public void startMachine(MachineConfig machineConfig, String workspaceId) throws ServerException, ConflictException, BadRequestException, NotFoundException {
    final WorkspaceImpl workspace = getWorkspace(workspaceId);
    if (RUNNING != workspace.getStatus()) {
        throw new ConflictException(format("Workspace '%s' is not running, new machine can't be started", workspaceId));
    }
    startAsync(machineConfig, workspaceId);
}
Also used : WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) ConflictException(org.eclipse.che.api.core.ConflictException)

Example 72 with ConflictException

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

the class WorkspaceRuntimes method snapshotAndUpdateStatus.

/** Creates a snapshot and changes status SNAPSHOTTING -> RUNNING. */
private void snapshotAndUpdateStatus(String workspaceId) throws NotFoundException, ConflictException, ServerException {
    eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withWorkspaceId(workspaceId).withStatus(WorkspaceStatus.SNAPSHOTTING).withEventType(EventType.SNAPSHOT_CREATING).withPrevStatus(WorkspaceStatus.RUNNING));
    WorkspaceRuntimeImpl runtime = getRuntime(workspaceId);
    List<MachineImpl> machines = runtime.getMachines();
    machines.sort(comparing(m -> !m.getConfig().isDev(), Boolean::compare));
    LOG.info("Creating snapshot of workspace '{}', machines to snapshot: '{}'", workspaceId, machines.size());
    List<SnapshotImpl> newSnapshots = new ArrayList<>(machines.size());
    for (MachineImpl machine : machines) {
        try {
            newSnapshots.add(envEngine.saveSnapshot(workspaceId, machine.getId()));
        } catch (ServerException | NotFoundException x) {
            if (machine.getConfig().isDev()) {
                compareAndSetStatus(workspaceId, WorkspaceStatus.SNAPSHOTTING, WorkspaceStatus.RUNNING);
                eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withWorkspaceId(workspaceId).withStatus(WorkspaceStatus.RUNNING).withEventType(EventType.SNAPSHOT_CREATION_ERROR).withPrevStatus(WorkspaceStatus.SNAPSHOTTING).withError(x.getMessage()));
                throw x;
            }
            LOG.warn(format("Couldn't create snapshot of machine '%s:%s' in workspace '%s'", machine.getEnvName(), machine.getConfig().getName(), workspaceId));
        }
    }
    LOG.info("Saving new snapshots metadata, workspace id '{}'", workspaceId);
    try {
        List<SnapshotImpl> removed = snapshotDao.replaceSnapshots(workspaceId, runtime.getActiveEnv(), newSnapshots);
        if (!removed.isEmpty()) {
            LOG.info("Removing old snapshots binaries, workspace id '{}', snapshots to remove '{}'", workspaceId, removed.size());
            removeBinaries(removed);
        }
    } catch (SnapshotException x) {
        LOG.error(format("Couldn't remove existing snapshots metadata for workspace '%s'", workspaceId), x);
        LOG.info("Removing newly created snapshots, workspace id '{}', snapshots to remove '{}'", workspaceId, newSnapshots.size());
        removeBinaries(newSnapshots);
        compareAndSetStatus(workspaceId, WorkspaceStatus.SNAPSHOTTING, WorkspaceStatus.RUNNING);
        eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withWorkspaceId(workspaceId).withStatus(WorkspaceStatus.RUNNING).withEventType(EventType.SNAPSHOT_CREATION_ERROR).withPrevStatus(WorkspaceStatus.SNAPSHOTTING).withError(x.getMessage()));
        throw x;
    }
    compareAndSetStatus(workspaceId, WorkspaceStatus.SNAPSHOTTING, WorkspaceStatus.RUNNING);
    eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class).withStatus(WorkspaceStatus.RUNNING).withWorkspaceId(workspaceId).withEventType(EventType.SNAPSHOT_CREATED).withPrevStatus(WorkspaceStatus.SNAPSHOTTING));
}
Also used : ENVIRONMENT_OUTPUT_CHANNEL_TEMPLATE(org.eclipse.che.api.machine.shared.Constants.ENVIRONMENT_OUTPUT_CHANNEL_TEMPLATE) AgentLauncher(org.eclipse.che.api.agent.server.launcher.AgentLauncher) Agent(org.eclipse.che.api.agent.shared.model.Agent) EnvironmentImpl(org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl) StripedLocks(org.eclipse.che.commons.lang.concurrent.StripedLocks) AgentException(org.eclipse.che.api.agent.server.exception.AgentException) RUNNING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.RUNNING) Unlocker(org.eclipse.che.commons.lang.concurrent.Unlocker) Future(java.util.concurrent.Future) WorkspaceStatusEvent(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent) EnvironmentStartInterruptedException(org.eclipse.che.api.environment.server.exception.EnvironmentStartInterruptedException) Map(java.util.Map) EnvironmentNotRunningException(org.eclipse.che.api.environment.server.exception.EnvironmentNotRunningException) EventService(org.eclipse.che.api.core.notification.EventService) CancellationException(java.util.concurrent.CancellationException) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Collectors(java.util.stream.Collectors) Nullable(org.eclipse.che.commons.annotation.Nullable) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) CountDownLatch(java.util.concurrent.CountDownLatch) STARTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STARTING) EnvironmentException(org.eclipse.che.api.environment.server.exception.EnvironmentException) List(java.util.List) Environment(org.eclipse.che.api.core.model.workspace.Environment) CheEnvironmentEngine(org.eclipse.che.api.environment.server.CheEnvironmentEngine) AgentKey(org.eclipse.che.api.agent.shared.model.AgentKey) EventType(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent.EventType) AgentLauncherFactory(org.eclipse.che.api.agent.server.launcher.AgentLauncherFactory) WorkspaceImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl) AgentRegistry(org.eclipse.che.api.agent.server.AgentRegistry) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Workspace(org.eclipse.che.api.core.model.workspace.Workspace) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Singleton(javax.inject.Singleton) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) HashSet(java.util.HashSet) WebsocketMessageConsumer(org.eclipse.che.api.core.util.WebsocketMessageConsumer) WorkspaceRuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceRuntimeImpl) Objects.requireNonNull(java.util.Objects.requireNonNull) ConflictException(org.eclipse.che.api.core.ConflictException) Comparator.comparing(java.util.Comparator.comparing) Instance(org.eclipse.che.api.machine.server.spi.Instance) SnapshotDao(org.eclipse.che.api.machine.server.spi.SnapshotDao) DtoFactory(org.eclipse.che.dto.server.DtoFactory) ExecutorService(java.util.concurrent.ExecutorService) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) Logger(org.slf4j.Logger) ExtendedMachine(org.eclipse.che.api.core.model.workspace.ExtendedMachine) SNAPSHOTTING(org.eclipse.che.api.core.model.workspace.WorkspaceStatus.SNAPSHOTTING) WorkspaceStatus(org.eclipse.che.api.core.model.workspace.WorkspaceStatus) NotFoundException(org.eclipse.che.api.core.NotFoundException) TimeUnit(java.util.concurrent.TimeUnit) SnapshotException(org.eclipse.che.api.machine.server.exception.SnapshotException) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) AgentSorter(org.eclipse.che.api.agent.server.impl.AgentSorter) ServerException(org.eclipse.che.api.core.ServerException) MachineConfigImpl(org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl) LoggerFactory.getLogger(org.slf4j.LoggerFactory.getLogger) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MachineStartedHandler(org.eclipse.che.api.environment.server.MachineStartedHandler) Collections(java.util.Collections) MachineImpl(org.eclipse.che.api.machine.server.model.impl.MachineImpl) ServerException(org.eclipse.che.api.core.ServerException) SnapshotImpl(org.eclipse.che.api.machine.server.model.impl.SnapshotImpl) WorkspaceStatusEvent(org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent) ArrayList(java.util.ArrayList) NotFoundException(org.eclipse.che.api.core.NotFoundException) WorkspaceRuntimeImpl(org.eclipse.che.api.workspace.server.model.impl.WorkspaceRuntimeImpl) SnapshotException(org.eclipse.che.api.machine.server.exception.SnapshotException)

Example 73 with ConflictException

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

the class SimpleGeneratorStrategy method generateProject.

@Override
public void generateProject(Path projectPath, Map<String, AttributeValue> attributes, Map<String, String> options) throws ForbiddenException, ConflictException, ServerException {
    AttributeValue artifactId = attributes.get(ARTIFACT_ID);
    AttributeValue groupId = attributes.get(GROUP_ID);
    AttributeValue version = attributes.get(VERSION);
    if (artifactId == null) {
        throw new ConflictException("Missed required attribute artifactId");
    }
    if (groupId == null) {
        throw new ConflictException("Missed required attribute groupId");
    }
    if (version == null) {
        throw new ConflictException("Missed required attribute version");
    }
    Model model = Model.createModel();
    model.setModelVersion("4.0.0");
    final FolderEntry baseFolder = new FolderEntry(vfs.getRoot().createFolder(projectPath.toString()));
    if (baseFolder.getChild("pom.xml") == null) {
        baseFolder.createFile("pom.xml", new byte[0]);
    }
    AttributeValue parentArtifactId = attributes.get(PARENT_ARTIFACT_ID);
    if (parentArtifactId != null) {
        model.setArtifactId(parentArtifactId.getString());
    }
    AttributeValue parentGroupId = attributes.get(PARENT_GROUP_ID);
    if (parentGroupId != null) {
        model.setGroupId(parentGroupId.getString());
    }
    AttributeValue parentVersion = attributes.get(PARENT_VERSION);
    if (parentVersion != null) {
        model.setVersion(parentVersion.getString());
    }
    model.setArtifactId(artifactId.getString());
    model.setGroupId(groupId.getString());
    model.setVersion(version.getString());
    AttributeValue packaging = attributes.get(PACKAGING);
    if (packaging != null) {
        model.setPackaging(packaging.getString());
    }
    AttributeValue sourceFolders = attributes.get(SOURCE_FOLDER);
    if (sourceFolders != null) {
        final String sourceFolder = sourceFolders.getString();
        baseFolder.createFolder(sourceFolder);
        if (!DEFAULT_SOURCE_FOLDER.equals(sourceFolder)) {
            model.setBuild(new Build().setSourceDirectory(sourceFolder));
        }
    }
    AttributeValue testSourceFolders = attributes.get(TEST_SOURCE_FOLDER);
    if (testSourceFolders != null) {
        final String testSourceFolder = testSourceFolders.getString();
        baseFolder.createFolder(testSourceFolder);
        if (!DEFAULT_TEST_SOURCE_FOLDER.equals(testSourceFolder)) {
            Build build = model.getBuild();
            if (build != null) {
                build.setTestSourceDirectory(testSourceFolder);
            } else {
                model.setBuild(new Build().setTestSourceDirectory(testSourceFolder));
            }
        }
    }
    model.writeTo(baseFolder.getChild("pom.xml").getVirtualFile());
}
Also used : AttributeValue(org.eclipse.che.api.project.server.type.AttributeValue) ConflictException(org.eclipse.che.api.core.ConflictException) Build(org.eclipse.che.ide.maven.tools.Build) FolderEntry(org.eclipse.che.api.project.server.FolderEntry) Model(org.eclipse.che.ide.maven.tools.Model)

Example 74 with ConflictException

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

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

the class MemoryVirtualFileTest method failsRenameFileWhenFolderContainsItemWithSameName.

@Test
public void failsRenameFileWhenFolderContainsItemWithSameName() throws Exception {
    VirtualFile folder = getRoot().createFolder(generateFolderName());
    VirtualFile file = folder.createFile(generateFileName(), DEFAULT_CONTENT);
    file.setProperty("property1", "value1");
    VirtualFile conflictFile = folder.createFile("existed_name", "xxx");
    conflictFile.setProperty("property2", "value2");
    try {
        file.rename("existed_name");
        thrown.expect(ConflictException.class);
    } catch (ConflictException e) {
        assertEquals(DEFAULT_CONTENT, file.getContentAsString());
        assertEquals(ImmutableMap.of("property1", "value1"), file.getProperties());
        assertEquals("xxx", conflictFile.getContentAsString());
        assertEquals(ImmutableMap.of("property2", "value2"), conflictFile.getProperties());
    }
}
Also used : VirtualFile(org.eclipse.che.api.vfs.VirtualFile) ConflictException(org.eclipse.che.api.core.ConflictException) Test(org.junit.Test)

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