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);
}
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));
}
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());
}
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();
}
}
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());
}
}
Aggregations