From 7798be0131a844b9abf056b7db8ba457bae82ffa Mon Sep 17 00:00:00 2001 From: Roman Iuvshin Date: Wed, 20 Jul 2016 14:56:55 +0300 Subject: [PATCH 01/24] Fix path to the assemble in Dockerfile --- dockerfiles/che-server/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dockerfiles/che-server/Dockerfile b/dockerfiles/che-server/Dockerfile index e281cab59c8b..7c577e4ff84a 100644 --- a/dockerfiles/che-server/Dockerfile +++ b/dockerfiles/che-server/Dockerfile @@ -40,7 +40,7 @@ EXPOSE 8000 8080 USER user -ADD assembly/assembly-main/target/eclipse-che-*/eclipse-che-* /home/user/che/ +ADD ../../assembly/assembly-main/target/eclipse-che-*/eclipse-che-* /home/user/che/ ENV CHE_HOME /home/user/che From 586a4d6b45944f7720123ff7e390ae23dfc90d43 Mon Sep 17 00:00:00 2001 From: Roman Iuvshin Date: Wed, 20 Jul 2016 15:18:57 +0300 Subject: [PATCH 02/24] Revert "Fix path to the assemble in Dockerfile" This reverts commit 7798be0131a844b9abf056b7db8ba457bae82ffa. --- dockerfiles/che-server/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dockerfiles/che-server/Dockerfile b/dockerfiles/che-server/Dockerfile index 7c577e4ff84a..e281cab59c8b 100644 --- a/dockerfiles/che-server/Dockerfile +++ b/dockerfiles/che-server/Dockerfile @@ -40,7 +40,7 @@ EXPOSE 8000 8080 USER user -ADD ../../assembly/assembly-main/target/eclipse-che-*/eclipse-che-* /home/user/che/ +ADD assembly/assembly-main/target/eclipse-che-*/eclipse-che-* /home/user/che/ ENV CHE_HOME /home/user/che From 7a1c842ec006bc2f2ed6cb66444231531dc7442e Mon Sep 17 00:00:00 2001 From: Vitalii Parfonov Date: Wed, 20 Jul 2016 15:26:25 +0300 Subject: [PATCH 03/24] [Issue #1413] register multiple callbacks (fixes #1413) (#1873) Signed-off-by: Sven Efftinge --- .../api/machine/WsAgentStateController.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/machine/WsAgentStateController.java b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/machine/WsAgentStateController.java index 7bfb2aae189b..dd1e4427fbd9 100644 --- a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/machine/WsAgentStateController.java +++ b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/machine/WsAgentStateController.java @@ -41,6 +41,7 @@ import java.util.ArrayList; import java.util.List; +import static com.google.common.collect.Lists.newArrayList; import static org.eclipse.che.ide.api.machine.WsAgentState.STARTED; import static org.eclipse.che.ide.api.machine.WsAgentState.STOPPED; import static org.eclipse.che.ide.ui.loaders.initialization.InitialLoadingInfo.Operations.WS_AGENT_BOOTING; @@ -66,8 +67,8 @@ public class WsAgentStateController implements ConnectionOpenedHandler, Connecti private MessageBus messageBus; private WsAgentState state; - private AsyncCallback messageBusCallback; - private AsyncCallback devMachineCallback; + private List> messageBusCallbacks = newArrayList(); + private List> devMachineCallbacks = newArrayList(); @Inject public WsAgentStateController(EventBus eventBus, @@ -111,7 +112,6 @@ public void onError() { @Override public void onOpen() { messageBus.removeOnOpenHandler(this); - MessageBus.ReadyState readyState = messageBus.getReadyState(); //need to make sure ready state equals 1 (OPEN) in same situations after opening it still equals 0 (CONNECTING) new Timer() { @Override @@ -129,12 +129,16 @@ private void started() { initialLoadingInfo.setOperationStatus(WS_AGENT_BOOTING.getValue(), SUCCESS); loader.hide(); - if (messageBusCallback != null) { - messageBusCallback.onSuccess(messageBus); - } - if (devMachineCallback != null) { - devMachineCallback.onSuccess(devMachine); + for (AsyncCallback callback : messageBusCallbacks) { + callback.onSuccess(messageBus); + } + messageBusCallbacks = null; + + for (AsyncCallback callback : devMachineCallbacks) { + callback.onSuccess(devMachine); } + devMachineCallbacks = null; + eventBus.fireEvent(WsAgentStateEvent.createWsAgentStartedEvent()); } @@ -149,7 +153,7 @@ public void makeCall(AsyncCallback callback) { if (messageBus != null) { callback.onSuccess(messageBus); } else { - WsAgentStateController.this.messageBusCallback = callback; + WsAgentStateController.this.messageBusCallbacks.add(callback); } } }); @@ -163,7 +167,7 @@ public void makeCall(AsyncCallback callback) { if (messageBus != null) { callback.onSuccess(devMachine); } else { - WsAgentStateController.this.devMachineCallback = callback; + WsAgentStateController.this.devMachineCallbacks.add(callback); } } }); From 260bd6d9ca6df63602afe1f271e8dfc37fb43b2d Mon Sep 17 00:00:00 2001 From: Vladyslav Zhukovskii Date: Wed, 20 Jul 2016 15:40:02 +0300 Subject: [PATCH 04/24] CHE-1535: Reveal resources after move and copy operation Now, it is possible to navigate to the copied and moved file after cut/copy/paste operation. --- .../eclipse/che/ide/resources/impl/CopyPasteManager.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/impl/CopyPasteManager.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/impl/CopyPasteManager.java index 23908de886b8..a2a388afb176 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/impl/CopyPasteManager.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/impl/CopyPasteManager.java @@ -36,6 +36,7 @@ import org.eclipse.che.ide.api.resources.modification.ClipboardManager; import org.eclipse.che.ide.api.resources.modification.CutResourceMarker; import org.eclipse.che.ide.resource.Path; +import org.eclipse.che.ide.resources.reveal.RevealResourceEvent; import static java.util.Arrays.copyOf; import static org.eclipse.che.api.promises.client.callback.AsyncPromiseHelper.createFromAsyncRequest; @@ -59,6 +60,7 @@ class CopyPasteManager implements ResourceChangedHandler { private final PromiseProvider promises; private final DialogFactory dialogFactory; private final NotificationManager notificationManager; + private final EventBus eventBus; private Resource[] resources; private boolean move; @@ -70,6 +72,7 @@ public CopyPasteManager(PromiseProvider promises, this.promises = promises; this.dialogFactory = dialogFactory; this.notificationManager = notificationManager; + this.eventBus = eventBus; eventBus.addHandler(ResourceChangedEvent.getType(), this); } @@ -137,7 +140,8 @@ private Promise moveResource(final Resource resource, final Path destinati //simple move without overwriting return resource.move(destination).thenPromise(new Function>() { @Override - public Promise apply(Resource ignored) throws FunctionException { + public Promise apply(Resource resource) throws FunctionException { + eventBus.fireEvent(new RevealResourceEvent(resource)); return promises.resolve(null); } }).catchErrorPromise(new Function>() { @@ -240,7 +244,8 @@ private Promise copyResource(final Resource resource, final Path destinati //simple copy without overwriting return resource.copy(destination).thenPromise(new Function>() { @Override - public Promise apply(Resource ignored) throws FunctionException { + public Promise apply(Resource resource) throws FunctionException { + eventBus.fireEvent(new RevealResourceEvent(resource)); return promises.resolve(null); } }).catchErrorPromise(new Function>() { From fe0cb3bd0f0c535b6d70167a18d175386af829c8 Mon Sep 17 00:00:00 2001 From: Max Shaposhnik Date: Wed, 20 Jul 2016 17:30:10 +0300 Subject: [PATCH 05/24] CHE-1248; remove workspace information from EnvironmentContext (#1658) --- .../che/DashboardRedirectionFilterTest.java | 8 ---- .../che/wsagent/server/WsAgentModule.java | 7 --- .../wsagent/server/WsAgentServletModule.java | 4 +- .../che/api/deploy/WsMasterModule.java | 4 -- .../che/api/deploy/WsMasterServletModule.java | 2 +- .../che/commons/env/EnvironmentContext.java | 34 -------------- .../che/everrest/CheAsynchronousJobPool.java | 9 ---- .../WebSocketMethodInvokerDecorator.java | 6 +-- .../commons/env/EnvironmentContextTest.java | 7 --- .../machine/DockerInstanceProviderTest.java | 1 - .../org-eclipse-jdt-ui/pom.xml | 8 ++-- .../internal/ui/text/java/ProposalInfo.java | 21 +++++---- .../server/jdt/CompletionJavadocTest.java | 1 - wsagent/che-core-api-git/pom.xml | 4 ++ .../che/api/git/GitProjectImporter.java | 3 +- .../api/project/server/ProjectService.java | 2 +- wsagent/che-core-git-impl-jgit/pom.xml | 4 ++ wsagent/che-core-git-impl-native/pom.xml | 4 ++ ...a => EnvironmentInitializationFilter.java} | 25 ++-------- ...sAgentEnvironmentInitializationFilter.java | 30 ------------ ...a => EnvironmentInitializationFilter.java} | 25 ++-------- ...MasterEnvironmentInitializationFilter.java | 47 ------------------- 22 files changed, 46 insertions(+), 210 deletions(-) rename wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/{AbstractEnvironmentInitializationFilter.java => EnvironmentInitializationFilter.java} (76%) delete mode 100644 wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/WsAgentEnvironmentInitializationFilter.java rename wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/{AbstractEnvironmentInitializationFilter.java => EnvironmentInitializationFilter.java} (76%) delete mode 100644 wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/WsMasterEnvironmentInitializationFilter.java diff --git a/assembly/assembly-ide-war/src/test/java/org/eclipse/che/DashboardRedirectionFilterTest.java b/assembly/assembly-ide-war/src/test/java/org/eclipse/che/DashboardRedirectionFilterTest.java index f114c15f1086..c9753a4e2dbb 100644 --- a/assembly/assembly-ide-war/src/test/java/org/eclipse/che/DashboardRedirectionFilterTest.java +++ b/assembly/assembly-ide-war/src/test/java/org/eclipse/che/DashboardRedirectionFilterTest.java @@ -56,9 +56,6 @@ public void shouldSkipRequestToProject() throws Exception { when(request.getMethod()).thenReturn("GET"); when(request.getRequestURI()).thenReturn("/namespace/ws-id/project1"); when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/namespace/ws-id/project1")); - EnvironmentContext context = new EnvironmentContext(); - context.setWorkspaceId("ws-id"); - EnvironmentContext.setCurrent(context); //when filter.doFilter(request, response, chain); @@ -74,8 +71,6 @@ public void shouldRedirectIfRequestWithoutNamespace(String uri, String url) thro when(request.getRequestURI()).thenReturn(uri); when(request.getRequestURL()).thenReturn(new StringBuffer(url)); EnvironmentContext context = new EnvironmentContext(); - context.setWorkspaceId("ws-id"); - context.setWorkspaceTemporary(false); context.setSubject(new SubjectImpl("id123", "name", "token123", false)); EnvironmentContext.setCurrent(context); @@ -99,9 +94,6 @@ public void shouldSkipNotGETRequest(String method) throws Exception { when(request.getMethod()).thenReturn(method); when(request.getRequestURI()).thenReturn("/ws-id/project1"); when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/ws-id/project1")); - EnvironmentContext context = new EnvironmentContext(); - context.setWorkspaceId("ws-id"); - EnvironmentContext.setCurrent(context); //when filter.doFilter(request, response, chain); diff --git a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentModule.java b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentModule.java index de7cbb0f84c7..a4a529e0bcaa 100644 --- a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentModule.java +++ b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentModule.java @@ -31,15 +31,11 @@ import org.eclipse.che.api.ssh.server.SshServiceClient; import org.eclipse.che.api.user.server.spi.PreferenceDao; import org.eclipse.che.commons.lang.Pair; -import org.eclipse.che.everrest.CheAsynchronousJobPool; import org.eclipse.che.api.git.LocalGitUserResolver; import org.eclipse.che.git.impl.jgit.JGitConnectionFactory; import org.eclipse.che.inject.DynaModule; import org.eclipse.che.plugin.java.server.rest.WsAgentURLProvider; import org.eclipse.che.security.oauth.RemoteOAuthTokenProvider; -import org.everrest.core.impl.async.AsynchronousJobPool; -import org.everrest.core.impl.async.AsynchronousJobService; -import org.everrest.guice.ServiceBindingHelper; import javax.inject.Named; import java.net.URI; @@ -71,9 +67,6 @@ protected void configure() { bind(GitUserResolver.class).to(LocalGitUserResolver.class); bind(GitConnectionFactory.class).to(JGitConnectionFactory.class); - bind(AsynchronousJobPool.class).to(CheAsynchronousJobPool.class); - bind(ServiceBindingHelper.bindingKey(AsynchronousJobService.class, "/async/{ws-id}")).to(AsynchronousJobService.class); - bind(String.class).annotatedWith(Names.named("api.endpoint")).toProvider(ApiEndpointProvider.class); bind(URI.class).annotatedWith(Names.named("api.endpoint")).toProvider(UriApiEndpointProvider.class); bind(String.class).annotatedWith(Names.named("user.token")).toProvider(UserTokenProvider.class); diff --git a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentServletModule.java b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentServletModule.java index a7abaa72545c..1e2d85523752 100644 --- a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentServletModule.java +++ b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentServletModule.java @@ -14,7 +14,7 @@ import com.google.inject.servlet.ServletModule; import org.eclipse.che.api.core.cors.CheCorsFilter; -import org.eclipse.che.filters.WsAgentEnvironmentInitializationFilter; +import org.eclipse.che.filters.EnvironmentInitializationFilter; import org.eclipse.che.inject.DynaModule; import org.everrest.guice.servlet.GuiceEverrestServlet; import org.everrest.websockets.WSConnectionTracker; @@ -27,7 +27,7 @@ protected void configureServlets() { getServletContext().addListener(new WSConnectionTracker()); filter("/*").through(CheCorsFilter.class); - filter("/ext/*").through(WsAgentEnvironmentInitializationFilter.class); + filter("/ext/*").through(EnvironmentInitializationFilter.class); serveRegex("^/ext((?!(/(ws|eventbus)($|/.*)))/.*)").with(GuiceEverrestServlet.class); diff --git a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java index e0bfca91ff90..54628a973084 100644 --- a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java +++ b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java @@ -17,7 +17,6 @@ import org.eclipse.che.api.machine.shared.Constants; import org.eclipse.che.api.user.server.ProfileService; import org.eclipse.che.inject.DynaModule; -import org.everrest.guice.ServiceBindingHelper; /** @author andrew00x */ @DynaModule @@ -37,9 +36,6 @@ protected void configure() { bind(org.eclipse.che.api.workspace.server.stack.StackService.class); bind(org.eclipse.che.api.workspace.server.WorkspaceService.class); bind(org.eclipse.che.api.workspace.server.event.WorkspaceMessenger.class).asEagerSingleton(); - bind(org.everrest.core.impl.async.AsynchronousJobPool.class).to(org.eclipse.che.everrest.CheAsynchronousJobPool.class); - bind(ServiceBindingHelper.bindingKey(org.everrest.core.impl.async.AsynchronousJobService.class, "/async/{ws-id}")) - .to(org.everrest.core.impl.async.AsynchronousJobService.class); bind(org.eclipse.che.plugin.docker.machine.ext.DockerMachineExtServerChecker.class); bind(org.eclipse.che.plugin.docker.machine.ext.DockerMachineTerminalChecker.class); bind(org.eclipse.che.everrest.EverrestDownloadFileResponseFilter.class); diff --git a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterServletModule.java b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterServletModule.java index e04997d24ab9..0b4f6d82655a 100644 --- a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterServletModule.java +++ b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterServletModule.java @@ -47,7 +47,7 @@ protected void configureServlets() { filter("/*").through(CorsFilter.class, corsFilterParams); - filter("/api/*").through(org.eclipse.che.api.local.filters.WsMasterEnvironmentInitializationFilter.class); + filter("/api/*").through(org.eclipse.che.api.local.filters.EnvironmentInitializationFilter.class); serveRegex("^/api((?!(/(ws|eventbus)($|/.*)))/.*)").with(org.eclipse.che.api.local.CheGuiceEverrestServlet.class); install(new org.eclipse.che.swagger.deploy.BasicSwaggerConfigurationModule()); } diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/commons/env/EnvironmentContext.java b/core/che-core-api-core/src/main/java/org/eclipse/che/commons/env/EnvironmentContext.java index 3321687628d2..16eb416bb50c 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/commons/env/EnvironmentContext.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/commons/env/EnvironmentContext.java @@ -50,21 +50,11 @@ public static void reset() { private Subject subject; - private String workspaceName; - - private String workspaceId; - - private boolean workspaceTemporary; - - public EnvironmentContext() { } public EnvironmentContext(EnvironmentContext other) { setSubject(other.getSubject()); - setWorkspaceName(other.getWorkspaceName()); - setWorkspaceId(other.getWorkspaceId()); - setWorkspaceTemporary(other.isWorkspaceTemporary()); } public Subject getSubject() { @@ -74,28 +64,4 @@ public Subject getSubject() { public void setSubject(Subject subject) { this.subject = subject; } - - public String getWorkspaceName() { - return workspaceName; - } - - public void setWorkspaceName(String workspaceName) { - this.workspaceName = workspaceName; - } - - public String getWorkspaceId() { - return workspaceId; - } - - public void setWorkspaceId(String workspaceId) { - this.workspaceId = workspaceId; - } - - public boolean isWorkspaceTemporary() { - return workspaceTemporary; - } - - public void setWorkspaceTemporary(boolean workspaceTemporary) { - this.workspaceTemporary = workspaceTemporary; - } } diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheAsynchronousJobPool.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheAsynchronousJobPool.java index 4d685333672d..c5e5c3a259ca 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheAsynchronousJobPool.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheAsynchronousJobPool.java @@ -35,15 +35,6 @@ public CheAsynchronousJobPool(EverrestConfiguration everrestConfiguration) { super(everrestConfiguration); } - @Override - protected UriBuilder getAsynchronousJobUriBuilder(AsynchronousJob job) { - final String wsId = EnvironmentContext.getCurrent().getWorkspaceId(); - if (wsId == null) { - return super.getAsynchronousJobUriBuilder(job); - } - return UriBuilder.fromPath(asynchronousServicePath).path(wsId).path(Long.toString(job.getJobId())); - } - @Override protected Callable newCallable(Object resource, Method method, Object[] params) { return ThreadLocalPropagateContext.wrap((super.newCallable(resource, method, params))); diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java index 1dc8cf3797c9..e4abda6b033b 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java @@ -46,11 +46,9 @@ public Object invokeMethod(Object resource, GenericMethodResource genericMethodR EnvironmentContext.setCurrent(environmentContext); - LOG.debug("Websocket {} in http session {} context of ws {} is temporary {}", + LOG.debug("Websocket {} in http session {}", wsConnection.getId(), - wsConnection.getHttpSession(), - EnvironmentContext.getCurrent().getWorkspaceName(), - EnvironmentContext.getCurrent().isWorkspaceTemporary()); + wsConnection.getHttpSession()); return super.invokeMethod(resource, genericMethodResource, context); } finally { EnvironmentContext.reset(); diff --git a/core/che-core-api-core/src/test/java/org/eclipse/che/commons/env/EnvironmentContextTest.java b/core/che-core-api-core/src/test/java/org/eclipse/che/commons/env/EnvironmentContextTest.java index 8cf1efb6be2a..7b180460c67d 100644 --- a/core/che-core-api-core/src/test/java/org/eclipse/che/commons/env/EnvironmentContextTest.java +++ b/core/che-core-api-core/src/test/java/org/eclipse/che/commons/env/EnvironmentContextTest.java @@ -16,7 +16,6 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; public class EnvironmentContextTest { @@ -24,13 +23,9 @@ public class EnvironmentContextTest { public void shouldBeAbleToSetEnvContextInSameThread() { //given EnvironmentContext expected = EnvironmentContext.getCurrent(); - expected.setWorkspaceId("ws1"); - expected.setWorkspaceTemporary(true); expected.setSubject(new SubjectImpl("user", "id", "token", false)); EnvironmentContext actual = EnvironmentContext.getCurrent(); - assertEquals(actual.getWorkspaceId(), "ws1"); - assertTrue(actual.isWorkspaceTemporary()); Subject actualSubject = actual.getSubject(); assertEquals(actualSubject.getUserName(), "user"); assertEquals(actualSubject.getUserId(), "id"); @@ -42,8 +37,6 @@ public void shouldBeAbleToSetEnvContextInSameThread() { public void shouldNotBeAbleToSeeContextInOtherThread() { //given final EnvironmentContext expected = EnvironmentContext.getCurrent(); - expected.setWorkspaceId("ws1"); - expected.setWorkspaceTemporary(true); expected.setSubject(new SubjectImpl("user", "id", "token", false)); diff --git a/plugins/plugin-docker/che-plugin-docker-machine/src/test/java/org/eclipse/che/plugin/docker/machine/DockerInstanceProviderTest.java b/plugins/plugin-docker/che-plugin-docker-machine/src/test/java/org/eclipse/che/plugin/docker/machine/DockerInstanceProviderTest.java index 44fe120aecff..3f9cbbd2ed9f 100644 --- a/plugins/plugin-docker/che-plugin-docker-machine/src/test/java/org/eclipse/che/plugin/docker/machine/DockerInstanceProviderTest.java +++ b/plugins/plugin-docker/che-plugin-docker-machine/src/test/java/org/eclipse/che/plugin/docker/machine/DockerInstanceProviderTest.java @@ -156,7 +156,6 @@ public void setUp() throws Exception { EnvironmentContext envCont = new EnvironmentContext(); envCont.setSubject(new SubjectImpl(USER_NAME, "userId", USER_TOKEN, false)); - envCont.setWorkspaceId(WORKSPACE_ID); EnvironmentContext.setCurrent(envCont); diff --git a/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/pom.xml b/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/pom.xml index 64b7fca99505..80a66f411489 100644 --- a/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/pom.xml +++ b/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/pom.xml @@ -46,10 +46,6 @@ org.eclipse.birt.runtime org.eclipse.equinox.common - - org.eclipse.che.core - che-core-api-core - org.eclipse.che.core che-core-api-dto @@ -66,6 +62,10 @@ org.eclipse.che.core che-core-commons-lang + + org.eclipse.che.core + wsagent-local + org.eclipse.che.plugin che-plugin-java-ext-lang-shared diff --git a/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/ui/text/java/ProposalInfo.java b/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/ui/text/java/ProposalInfo.java index cfda277baf9e..dc823cd77641 100644 --- a/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/ui/text/java/ProposalInfo.java +++ b/plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/ui/text/java/ProposalInfo.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; -import org.eclipse.che.commons.env.EnvironmentContext; +import org.eclipse.che.WorkspaceIdProvider; import org.eclipse.che.jdt.javadoc.JavaDocLocations; import org.eclipse.che.jdt.javadoc.JavadocContentAccess2; import org.eclipse.che.jdt.rest.UrlContextProvider; @@ -89,14 +89,17 @@ private String computeInfo(IProgressMonitor monitor) { */ private String extractJavadoc(IJavaElement element) throws CoreException { if (element instanceof IMember) { - return JavadocContentAccess2.getHTMLContent((IMember) element, true, UrlContextProvider.get(EnvironmentContext.getCurrent().getWorkspaceId(), element.getJavaProject().getPath().toString())); - } else if (element instanceof IPackageDeclaration) { - return JavadocContentAccess2.getHTMLContent((IPackageDeclaration)element,UrlContextProvider.get(EnvironmentContext.getCurrent().getWorkspaceId(), - element.getJavaProject().getPath().toString())); - } else if (element instanceof IPackageFragment) { - return JavadocContentAccess2.getHTMLContent((IPackageFragment) element,UrlContextProvider.get(EnvironmentContext.getCurrent().getWorkspaceId(), - element.getJavaProject().getPath().toString())); - } + return JavadocContentAccess2.getHTMLContent((IMember)element, true, UrlContextProvider + .get(WorkspaceIdProvider.getWorkspaceId(), element.getJavaProject().getPath().toString())); + } else if (element instanceof IPackageDeclaration) { + return JavadocContentAccess2 + .getHTMLContent((IPackageDeclaration)element, UrlContextProvider.get(WorkspaceIdProvider.getWorkspaceId(), + element.getJavaProject().getPath().toString())); + } else if (element instanceof IPackageFragment) { + return JavadocContentAccess2 + .getHTMLContent((IPackageFragment)element, UrlContextProvider.get(WorkspaceIdProvider.getWorkspaceId(), + element.getJavaProject().getPath().toString())); + } return null; } diff --git a/plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/java/org/eclipse/che/plugin/java/server/jdt/CompletionJavadocTest.java b/plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/java/org/eclipse/che/plugin/java/server/jdt/CompletionJavadocTest.java index d47dc6a19222..608f3c874321 100644 --- a/plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/java/org/eclipse/che/plugin/java/server/jdt/CompletionJavadocTest.java +++ b/plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/java/org/eclipse/che/plugin/java/server/jdt/CompletionJavadocTest.java @@ -82,7 +82,6 @@ private static List computeProposals(ICompilationUnit compi public void setUp() throws Exception { super.setUp(); EnvironmentContext customEnvironment = mock(EnvironmentContext.class); - doReturn("1q2w3e").when(customEnvironment).getWorkspaceId(); doReturn(new SubjectImpl(vfsUser, "", "", false)).when(customEnvironment).getSubject(); EnvironmentContext.setCurrent(customEnvironment); fJProject1 = Java18ProjectTestSetup.getProject(); diff --git a/wsagent/che-core-api-git/pom.xml b/wsagent/che-core-api-git/pom.xml index ce772a0357f8..b39b99f95dec 100644 --- a/wsagent/che-core-api-git/pom.xml +++ b/wsagent/che-core-api-git/pom.xml @@ -86,6 +86,10 @@ org.eclipse.che.core che-core-commons-lang + + org.eclipse.che.core + wsagent-local + org.everrest everrest-websockets diff --git a/wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/GitProjectImporter.java b/wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/GitProjectImporter.java index cba993390df7..e8ddf54ecc73 100644 --- a/wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/GitProjectImporter.java +++ b/wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/GitProjectImporter.java @@ -13,6 +13,7 @@ import com.google.inject.Inject; import com.google.inject.Singleton; +import org.eclipse.che.WorkspaceIdProvider; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.ServerException; @@ -265,7 +266,7 @@ private void checkoutBranch(GitConnection git, .stream() .anyMatch(branch -> branch.getName().equals(branchName)); final GitCheckoutEvent checkout = dtoFactory.createDto(GitCheckoutEvent.class) - .withWorkspaceId(System.getenv("CHE_WORKSPACE_ID")) + .withWorkspaceId(WorkspaceIdProvider.getWorkspaceId()) .withProjectName(projectName); if (startPoint != null) { if (branchExist) { diff --git a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java index 98a1e93cf277..ab9013ca579a 100644 --- a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java +++ b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java @@ -872,7 +872,7 @@ private void logProjectCreatedEvent(@NotNull String projectName, @NotNull String LOG.info("EVENT#project-created# PROJECT#{}# TYPE#{}# WS#{}# USER#{}# PAAS#default#", projectName, projectType, - EnvironmentContext.getCurrent().getWorkspaceId(), + workspace, EnvironmentContext.getCurrent().getSubject().getUserId()); } diff --git a/wsagent/che-core-git-impl-jgit/pom.xml b/wsagent/che-core-git-impl-jgit/pom.xml index 6a6a673f62e8..17e0483022e1 100644 --- a/wsagent/che-core-git-impl-jgit/pom.xml +++ b/wsagent/che-core-git-impl-jgit/pom.xml @@ -99,6 +99,10 @@ org.eclipse.che.core che-core-commons-lang + + org.eclipse.che.core + wsagent-local + org.eclipse.che.plugin che-plugin-ssh-key-server diff --git a/wsagent/che-core-git-impl-native/pom.xml b/wsagent/che-core-git-impl-native/pom.xml index 63a143fa3933..d1b9372fb85b 100644 --- a/wsagent/che-core-git-impl-native/pom.xml +++ b/wsagent/che-core-git-impl-native/pom.xml @@ -94,6 +94,10 @@ org.eclipse.che.core che-core-commons-lang + + org.eclipse.che.core + wsagent-local + org.eclipse.che.plugin che-plugin-ssh-key-server diff --git a/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/AbstractEnvironmentInitializationFilter.java b/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/EnvironmentInitializationFilter.java similarity index 76% rename from wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/AbstractEnvironmentInitializationFilter.java rename to wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/EnvironmentInitializationFilter.java index 7c90f39ab2fc..8fef4660248f 100644 --- a/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/AbstractEnvironmentInitializationFilter.java +++ b/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/EnvironmentInitializationFilter.java @@ -14,6 +14,7 @@ import org.eclipse.che.commons.subject.Subject; import org.eclipse.che.commons.subject.SubjectImpl; +import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -27,12 +28,12 @@ import java.security.Principal; /** - * The class contains commons business logic for all environment workspace id initialization filters. The filters are necessary to set - * workspace meta information to environment context. + * Fills environment context with information about current subject. * * @author Dmitry Shnurenko */ -public abstract class AbstractEnvironmentInitializationFilter implements Filter { +@Singleton +public class EnvironmentInitializationFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -50,23 +51,12 @@ public final void doFilter(ServletRequest request, ServletResponse response, Fil try { environmentContext.setSubject(subject); - environmentContext.setWorkspaceId(getWorkspaceId(request)); - filterChain.doFilter(addUserInRequest(httpRequest, subject), response); } finally { EnvironmentContext.reset(); } } - /** - * Extracts workspace id from request. - * - * @param request - * request which contains workspace id - * @return workspace id - */ - protected abstract String getWorkspaceId(ServletRequest request); - private HttpServletRequest addUserInRequest(final HttpServletRequest httpRequest, final Subject subject) { return new HttpServletRequestWrapper(httpRequest) { @Override @@ -76,12 +66,7 @@ public String getRemoteUser() { @Override public Principal getUserPrincipal() { - return new Principal() { - @Override - public String getName() { - return subject.getUserName(); - } - }; + return () -> subject.getUserName(); } }; } diff --git a/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/WsAgentEnvironmentInitializationFilter.java b/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/WsAgentEnvironmentInitializationFilter.java deleted file mode 100644 index 406fbbb3facb..000000000000 --- a/wsagent/wsagent-local/src/main/java/org/eclipse/che/filters/WsAgentEnvironmentInitializationFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2016 Codenvy, S.A. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Codenvy, S.A. - initial API and implementation - *******************************************************************************/ -package org.eclipse.che.filters; - -import com.google.inject.Singleton; - -import javax.servlet.ServletRequest; - -/** - * The filter contains business logic which allows extract workspace id and sets it to environment context. Workspace id - * has defined place in URL. The filter mapped for all requests to ws agent API. - * - * @author Dmitry Shnurenko - */ -@Singleton -public class WsAgentEnvironmentInitializationFilter extends AbstractEnvironmentInitializationFilter { - - @Override - protected String getWorkspaceId(ServletRequest request) { - return System.getenv("CHE_WORKSPACE_ID"); - } -} diff --git a/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/AbstractEnvironmentInitializationFilter.java b/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/EnvironmentInitializationFilter.java similarity index 76% rename from wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/AbstractEnvironmentInitializationFilter.java rename to wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/EnvironmentInitializationFilter.java index c42d095410dd..8ba45caf22a3 100644 --- a/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/AbstractEnvironmentInitializationFilter.java +++ b/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/EnvironmentInitializationFilter.java @@ -14,6 +14,7 @@ import org.eclipse.che.commons.subject.Subject; import org.eclipse.che.commons.subject.SubjectImpl; +import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -27,12 +28,12 @@ import java.security.Principal; /** - * The class contains commons business logic for all environment workspace id initialization filters. The filters are necessary to set - * workspace meta information to environment context. + * Fills environment context with information about current subject. * * @author Dmitry Shnurenko */ -public abstract class AbstractEnvironmentInitializationFilter implements Filter { +@Singleton +public class EnvironmentInitializationFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -50,23 +51,12 @@ public final void doFilter(ServletRequest request, ServletResponse response, Fil try { environmentContext.setSubject(subject); - environmentContext.setWorkspaceId(getWorkspaceId(request)); - filterChain.doFilter(addUserInRequest(httpRequest, subject), response); } finally { EnvironmentContext.reset(); } } - /** - * Extracts workspace id from request. - * - * @param request - * request which contains workspace id - * @return workspace id - */ - protected abstract String getWorkspaceId(ServletRequest request); - private HttpServletRequest addUserInRequest(final HttpServletRequest httpRequest, final Subject subject) { return new HttpServletRequestWrapper(httpRequest) { @Override @@ -76,12 +66,7 @@ public String getRemoteUser() { @Override public Principal getUserPrincipal() { - return new Principal() { - @Override - public String getName() { - return subject.getUserName(); - } - }; + return () -> subject.getUserName(); } }; } diff --git a/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/WsMasterEnvironmentInitializationFilter.java b/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/WsMasterEnvironmentInitializationFilter.java deleted file mode 100644 index 5aac8155ecb8..000000000000 --- a/wsmaster/wsmaster-local/src/main/java/org/eclipse/che/api/local/filters/WsMasterEnvironmentInitializationFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2016 Codenvy, S.A. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Codenvy, S.A. - initial API and implementation - *******************************************************************************/ -package org.eclipse.che.api.local.filters; - -import com.google.inject.Singleton; - -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; - -/** - * The filter contains business logic which extracts workspace id and sets it to environment context. Workspace id - * has defined place in URL. The filter mapped for all requests to master API. - * - * @author Dmitry Shnurenko - */ -@Singleton -public class WsMasterEnvironmentInitializationFilter extends AbstractEnvironmentInitializationFilter { - - /** - * The index of workspace id inside request uri. - */ - private static final int WORKSPACE_ID_INDEX = 4; - - @Override - protected String getWorkspaceId(ServletRequest request) { - String requestUri = ((HttpServletRequest)request).getRequestURI(); - String[] uriParts = requestUri.split("/"); - - if (uriParts.length >= 5) { - String workspaceId = uriParts[WORKSPACE_ID_INDEX]; - - if (workspaceId.startsWith("workspace")) { - return workspaceId; - } - } - - return ""; - } -} From 621a06c76fe780c99ae4af83a49edb3f9662299d Mon Sep 17 00:00:00 2001 From: Mario Loriedo Date: Wed, 20 Jul 2016 18:27:12 +0200 Subject: [PATCH 06/24] che-launcher infer Che version and self destruct itself (#1881) Signed-off-by: Mario Loriedo --- dockerfiles/che-launcher/launcher.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/dockerfiles/che-launcher/launcher.sh b/dockerfiles/che-launcher/launcher.sh index 12926184a53b..28d34b2971eb 100755 --- a/dockerfiles/che-launcher/launcher.sh +++ b/dockerfiles/che-launcher/launcher.sh @@ -30,7 +30,7 @@ init_global_variables() { DEFAULT_DOCKER_HOST_IP=$(get_docker_host_ip) DEFAULT_CHE_HOSTNAME=$(get_che_hostname) DEFAULT_CHE_PORT="8080" - DEFAULT_CHE_VERSION="latest" + DEFAULT_CHE_VERSION=$(get_che_launcher_version) DEFAULT_CHE_RESTART_POLICY="no" DEFAULT_CHE_USER="root" DEFAULT_CHE_LOG_LEVEL="info" @@ -139,6 +139,16 @@ print_debug_info() { debug "---------------------------------------" } +get_che_launcher_container_id() { + hostname +} + +get_che_launcher_version() { + LAUNCHER_CONTAINER_ID=$(get_che_launcher_container_id) + LAUNCHER_IMAGE_NAME=$(docker inspect --format='{{.Config.Image}}' "${LAUNCHER_CONTAINER_ID}") + echo "${LAUNCHER_IMAGE_NAME}" | cut -d : -f2 +} + is_boot2docker() { if uname -r | grep -q 'boot2docker'; then return 0 @@ -428,3 +438,6 @@ case ${CHE_SERVER_ACTION} in print_debug_info ;; esac + +# This container will self destruct after execution +docker rm -f "$(get_che_launcher_container_id)" > /dev/null 2>&1 From 3d9060f4aeddca01bf109262e371370ba99b104d Mon Sep 17 00:00:00 2001 From: Florent BENOIT Date: Thu, 21 Jul 2016 20:51:32 +0200 Subject: [PATCH 07/24] Add docker image to grab the ip used by docker (#1891) Change-Id: Id781e34c99f14c87909197b99969d645268e62d3 Signed-off-by: Florent BENOIT --- dockerfiles/che-ip/Dockerfile | 17 +++++++++++++++++ dockerfiles/che-ip/getip.sh | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 dockerfiles/che-ip/Dockerfile create mode 100755 dockerfiles/che-ip/getip.sh diff --git a/dockerfiles/che-ip/Dockerfile b/dockerfiles/che-ip/Dockerfile new file mode 100644 index 000000000000..c9f6902d516a --- /dev/null +++ b/dockerfiles/che-ip/Dockerfile @@ -0,0 +1,17 @@ +# Copyright (c) 2016 Codenvy, S.A. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# To build, in this directory: +# `docker build -t codenvy/che-ip .` +# +# To use it: +# `docker run --rm --net=host codenvy/che-ip` + +FROM alpine:3.4 + +ADD getip.sh /bin/getip.sh + +CMD /bin/getip.sh diff --git a/dockerfiles/che-ip/getip.sh b/dockerfiles/che-ip/getip.sh new file mode 100755 index 000000000000..25a582e17d62 --- /dev/null +++ b/dockerfiles/che-ip/getip.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Copyright (c) 2012-2016 Codenvy, S.A., Red Hat, Inc +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html + + +# return true if system is using boot2docker +is_boot2docker() { + if uname -r | grep -q 'boot2docker'; then + return 0 + else + return 1 + fi +} + +# network interface to use to grab local ip +NETWORK_IF="eth0" +if is_boot2docker; then + NETWORK_IF="eth1" +fi + +# grab ip from the following command +ip a show "${NETWORK_IF}" | \ + grep 'inet ' | \ + cut -d/ -f1 | \ + awk '{print $2}' + From 51903bfdcd5b008f21e21be4337b531191358cf2 Mon Sep 17 00:00:00 2001 From: Florent BENOIT Date: Thu, 21 Jul 2016 20:53:18 +0200 Subject: [PATCH 08/24] Fix the ENV about configuration folder to set when using docker image in the launcher (#1896) Change-Id: Ic88018709671e36e23fbceeb9e5cee5dd5ee0129 Signed-off-by: Florent BENOIT --- dockerfiles/che-launcher/launcher.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dockerfiles/che-launcher/launcher.sh b/dockerfiles/che-launcher/launcher.sh index 28d34b2971eb..4df9d7a034bf 100755 --- a/dockerfiles/che-launcher/launcher.sh +++ b/dockerfiles/che-launcher/launcher.sh @@ -48,7 +48,7 @@ init_global_variables() { # CHE_CONF_ARGS are the Docker run options that need to be used if users set CHE_CONF_FOLDER: # - empty if CHE_CONF_FOLDER is not set # - -v ${CHE_CONF_FOLDER}:/conf -e "CHE_LOCAL_CONF_DIR=/conf" if CHE_CONF_FOLDER is set - CHE_CONF_ARGS=${CHE_CONF_FOLDER:+-v ${CHE_CONF_FOLDER}:/conf -e \"CHE_LOCAL_CONF_DIR=/conf\"} + CHE_CONF_ARGS=${CHE_CONF_FOLDER:+-v ${CHE_CONF_FOLDER}:/conf -e CHE_LOCAL_CONF_DIR=/conf} CHE_LOCAL_BINARY_ARGS=${CHE_LOCAL_BINARY:+-v ${CHE_LOCAL_BINARY}:/home/user/che} if is_docker_for_mac || is_docker_for_windows; then From e69e1a5840af1b20ac365193a4d6143d6748e65c Mon Sep 17 00:00:00 2001 From: Oleksii Kurinnyi Date: Fri, 22 Jul 2016 13:48:47 +0300 Subject: [PATCH 09/24] #1903: fix export a workspace from the Dashboard Signed-off-by: Oleksii Kurinnyi --- dashboard/bower.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/bower.json b/dashboard/bower.json index 0ff01351a6f3..087ebb12b1a8 100644 --- a/dashboard/bower.json +++ b/dashboard/bower.json @@ -33,7 +33,7 @@ "zeroclipboard": "2.2.0", "angular-uuid4": "0.3.0", "angular-file-upload": "2.0.0", - "jquery": "1.8.1" + "jquery": "2.1.3" }, "devDependencies": { }, From 4fdecd8d97172763d1072ce339015ab0861a203b Mon Sep 17 00:00:00 2001 From: Max Shaposhnik Date: Fri, 22 Jul 2016 15:25:20 +0300 Subject: [PATCH 10/24] CHE-1893; fix authorization flow during clone from private repo (#1905) --- .../che/git/impl/jgit/JGitConnection.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java index bde03f88bd4d..2ef753170d68 100644 --- a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java +++ b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java @@ -11,6 +11,7 @@ *******************************************************************************/ package org.eclipse.che.git.impl.jgit; +import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; @@ -51,6 +52,7 @@ import org.eclipse.che.api.git.shared.MergeRequest; import org.eclipse.che.api.git.shared.MergeResult; import org.eclipse.che.api.git.shared.MoveRequest; +import org.eclipse.che.api.git.shared.ProviderInfo; import org.eclipse.che.api.git.shared.PullRequest; import org.eclipse.che.api.git.shared.PullResponse; import org.eclipse.che.api.git.shared.PushRequest; @@ -170,6 +172,8 @@ import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.eclipse.che.api.git.shared.ProviderInfo.AUTHENTICATE_URL; +import static org.eclipse.che.api.git.shared.ProviderInfo.PROVIDER_NAME; import static org.eclipse.che.dto.server.DtoFactory.newDto; /** @@ -1564,12 +1568,12 @@ public boolean accept(File dir) { */ private Object executeRemoteCommand(String remoteUrl, TransportCommand command) throws GitException, GitAPIException, UnauthorizedException { - String sshKeyDirectoryPath = ""; + File keyDirectory = null; + UserCredential credentials = null; try { if (GitUrlUtils.isSSH(remoteUrl)) { - File keyDirectory = Files.createTempDir(); - sshKeyDirectoryPath = keyDirectory.getPath(); - File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory); + keyDirectory = Files.createTempDir(); + final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory); SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override @@ -1593,7 +1597,7 @@ public void configure(Transport transport) { } }); } else { - UserCredential credentials = credentialsLoader.getUserCredential(remoteUrl); + credentials = credentialsLoader.getUserCredential(remoteUrl); if (credentials != null) { command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword())); @@ -1604,16 +1608,25 @@ public void configure(Transport transport) { return command.call(); } catch (GitException | TransportException exception) { - if ("Unable get private ssh key".equals(exception.getMessage()) - || exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) { - throw new UnauthorizedException(exception.getMessage()); + if ("Unable get private ssh key".equals(exception.getMessage())) { + throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY); + } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) { + final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl); + if (info != null) { + throw new UnauthorizedException(exception.getMessage(), + ErrorCodes.UNAUTHORIZED_GIT_OPERATION, + ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), + AUTHENTICATE_URL, info.getAuthenticateUrl(), + "authenticated", Boolean.toString(credentials != null))); + } + throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION); } else { throw exception; } } finally { - if (!sshKeyDirectoryPath.isEmpty()) { + if (keyDirectory != null && keyDirectory.exists()) { try { - FileUtils.delete(new File(sshKeyDirectoryPath), FileUtils.RECURSIVE); + FileUtils.delete(keyDirectory, FileUtils.RECURSIVE); } catch (IOException exception) { throw new GitException("Can't remove SSH key directory", exception); } From 826f637a7aba2065628ac3cb841db8d6624f6437 Mon Sep 17 00:00:00 2001 From: Sergii Kabashniuk Date: Fri, 22 Jul 2016 15:39:19 +0300 Subject: [PATCH 11/24] Code cleanup --- .../che/wsagent/server/WsAgentAnalyticsAddresser.java | 8 ++++---- .../che/api/deploy/WsMasterAnalyticsAddresser.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentAnalyticsAddresser.java b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentAnalyticsAddresser.java index c27b86efa735..77b80e457555 100644 --- a/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentAnalyticsAddresser.java +++ b/assembly/assembly-wsagent-war/src/main/java/org/eclipse/che/wsagent/server/WsAgentAnalyticsAddresser.java @@ -30,15 +30,15 @@ public class WsAgentAnalyticsAddresser { void send() { HttpURLConnection connection = null; try { - final URL url = new URL("https://install.codenvycorp.com/che/telemetry/workspace"); + final URL url = new URL("https://install.codenvycorp.com/che/init/workspace"); connection = (HttpsURLConnection)url.openConnection(); connection.getResponseCode(); } catch (IOException e) { LOG.error("Failed to send agent analytics", e); } finally { - if (connection != null) { - connection.disconnect(); - } + if (connection != null) { + connection.disconnect(); + } } } } diff --git a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterAnalyticsAddresser.java b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterAnalyticsAddresser.java index 67b7419fb652..d2c839eb4ee4 100644 --- a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterAnalyticsAddresser.java +++ b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterAnalyticsAddresser.java @@ -30,7 +30,7 @@ public class WsMasterAnalyticsAddresser { void send() { HttpURLConnection connection = null; try { - final URL url = new URL("https://install.codenvycorp.com/che/telemetry/master"); + final URL url = new URL("https://install.codenvycorp.com/che/init/server"); connection = (HttpsURLConnection)url.openConnection(); connection.getResponseCode(); } catch (IOException e) { From e0db4445cc8af290ca1c63f1374a5f0e11c178f4 Mon Sep 17 00:00:00 2001 From: Mario Loriedo Date: Fri, 22 Jul 2016 15:42:54 +0200 Subject: [PATCH 12/24] [Replaces #1885] Launcher: fixed Path problems, splitted in 3 files and added tests (#1914) * Fix environment variables for CHE_DATA_FOLDER Cleaned up syntax so that the variables will work on Windows. Signed-off-by: Mario Loriedo * Launcher: fixed Path problems, splitted in 3 files and added tests Signed-off-by: Mario Loriedo * Launcher tests: added instructions to run bats tests --- dockerfiles/che-launcher/Dockerfile | 10 +- dockerfiles/che-launcher/launcher.sh | 139 ++---------- dockerfiles/che-launcher/launcher_cmds.sh | 124 +++++++++++ dockerfiles/che-launcher/launcher_funcs.sh | 224 ++++++++++++++++++++ dockerfiles/che-launcher/launcher_test.bats | 40 ++++ 5 files changed, 411 insertions(+), 126 deletions(-) create mode 100644 dockerfiles/che-launcher/launcher_cmds.sh create mode 100644 dockerfiles/che-launcher/launcher_funcs.sh create mode 100644 dockerfiles/che-launcher/launcher_test.bats diff --git a/dockerfiles/che-launcher/Dockerfile b/dockerfiles/che-launcher/Dockerfile index 2d25f8c1643c..4e58cc48e0a8 100644 --- a/dockerfiles/che-launcher/Dockerfile +++ b/dockerfiles/che-launcher/Dockerfile @@ -11,10 +11,10 @@ # `docker build -t codenvy/che-launcher .` # # To use it: -# `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock codenvy/che start` -# `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock codenvy/che stop` -# `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock codenvy/che restart` -# `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock codenvy/che update` +# `docker run -v /var/run/docker.sock:/var/run/docker.sock codenvy/che start` +# `docker run -v /var/run/docker.sock:/var/run/docker.sock codenvy/che stop` +# `docker run -v /var/run/docker.sock:/var/run/docker.sock codenvy/che restart` +# `docker run -v /var/run/docker.sock:/var/run/docker.sock codenvy/che update` # FROM alpine:3.4 @@ -31,6 +31,8 @@ RUN set -x \ && curl -sL "https://${DOCKER_BUCKET}/builds/Linux/x86_64/docker-$DOCKER_VERSION" \ > /usr/bin/docker; chmod +x /usr/bin/docker +COPY /launcher_cmds.sh /bin/launcher_cmds.sh +COPY /launcher_funcs.sh /bin/launcher_funcs.sh COPY /launcher.sh /bin/launcher.sh ENTRYPOINT ["bin/launcher.sh"] diff --git a/dockerfiles/che-launcher/launcher.sh b/dockerfiles/che-launcher/launcher.sh index 4df9d7a034bf..2d489918d7b1 100755 --- a/dockerfiles/che-launcher/launcher.sh +++ b/dockerfiles/che-launcher/launcher.sh @@ -9,6 +9,10 @@ # Mario Loriedo - Initial implementation # +launcher_dir="$(dirname "$0")" +source "$launcher_dir/launcher_funcs.sh" +source "$launcher_dir/launcher_cmds.sh" + init_logging() { BLUE='\033[1;34m' GREEN='\033[0;32m' @@ -36,6 +40,10 @@ init_global_variables() { DEFAULT_CHE_LOG_LEVEL="info" DEFAULT_CHE_DATA_FOLDER="/home/user/che" + # Clean eventual user provided paths + CHE_CONF_FOLDER=${CHE_CONF_FOLDER:+$(get_clean_path ${CHE_CONF_FOLDER})} + CHE_DATA_FOLDER=${CHE_DATA_FOLDER:+$(get_clean_path ${CHE_DATA_FOLDER})} + CHE_HOSTNAME=${CHE_HOSTNAME:-${DEFAULT_CHE_HOSTNAME}} CHE_PORT=${CHE_PORT:-${DEFAULT_CHE_PORT}} CHE_VERSION=${CHE_VERSION:-${DEFAULT_CHE_VERSION}} @@ -48,16 +56,16 @@ init_global_variables() { # CHE_CONF_ARGS are the Docker run options that need to be used if users set CHE_CONF_FOLDER: # - empty if CHE_CONF_FOLDER is not set # - -v ${CHE_CONF_FOLDER}:/conf -e "CHE_LOCAL_CONF_DIR=/conf" if CHE_CONF_FOLDER is set - CHE_CONF_ARGS=${CHE_CONF_FOLDER:+-v ${CHE_CONF_FOLDER}:/conf -e CHE_LOCAL_CONF_DIR=/conf} + CHE_CONF_ARGS=${CHE_CONF_FOLDER:+-v "${CHE_CONF_FOLDER}":/conf -e "CHE_LOCAL_CONF_DIR=/conf"} CHE_LOCAL_BINARY_ARGS=${CHE_LOCAL_BINARY:+-v ${CHE_LOCAL_BINARY}:/home/user/che} if is_docker_for_mac || is_docker_for_windows; then - CHE_STORAGE_ARGS=${CHE_DATA_FOLDER:+-v ${CHE_DATA_FOLDER}/storage:/home/user/che/storage \ - -e \"CHE_WORKSPACE_STORAGE=${CHE_DATA_FOLDER}/workspaces\" \ - -e \"CHE_WORKSPACE_STORAGE_CREATE_FOLDERS=false\"} + CHE_STORAGE_ARGS=${CHE_DATA_FOLDER:+-v "${CHE_DATA_FOLDER}/storage":/home/user/che/storage \ + -e "CHE_WORKSPACE_STORAGE=${CHE_DATA_FOLDER}/workspaces" \ + -e "CHE_WORKSPACE_STORAGE_CREATE_FOLDERS=false"} else - CHE_STORAGE_ARGS=${CHE_DATA_FOLDER:+-v ${CHE_DATA_FOLDER}/storage:/home/user/che/storage \ - -v ${CHE_DATA_FOLDER}/workspaces:/home/user/che/workspaces} + CHE_STORAGE_ARGS=${CHE_DATA_FOLDER:+-v "${CHE_DATA_FOLDER}/storage":/home/user/che/storage \ + -v "${CHE_DATA_FOLDER}/workspaces":/home/user/che/workspaces} fi if [ "${CHE_LOG_LEVEL}" = "debug" ]; then @@ -274,19 +282,10 @@ server_is_booted() { fi } -wait_until_server_is_booted () { - SERVER_BOOT_TIMEOUT=${1} - - ELAPSED=0 - until server_is_booted || [ ${ELAPSED} -eq "${SERVER_BOOT_TIMEOUT}" ]; do - sleep 1 - ELAPSED=$((ELAPSED+1)) - done -} - parse_command_line () { if [ $# -eq 0 ]; then usage + container_self_destruction exit fi @@ -297,6 +296,7 @@ parse_command_line () { ;; -h|--help) usage + container_self_destruction exit ;; *) @@ -307,111 +307,6 @@ parse_command_line () { done } -start_che_server() { - if che_container_exist; then - error_exit "A container named \"${CHE_SERVER_CONTAINER_NAME}\" already exists. Please remove it manually (docker rm -f ${CHE_SERVER_CONTAINER_NAME}) and try again." - fi - - CURRENT_IMAGE=$(docker images -q "${CHE_SERVER_IMAGE_NAME}":"${CHE_VERSION}") - - if [ "${CURRENT_IMAGE}" != "" ]; then - info "ECLIPSE CHE: ALREADY HAVE IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION}" - else - update_che_server - fi - - info "ECLIPSE CHE: CONTAINER STARTING" - docker run -d --name "${CHE_SERVER_CONTAINER_NAME}" \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v /home/user/che/lib:/home/user/che/lib-copy \ - ${CHE_LOCAL_BINARY_ARGS} \ - -p "${CHE_PORT}":8080 \ - --restart="${CHE_RESTART_POLICY}" \ - --user="${CHE_USER}" \ - ${CHE_CONF_ARGS} \ - ${CHE_STORAGE_ARGS} \ - "${CHE_SERVER_IMAGE_NAME}":"${CHE_VERSION}" \ - --remote:"${CHE_HOST_IP}" \ - -s:uid \ - -s:client \ - ${CHE_DEBUG_OPTION} \ - run > /dev/null - - wait_until_container_is_running 10 - if ! che_container_is_running; then - error_exit "ECLIPSE CHE: Timeout waiting Che container to start." - fi - - info "ECLIPSE CHE: SERVER LOGS AT \"docker logs -f ${CHE_SERVER_CONTAINER_NAME}\"" - info "ECLIPSE CHE: SERVER BOOTING..." - wait_until_server_is_booted 20 - - if server_is_booted; then - info "ECLIPSE CHE: BOOTED AND REACHABLE" - info "ECLIPSE CHE: http://${CHE_HOSTNAME}:${CHE_PORT}" - else - error_exit "ECLIPSE CHE: Timeout waiting Che server to boot. Run \"docker logs ${CHE_SERVER_CONTAINER_NAME}\" to see the logs." - fi -} - -execute_command_with_progress() { - progress=$1 - command=$2 - shift 2 - - pid="" - printf "\n" - - case "$progress" in - extended) - $command "$@" - ;; - basic|*) - $command "$@" &>/dev/null & - pid=$! - while kill -0 "$pid" >/dev/null 2>&1; do - printf "#" - sleep 10 - done - wait $pid # return pid's exit code - printf "\n" - ;; - esac - printf "\n" -} - -stop_che_server() { - if ! che_container_is_running; then - info "-------------------------------------------------------" - info "ECLIPSE CHE: CONTAINER IS NOT RUNNING. NOTHING TO DO." - info "-------------------------------------------------------" - else - info "ECLIPSE CHE: STOPPING SERVER..." - docker exec ${CHE_SERVER_CONTAINER_NAME} /home/user/che/bin/che.sh -c stop > /dev/null 2>&1 - sleep 5 - info "ECLIPSE CHE: REMOVING CONTAINER" - docker rm -f ${CHE_SERVER_CONTAINER_NAME} > /dev/null 2>&1 - info "ECLIPSE CHE: STOPPED" - fi -} - -restart_che_server() { - if che_container_is_running; then - stop_che_server - fi - start_che_server -} - -update_che_server() { - if [ -z "${CHE_VERSION}" ]; then - CHE_VERSION=${DEFAULT_CHE_VERSION} - fi - - info "ECLIPSE CHE: PULLING IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION}" - execute_command_with_progress extended docker pull ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION} - info "ECLIPSE CHE: IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION} INSTALLED" -} - # See: https://sipb.mit.edu/doc/safe-shell/ set -e set -u @@ -440,4 +335,4 @@ case ${CHE_SERVER_ACTION} in esac # This container will self destruct after execution -docker rm -f "$(get_che_launcher_container_id)" > /dev/null 2>&1 +container_self_destruction diff --git a/dockerfiles/che-launcher/launcher_cmds.sh b/dockerfiles/che-launcher/launcher_cmds.sh new file mode 100644 index 000000000000..aad56ed8be4d --- /dev/null +++ b/dockerfiles/che-launcher/launcher_cmds.sh @@ -0,0 +1,124 @@ +#!/bin/sh +# Copyright (c) 2012-2016 Codenvy, S.A., Red Hat, Inc +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Mario Loriedo - Initial implementation +# + +start_che_server() { + if che_container_exist; then + error_exit "A container named \"${CHE_SERVER_CONTAINER_NAME}\" already exists. Please remove it manually (docker rm -f ${CHE_SERVER_CONTAINER_NAME}) and try again." + fi + + CURRENT_IMAGE=$(docker images -q "${CHE_SERVER_IMAGE_NAME}":"${CHE_VERSION}") + + if [ "${CURRENT_IMAGE}" != "" ]; then + info "ECLIPSE CHE: ALREADY HAVE IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION}" + else + update_che_server + fi + + info "ECLIPSE CHE: CONTAINER STARTING" + docker run -d --name "${CHE_SERVER_CONTAINER_NAME}" \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v /home/user/che/lib:/home/user/che/lib-copy \ + ${CHE_LOCAL_BINARY_ARGS} \ + -p "${CHE_PORT}":8080 \ + --restart="${CHE_RESTART_POLICY}" \ + --user="${CHE_USER}" \ + ${CHE_CONF_ARGS} \ + ${CHE_STORAGE_ARGS} \ + "${CHE_SERVER_IMAGE_NAME}":"${CHE_VERSION}" \ + --remote:"${CHE_HOST_IP}" \ + -s:uid \ + -s:client \ + ${CHE_DEBUG_OPTION} \ + run > /dev/null + + wait_until_container_is_running 10 + if ! che_container_is_running; then + error_exit "ECLIPSE CHE: Timeout waiting Che container to start." + fi + + info "ECLIPSE CHE: SERVER LOGS AT \"docker logs -f ${CHE_SERVER_CONTAINER_NAME}\"" + info "ECLIPSE CHE: SERVER BOOTING..." + wait_until_server_is_booted 20 + + if server_is_booted; then + info "ECLIPSE CHE: BOOTED AND REACHABLE" + info "ECLIPSE CHE: http://${CHE_HOSTNAME}:${CHE_PORT}" + else + error_exit "ECLIPSE CHE: Timeout waiting Che server to boot. Run \"docker logs ${CHE_SERVER_CONTAINER_NAME}\" to see the logs." + fi +} + +stop_che_server() { + if ! che_container_is_running; then + info "-------------------------------------------------------" + info "ECLIPSE CHE: CONTAINER IS NOT RUNNING. NOTHING TO DO." + info "-------------------------------------------------------" + else + info "ECLIPSE CHE: STOPPING SERVER..." + docker exec ${CHE_SERVER_CONTAINER_NAME} /home/user/che/bin/che.sh -c stop > /dev/null 2>&1 + sleep 5 + info "ECLIPSE CHE: REMOVING CONTAINER" + docker rm -f ${CHE_SERVER_CONTAINER_NAME} > /dev/null 2>&1 + info "ECLIPSE CHE: STOPPED" + fi +} + +restart_che_server() { + if che_container_is_running; then + stop_che_server + fi + start_che_server +} + +update_che_server() { + if [ -z "${CHE_VERSION}" ]; then + CHE_VERSION=${DEFAULT_CHE_VERSION} + fi + + info "ECLIPSE CHE: PULLING IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION}" + execute_command_with_progress extended docker pull ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION} + info "ECLIPSE CHE: IMAGE ${CHE_SERVER_IMAGE_NAME}:${CHE_VERSION} INSTALLED" +} + +print_debug_info() { + debug "---------------------------------------" + debug "--------- CHE DEBUG INFO -----------" + debug "---------------------------------------" + debug "" + debug "DOCKER_INSTALL_TYPE = ${DOCKER_INSTALL_TYPE}" + debug "" + debug "CHE_SERVER_CONTAINER_NAME = ${CHE_SERVER_CONTAINER_NAME}" + debug "CHE_SERVER_IMAGE_NAME = ${CHE_SERVER_IMAGE_NAME}" + debug "" + VAL=$(if che_container_exist;then echo "YES"; else echo "NO"; fi) + debug "CHE CONTAINER EXISTS? ${VAL}" + VAL=$(if che_container_is_running;then echo "YES"; else echo "NO"; fi) + debug "CHE CONTAINER IS RUNNING? ${VAL}" + VAL=$(if che_container_is_stopped;then echo "YES"; else echo "NO"; fi) + debug "CHE CONTAINER IS STOPPED? ${VAL}" + VAL=$(if server_is_booted;then echo "YES"; else echo "NO"; fi) + debug "CHE SERVER IS BOOTED? ${VAL}" + debug "" + debug "CHE_PORT = ${CHE_PORT}" + debug "CHE_VERSION = ${CHE_VERSION}" + debug "CHE_RESTART_POLICY = ${CHE_RESTART_POLICY}" + debug "CHE_USER = ${CHE_USER}" + debug "CHE_HOST_IP = ${CHE_HOST_IP}" + debug "CHE_LOG_LEVEL = ${CHE_LOG_LEVEL}" + debug "CHE_HOSTNAME = ${CHE_HOSTNAME}" + debug "CHE_DATA_FOLDER = ${CHE_DATA_FOLDER}" + debug "CHE_CONF_FOLDER = ${CHE_CONF_FOLDER:-not set}" + debug "CHE_LOCAL_BINARY = ${CHE_LOCAL_BINARY:-not set}" + debug "" + debug "---------------------------------------" + debug "---------------------------------------" + debug "---------------------------------------" +} diff --git a/dockerfiles/che-launcher/launcher_funcs.sh b/dockerfiles/che-launcher/launcher_funcs.sh new file mode 100644 index 000000000000..9a00f5f78fc4 --- /dev/null +++ b/dockerfiles/che-launcher/launcher_funcs.sh @@ -0,0 +1,224 @@ +#!/bin/sh +# Copyright (c) 2012-2016 Codenvy, S.A., Red Hat, Inc +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Mario Loriedo - Initial implementation +# + +usage () { + printf "%s" "${USAGE}" +} + +info() { + printf "${GREEN}INFO:${NC} %s\n" "${1}" +} + +debug() { + printf "${BLUE}DEBUG:${NC} %s\n" "${1}" +} + +error() { + printf "${RED}ERROR:${NC} %s\n" "${1}" +} + +error_exit() { + echo "---------------------------------------" + error "!!!" + error "!!! ${1}" + error "!!!" + echo "---------------------------------------" + container_self_destruction + exit 1 +} + +get_clean_path() { + INPUT_PATH=$1 + # \some\path => /some/path + OUTPUT_PATH=$(echo ${INPUT_PATH} | tr '\\' '/') + # /somepath/ => /somepath + OUTPUT_PATH=${OUTPUT_PATH%/} + # /some//path => /some/path + OUTPUT_PATH=$(echo ${OUTPUT_PATH} | tr -s '/') + # "/some/path" => /some/path + OUTPUT_PATH=${OUTPUT_PATH//\"} + echo ${OUTPUT_PATH} +} + +get_che_launcher_container_id() { + hostname +} + +get_che_launcher_version() { + LAUNCHER_CONTAINER_ID=$(get_che_launcher_container_id) + LAUNCHER_IMAGE_NAME=$(docker inspect --format='{{.Config.Image}}' "${LAUNCHER_CONTAINER_ID}") + echo "${LAUNCHER_IMAGE_NAME}" | cut -d : -f2 +} + +is_boot2docker() { + if uname -r | grep -q 'boot2docker'; then + return 0 + else + return 1 + fi +} + +has_docker_for_windows_ip() { + DOCKER_HOST_IP=$(get_docker_host_ip) + if [ "${DOCKER_HOST_IP}" = "10.0.75.2" ]; then + return 0 + else + return 1 + fi +} + +is_docker_for_mac() { + if uname -r | grep -q 'moby' && ! has_docker_for_windows_ip; then + return 0 + else + return 1 + fi +} + +is_docker_for_windows() { + if uname -r | grep -q 'moby' && has_docker_for_windows_ip; then + return 0 + else + return 1 + fi +} + +get_docker_install_type() { + if is_boot2docker; then + echo "boot2docker" + elif is_docker_for_windows; then + echo "docker4windows" + elif is_docker_for_mac; then + echo "docker4mac" + else + echo "native" + fi +} + +get_docker_host_ip() { + NETWORK_IF="eth0" + if is_boot2docker; then + NETWORK_IF="eth1" + fi + + docker run --rm --net host \ + alpine sh -c \ + "ip a show ${NETWORK_IF}" | \ + grep 'inet ' | \ + cut -d/ -f1 | \ + awk '{ print $2}' +} + +get_che_hostname() { + INSTALL_TYPE=$(get_docker_install_type) + if [ "${INSTALL_TYPE}" = "boot2docker" ] || + [ "${INSTALL_TYPE}" = "docker4windows" ]; then + get_docker_host_ip + else + echo "localhost" + fi +} + +check_docker() { + if [ ! -S /var/run/docker.sock ]; then + error_exit "Docker socket (/var/run/docker.sock) hasn't be mounted \ +inside the container. Verify the syntax of the \"docker run\" command." + fi + + if ! docker ps > /dev/null 2>&1; then + output=$(docker ps) + error_exit "Error when running \"docker ps\": ${output}" + fi +} + +che_container_exist() { + if [ "$(docker ps -aq -f "name=${CHE_SERVER_CONTAINER_NAME}" | wc -l)" = "0" ]; then + return 1 + else + return 0 + fi +} + +che_container_is_running() { + if [ "$(docker ps -qa -f "status=running" -f "name=${CHE_SERVER_CONTAINER_NAME}" | wc -l)" = "0" ]; then + return 1 + else + return 0 + fi +} + +che_container_is_stopped() { + if [ "$(docker ps -qa -f "status=exited" -f "name=${CHE_SERVER_CONTAINER_NAME}" | wc -l)" = "0" ]; then + return 1 + else + return 0 + fi +} + +wait_until_container_is_running() { + CONTAINER_START_TIMEOUT=${1} + + ELAPSED=0 + until che_container_is_running || [ ${ELAPSED} -eq "${CONTAINER_START_TIMEOUT}" ]; do + sleep 1 + ELAPSED=$((ELAPSED+1)) + done +} + +server_is_booted() { + HTTP_STATUS_CODE=$(curl -I http://"${CHE_HOST_IP}":"${CHE_PORT}"/api/ \ + -s -o /dev/null --write-out "%{http_code}") + if [ "${HTTP_STATUS_CODE}" = "200" ]; then + return 0 + else + return 1 + fi +} + +wait_until_server_is_booted () { + SERVER_BOOT_TIMEOUT=${1} + + ELAPSED=0 + until server_is_booted || [ ${ELAPSED} -eq "${SERVER_BOOT_TIMEOUT}" ]; do + sleep 1 + ELAPSED=$((ELAPSED+1)) + done +} + +execute_command_with_progress() { + progress=$1 + command=$2 + shift 2 + + pid="" + printf "\n" + + case "$progress" in + extended) + $command "$@" + ;; + basic|*) + $command "$@" &>/dev/null & + pid=$! + while kill -0 "$pid" >/dev/null 2>&1; do + printf "#" + sleep 10 + done + wait $pid # return pid's exit code + printf "\n" + ;; + esac + printf "\n" +} + +container_self_destruction() { + docker rm -f "$(get_che_launcher_container_id)" > /dev/null 2>&1 +} diff --git a/dockerfiles/che-launcher/launcher_test.bats b/dockerfiles/che-launcher/launcher_test.bats new file mode 100644 index 000000000000..01ffcffba477 --- /dev/null +++ b/dockerfiles/che-launcher/launcher_test.bats @@ -0,0 +1,40 @@ +#!/usr/bin/env bats +# Copyright (c) 2012-2016 Codenvy, S.A., Red Hat, Inc +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Mario Loriedo - Initial implementation +# +# To run the tests: +# docker run -w /tests/ -v $PWD:/tests dduportal/bats:0.4.0 /tests/launcher_test.bats +# + +source ./launcher_funcs.sh + +@test "clean folder path that is already clean" { + result="$(get_clean_path /somefolder)" + [ "$result" = "/somefolder" ] +} + +@test "clean folder path with extra slash" { + result="$(get_clean_path /somefolder/)" + [ "$result" = "/somefolder" ] +} + +@test "clean folder path with two consecutive slashes" { + result="$(get_clean_path /some//path)" + [ "$result" = "/some/path" ] +} + +@test "clean folder path with backslashes" { + result="$(get_clean_path \\some\\path)" + [ "$result" = "/some/path" ] +} + +@test "clean folder path with quotes" { + result="$(get_clean_path \"/some\"/path\")" + [ "$result" = "/some/path" ] +} From 48c8f149bc7df9895c84fc9669017ab789d53d6f Mon Sep 17 00:00:00 2001 From: Florent BENOIT Date: Fri, 22 Jul 2016 16:35:52 +0200 Subject: [PATCH 13/24] Allow to continue to start the script even if there is a chown failure (#1917) When mounting a local folder with .git we have the following warnings chown: changing permission on ....git.idx : permission denied this new command allow to continue Change-Id: Idbedd1958e4a60a2aea251d1a657bbcdec063ffb Signed-off-by: Florent BENOIT --- .../main/java/org/eclipse/che/api/deploy/WsMasterModule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java index 54628a973084..bbc99a609396 100644 --- a/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java +++ b/assembly/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/WsMasterModule.java @@ -64,7 +64,7 @@ protected void configure() { bindConstant().annotatedWith(Names.named(org.eclipse.che.api.machine.server.wsagent.WsAgentLauncherImpl.WS_AGENT_PROCESS_START_COMMAND)) .to("rm -rf ~/che && mkdir -p ~/che && unzip -qq /mnt/che/ws-agent.zip -d ~/che/ws-agent && " + - "sudo chown -R $(id -u -n) /projects && " + + "sudo sh -c \"chown -R $(id -u -n) /projects || true\" && " + "export JPDA_ADDRESS=\"4403\" && ~/che/ws-agent/bin/catalina.sh jpda run"); bindConstant().annotatedWith(Names.named(org.eclipse.che.plugin.docker.machine.DockerMachineImplTerminalLauncher.START_TERMINAL_COMMAND)) .to("mkdir -p ~/che " + From f63d7a448dc678e87a38dbf6e24b6c80f6831ad1 Mon Sep 17 00:00:00 2001 From: Mihail Kuznyetsov Date: Wed, 20 Jul 2016 19:15:29 +0300 Subject: [PATCH 14/24] EVERREST-83 Update accordingly to the changes in Everrest --- .../che/api/core/rest/ApiInfoService.java | 8 ++--- .../che/everrest/CheMethodInvokerFilter.java | 8 ++--- .../che/everrest/ETagResponseFilter.java | 5 ++- .../EverrestDownloadFileResponseFilter.java | 5 ++- .../ServerContainerInitializeListener.java | 30 +++++++---------- .../WebSocketMethodInvokerDecorator.java | 5 ++- .../api/core/rest/ServiceDescriptorTest.java | 16 ++++++--- .../DownloadFileResponseFilterTest.java | 21 ++++++------ .../che/everrest/ETagResponseFilterTest.java | 21 ++++++------ .../api/project/server/ProjectService.java | 30 ++++++++--------- .../api/project/server/WorkspaceHolder.java | 4 +-- .../project/server/ProjectServiceTest.java | 33 ++++++++++--------- 12 files changed, 93 insertions(+), 93 deletions(-) diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ApiInfoService.java b/core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ApiInfoService.java index 80337d9db9a9..059e2bf1bc8d 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ApiInfoService.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ApiInfoService.java @@ -20,7 +20,7 @@ import org.eclipse.che.dto.server.DtoFactory; import org.everrest.core.ObjectFactory; import org.everrest.core.ResourceBinder; -import org.everrest.core.resource.AbstractResourceDescriptor; +import org.everrest.core.resource.ResourceDescriptor; import org.everrest.services.RestServicesList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -85,11 +85,11 @@ private ApiInfo readApiInfo() throws ServerException { public RestServicesList.RootResourcesList listJSON(@Context ServletContext context) { ResourceBinder binder = (ResourceBinder)context.getAttribute(ResourceBinder.class.getName()); return new RestServicesList.RootResourcesList(FluentIterable.from(binder.getResources()).transform( - new Function, RestServicesList.RootResource>() { + new Function, RestServicesList.RootResource>() { @Nullable @Override - public RestServicesList.RootResource apply(ObjectFactory input) { - AbstractResourceDescriptor descriptor = input.getObjectModel(); + public RestServicesList.RootResource apply(ObjectFactory input) { + ResourceDescriptor descriptor = input.getObjectModel(); return new RestServicesList.RootResource(descriptor.getObjectClass().getName(), // descriptor.getPathValue().getPath(), // descriptor.getUriPattern().getRegex()); diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheMethodInvokerFilter.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheMethodInvokerFilter.java index 8679a19ab3f0..0a2e65e13022 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheMethodInvokerFilter.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/CheMethodInvokerFilter.java @@ -19,7 +19,7 @@ import org.eclipse.che.api.core.UnauthorizedException; import org.eclipse.che.dto.server.DtoFactory; import org.everrest.core.method.MethodInvokerFilter; -import org.everrest.core.resource.GenericMethodResource; +import org.everrest.core.resource.GenericResourceMethod; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; @@ -33,7 +33,7 @@ */ public abstract class CheMethodInvokerFilter implements MethodInvokerFilter { @Override - public void accept(GenericMethodResource genericMethodResource, Object[] arguments) throws WebApplicationException { + public void accept(GenericResourceMethod genericMethodResource, Object[] arguments) throws WebApplicationException { try { filter(genericMethodResource, arguments); } catch (ApiException exception) { @@ -83,11 +83,11 @@ else if (exception instanceof BadRequestException) { * Check does supplied method can be invoked. * * @param genericMethodResource - * See {@link GenericMethodResource} + * See {@link GenericResourceMethod} * @param arguments * actual method arguments that were created from request * @throws ApiException * if method can not be invoked cause current environment context, e.g. for current user, with current request attributes, etc. */ - protected abstract void filter(GenericMethodResource genericMethodResource, Object[] arguments) throws ApiException; + protected abstract void filter(GenericResourceMethod genericMethodResource, Object[] arguments) throws ApiException; } diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ETagResponseFilter.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ETagResponseFilter.java index 81bef1ccb782..a5fcf9ce1c26 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ETagResponseFilter.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ETagResponseFilter.java @@ -20,7 +20,6 @@ import org.everrest.core.Filter; import org.everrest.core.GenericContainerResponse; import org.everrest.core.ResponseFilter; -import org.everrest.core.impl.ApplicationContextImpl; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.EntityTag; @@ -55,7 +54,7 @@ public enum EntityType { * Filter the given container response * * @param containerResponse - * the reponse to use + * the response to use */ public void doFilter(GenericContainerResponse containerResponse) { @@ -73,7 +72,7 @@ public void doFilter(GenericContainerResponse containerResponse) { } // Get the request - ApplicationContext applicationContext = ApplicationContextImpl.getCurrent(); + ApplicationContext applicationContext = ApplicationContext.getCurrent(); Request request = applicationContext.getRequest(); // manage only GET requests diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/EverrestDownloadFileResponseFilter.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/EverrestDownloadFileResponseFilter.java index 94898dfd9c7d..15e21bed4eee 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/EverrestDownloadFileResponseFilter.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/EverrestDownloadFileResponseFilter.java @@ -15,7 +15,6 @@ import org.everrest.core.Filter; import org.everrest.core.GenericContainerResponse; import org.everrest.core.ResponseFilter; -import org.everrest.core.impl.ApplicationContextImpl; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; @@ -33,13 +32,13 @@ public class EverrestDownloadFileResponseFilter extends DownloadFileResponseFilt * Filter the given container response. * * @param containerResponse - * the reponse to use + * the response to use */ public void doFilter(GenericContainerResponse containerResponse) { containerResponse.getResponse(); // Get the request - ApplicationContext applicationContext = ApplicationContextImpl.getCurrent(); + ApplicationContext applicationContext = ApplicationContext.getCurrent(); Request request = applicationContext.getRequest(); // Apply header if all if correct diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ServerContainerInitializeListener.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ServerContainerInitializeListener.java index 6374ce5cca83..12e224c3ff9a 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ServerContainerInitializeListener.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/ServerContainerInitializeListener.java @@ -10,6 +10,9 @@ *******************************************************************************/ package org.eclipse.che.everrest; +import com.google.common.base.MoreObjects; +import com.google.common.util.concurrent.ThreadFactoryBuilder; + import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.subject.Subject; import org.everrest.core.DependencySupplier; @@ -18,6 +21,8 @@ import org.everrest.core.impl.EverrestConfiguration; import org.everrest.core.impl.EverrestProcessor; import org.everrest.core.impl.ProviderBinder; +import org.everrest.core.impl.RequestDispatcher; +import org.everrest.core.impl.RequestHandlerImpl; import org.everrest.core.impl.provider.json.JsonException; import org.everrest.core.tools.SimplePrincipal; import org.everrest.core.tools.SimpleSecurityContext; @@ -47,14 +52,10 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicLong; import static javax.websocket.server.ServerEndpointConfig.Builder.create; import static javax.websocket.server.ServerEndpointConfig.Configurator; -import com.google.common.base.MoreObjects; - /** * @author andrew00x */ @@ -66,8 +67,6 @@ public class ServerContainerInitializeListener implements ServletContextListener public static final String EXECUTOR_ATTRIBUTE = "everrest.Executor"; public static final String SECURITY_CONTEXT = SecurityContext.class.getName(); - private static final AtomicLong sequence = new AtomicLong(1); - private WebApplicationDeclaredRoles webApplicationDeclaredRoles; private EverrestConfiguration everrestConfiguration; private ServerEndpointConfig wsServerEndpointConfig; @@ -161,9 +160,10 @@ protected EverrestProcessor getEverrestProcessor(ServletContext servletContext) final DependencySupplier dependencies = (DependencySupplier)servletContext.getAttribute(DependencySupplier.class.getName()); final ResourceBinder resources = (ResourceBinder)servletContext.getAttribute(ResourceBinder.class.getName()); final ProviderBinder providers = (ProviderBinder)servletContext.getAttribute(ApplicationProviderBinder.class.getName()); - final EverrestConfiguration copy = getEverrestConfiguration(servletContext); - copy.setProperty(EverrestConfiguration.METHOD_INVOKER_DECORATOR_FACTORY, WebSocketMethodInvokerDecoratorFactory.class.getName()); - return new EverrestProcessor(resources, providers, dependencies, copy, null); + final EverrestConfiguration copyOfEverrestConfiguration = new EverrestConfiguration(getEverrestConfiguration(servletContext)); + copyOfEverrestConfiguration.setProperty(EverrestConfiguration.METHOD_INVOKER_DECORATOR_FACTORY, WebSocketMethodInvokerDecoratorFactory.class.getName()); + final RequestHandlerImpl requestHandler = new RequestHandlerImpl(new RequestDispatcher(resources), providers); + return new EverrestProcessor(copyOfEverrestConfiguration, dependencies, requestHandler, null); } protected EverrestConfiguration getEverrestConfiguration(ServletContext servletContext) { @@ -172,15 +172,9 @@ protected EverrestConfiguration getEverrestConfiguration(ServletContext servletC protected ExecutorService createExecutor(final ServletContext servletContext) { final EverrestConfiguration everrestConfiguration = getEverrestConfiguration(servletContext); - return Executors.newFixedThreadPool(everrestConfiguration.getAsynchronousPoolSize(), new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - final Thread t = - new Thread(r, "everrest.WSConnection." + servletContext.getServletContextName() + sequence.getAndIncrement()); - t.setDaemon(true); - return t; - } - }); + final String threadNameFormat = "everrest.WSConnection." + servletContext.getServletContextName() + "-%d"; + return Executors.newFixedThreadPool(everrestConfiguration.getAsynchronousPoolSize(), + new ThreadFactoryBuilder().setNameFormat(threadNameFormat).setDaemon(true).build()); } protected SecurityContext createSecurityContext(final HandshakeRequest req) { diff --git a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java index e4abda6b033b..eba9e357888e 100644 --- a/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java +++ b/core/che-core-api-core/src/main/java/org/eclipse/che/everrest/WebSocketMethodInvokerDecorator.java @@ -17,8 +17,7 @@ import org.everrest.core.ApplicationContext; import org.everrest.core.impl.method.MethodInvokerDecorator; import org.everrest.core.method.MethodInvoker; -import org.everrest.core.resource.GenericMethodResource; -import org.everrest.websockets.ServerContainerInitializeListener; +import org.everrest.core.resource.GenericResourceMethod; import org.everrest.websockets.WSConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,7 +35,7 @@ class WebSocketMethodInvokerDecorator extends MethodInvokerDecorator { } @Override - public Object invokeMethod(Object resource, GenericMethodResource genericMethodResource, ApplicationContext context) { + public Object invokeMethod(Object resource, GenericResourceMethod genericMethodResource, ApplicationContext context) { WSConnection wsConnection = (WSConnection)org.everrest.core.impl.EnvironmentContext.getCurrent().get(WSConnection.class); if (wsConnection != null) { diff --git a/core/che-core-api-core/src/test/java/org/eclipse/che/api/core/rest/ServiceDescriptorTest.java b/core/che-core-api-core/src/test/java/org/eclipse/che/api/core/rest/ServiceDescriptorTest.java index 1dbc6e13c1d8..e3180aa91782 100644 --- a/core/che-core-api-core/src/test/java/org/eclipse/che/api/core/rest/ServiceDescriptorTest.java +++ b/core/che-core-api-core/src/test/java/org/eclipse/che/api/core/rest/ServiceDescriptorTest.java @@ -18,13 +18,15 @@ import org.eclipse.che.api.core.rest.shared.dto.Link; import org.eclipse.che.api.core.rest.shared.dto.LinkParameter; import org.eclipse.che.api.core.rest.shared.dto.ServiceDescriptor; +import org.everrest.core.ApplicationContext; import org.everrest.core.ResourceBinder; -import org.everrest.core.impl.ApplicationContextImpl; import org.everrest.core.impl.ApplicationProviderBinder; import org.everrest.core.impl.ContainerResponse; import org.everrest.core.impl.EverrestConfiguration; import org.everrest.core.impl.EverrestProcessor; import org.everrest.core.impl.ProviderBinder; +import org.everrest.core.impl.RequestDispatcher; +import org.everrest.core.impl.RequestHandlerImpl; import org.everrest.core.impl.ResourceBinderImpl; import org.everrest.core.tools.DependencySupplierImpl; import org.everrest.core.tools.ResourceLauncher; @@ -40,12 +42,13 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; - import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; +import static org.everrest.core.ApplicationContext.anApplicationContext; + /** @author Andrey Parfonov */ public class ServiceDescriptorTest { final String BASE_URI = "http://localhost/service"; @@ -91,11 +94,14 @@ public void setUp() throws Exception { DependencySupplierImpl dependencies = new DependencySupplierImpl(); ResourceBinder resources = new ResourceBinderImpl(); ProviderBinder providers = new ApplicationProviderBinder(); - EverrestProcessor processor = new EverrestProcessor(resources,providers,dependencies,new EverrestConfiguration(), null); + EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), + dependencies, + new RequestHandlerImpl(new RequestDispatcher(resources), providers), + null); launcher = new ResourceLauncher(processor); processor.addApplication(new Deployer()); - ApplicationContextImpl.setCurrent(new ApplicationContextImpl(null, null, ProviderBinder.getInstance())); - System.out.println("initilize"); + ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build()); + System.out.println("initialized"); } @Test diff --git a/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/DownloadFileResponseFilterTest.java b/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/DownloadFileResponseFilterTest.java index 14a61e66ff3d..a22f96e093ab 100644 --- a/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/DownloadFileResponseFilterTest.java +++ b/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/DownloadFileResponseFilterTest.java @@ -12,12 +12,14 @@ import org.eclipse.che.api.core.rest.ApiExceptionMapper; import org.eclipse.che.api.core.rest.DownloadFileResponseFilter; -import org.everrest.core.impl.ApplicationContextImpl; +import org.everrest.core.ApplicationContext; import org.everrest.core.impl.ApplicationProviderBinder; import org.everrest.core.impl.ContainerRequest; import org.everrest.core.impl.ContainerResponse; import org.everrest.core.impl.EverrestConfiguration; import org.everrest.core.impl.EverrestProcessor; +import org.everrest.core.impl.RequestDispatcher; +import org.everrest.core.impl.RequestHandlerImpl; import org.everrest.core.impl.ResourceBinderImpl; import org.everrest.core.tools.DependencySupplierImpl; import org.everrest.core.tools.ResourceLauncher; @@ -39,6 +41,7 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.OK; +import static org.everrest.core.ApplicationContext.anApplicationContext; import static org.testng.Assert.assertEquals; /** @@ -105,18 +108,16 @@ public void before() throws Exception { final ResourceBinderImpl resources = new ResourceBinderImpl(); resources.addResource(MyJaxRSService.class, null); final DependencySupplierImpl dependencies = new DependencySupplierImpl(); - final ApplicationProviderBinder binder = new ApplicationProviderBinder(); - binder.addExceptionMapper(ApiExceptionMapper.class); - binder.addResponseFilter(EverrestDownloadFileResponseFilter.class); + final ApplicationProviderBinder providers = new ApplicationProviderBinder(); + providers.addExceptionMapper(ApiExceptionMapper.class); + providers.addResponseFilter(EverrestDownloadFileResponseFilter.class); final URI uri = new URI(BASE_URI); final ContainerRequest req = new ContainerRequest(null, uri, uri, null, null, null); - final ApplicationContextImpl contextImpl = new ApplicationContextImpl(req, null, binder); - contextImpl.setDependencySupplier(dependencies); - ApplicationContextImpl.setCurrent(contextImpl); - final EverrestProcessor processor = new EverrestProcessor(resources, - binder, + final ApplicationContext context = anApplicationContext().withRequest(req).withProviders(providers).withDependencySupplier(dependencies).build(); + ApplicationContext.setCurrent(context); + final EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, - new EverrestConfiguration(), + new RequestHandlerImpl(new RequestDispatcher(resources), providers), null); resourceLauncher = new ResourceLauncher(processor); } diff --git a/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/ETagResponseFilterTest.java b/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/ETagResponseFilterTest.java index 46388d3bba2a..fe9e6e3c49ed 100644 --- a/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/ETagResponseFilterTest.java +++ b/core/che-core-api-core/src/test/java/org/eclipse/che/everrest/ETagResponseFilterTest.java @@ -11,12 +11,14 @@ package org.eclipse.che.everrest; import org.eclipse.che.api.core.rest.ApiExceptionMapper; -import org.everrest.core.impl.ApplicationContextImpl; +import org.everrest.core.ApplicationContext; import org.everrest.core.impl.ApplicationProviderBinder; import org.everrest.core.impl.ContainerRequest; import org.everrest.core.impl.ContainerResponse; import org.everrest.core.impl.EverrestConfiguration; import org.everrest.core.impl.EverrestProcessor; +import org.everrest.core.impl.RequestDispatcher; +import org.everrest.core.impl.RequestHandlerImpl; import org.everrest.core.impl.ResourceBinderImpl; import org.everrest.core.tools.DependencySupplierImpl; import org.everrest.core.tools.ResourceLauncher; @@ -31,7 +33,6 @@ import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; - import java.net.URI; import java.util.Arrays; import java.util.Collections; @@ -42,6 +43,7 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.Response.Status.NOT_MODIFIED; import static javax.ws.rs.core.Response.Status.OK; +import static org.everrest.core.ApplicationContext.anApplicationContext; import static org.testng.Assert.assertEquals; /** @@ -109,18 +111,17 @@ public void before() throws Exception { final ResourceBinderImpl resources = new ResourceBinderImpl(); resources.addResource(MyJaxRSService.class, null); final DependencySupplierImpl dependencies = new DependencySupplierImpl(); - final ApplicationProviderBinder binder = new ApplicationProviderBinder(); - binder.addExceptionMapper(ApiExceptionMapper.class); - binder.addResponseFilter(ETagResponseFilter.class); + final ApplicationProviderBinder providers = new ApplicationProviderBinder(); + providers.addExceptionMapper(ApiExceptionMapper.class); + providers.addResponseFilter(ETagResponseFilter.class); final URI uri = new URI(BASE_URI); final ContainerRequest req = new ContainerRequest(null, uri, uri, null, null, null); - final ApplicationContextImpl contextImpl = new ApplicationContextImpl(req, null, binder); + final ApplicationContext contextImpl = anApplicationContext().withRequest(req).withProviders(providers).build(); contextImpl.setDependencySupplier(dependencies); - ApplicationContextImpl.setCurrent(contextImpl); - final EverrestProcessor processor = new EverrestProcessor(resources, - binder, + ApplicationContext.setCurrent(contextImpl); + final EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, - new EverrestConfiguration(), + new RequestHandlerImpl(new RequestDispatcher(resources), providers), null); resourceLauncher = new ResourceLauncher(processor); } diff --git a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java index ab9013ca579a..5458ca024949 100644 --- a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java +++ b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/ProjectService.java @@ -348,7 +348,7 @@ public Response createFile(@ApiParam(value = "Path to a target directory", requi final URI location = getServiceContext().getServiceUriBuilder().clone() .path(getClass(), "getFile") - .build(newFile.getPath().toString().substring(1)); + .build(new String[]{newFile.getPath().toString().substring(1)}, false); return Response.created(location) .entity(injectFileLinks(asDto(newFile))) .build(); @@ -372,7 +372,7 @@ public Response createFolder(@ApiParam(value = "Path to a new folder destination final FolderEntry newFolder = projectManager.getProjectsRoot().createFolder(path); final URI location = getServiceContext().getServiceUriBuilder().clone() .path(getClass(), "getChildren") - .build(newFolder.getPath().toString().substring(1)); + .build(new String[]{newFolder.getPath().toString().substring(1)}, false); eventService.publish(new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, workspace, @@ -520,7 +520,7 @@ public Response copy(@ApiParam("Path to a resource") @PathParam("path") String p final URI location = getServiceContext().getServiceUriBuilder() .path(getClass(), copy.isFile() ? "getFile" : "getChildren") - .build(copy.getPath().toString().substring(1)); + .build(new String[]{copy.getPath().toString().substring(1)}, false); if (copy.isFolder()) { try { @@ -567,7 +567,7 @@ public Response move(@ApiParam("Path to a resource to be moved") @PathParam("pat final URI location = getServiceContext().getServiceUriBuilder() .path(getClass(), move.isFile() ? "getFile" : "getChildren") - .build(move.getPath().toString().substring(1)); + .build(new String[]{move.getPath().toString().substring(1)}, false); eventService.publish(new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.MOVED, workspace, @@ -678,7 +678,7 @@ public Response importZip(@ApiParam(value = "Path to a location (where import to return Response.created(getServiceContext().getServiceUriBuilder() .path(getClass(), "getChildren") - .build(parent.getPath().toString().substring(1))).build(); + .build(new String[]{parent.getPath().toString().substring(1)}, false)).build(); } @GET @@ -1032,14 +1032,14 @@ private ItemReference injectFileLinks(ItemReference itemReference) { links.add(createLink(GET, uriBuilder.clone() .path(ProjectService.class, "getFile") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, LINK_REL_GET_CONTENT)); links.add(createLink(PUT, uriBuilder.clone() .path(ProjectService.class, "updateFile") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), MediaType.WILDCARD, null, @@ -1047,7 +1047,7 @@ private ItemReference injectFileLinks(ItemReference itemReference) { links.add(createLink(DELETE, uriBuilder.clone() .path(ProjectService.class, "delete") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), LINK_REL_DELETE)); @@ -1062,21 +1062,21 @@ private ItemReference injectFolderLinks(ItemReference itemReference) { links.add(createLink(GET, uriBuilder.clone() .path(ProjectService.class, "getChildren") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, LINK_REL_CHILDREN)); links.add(createLink(GET, uriBuilder.clone() .path(ProjectService.class, "getTree") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, LINK_REL_TREE)); links.add(createLink(DELETE, uriBuilder.clone() .path(ProjectService.class, "delete") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), LINK_REL_DELETE)); @@ -1091,7 +1091,7 @@ private ProjectConfigDto injectProjectLinks(ProjectConfigDto projectConfig) { links.add(createLink(PUT, uriBuilder.clone() .path(ProjectService.class, "updateProject") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, APPLICATION_JSON, @@ -1099,21 +1099,21 @@ private ProjectConfigDto injectProjectLinks(ProjectConfigDto projectConfig) { links.add(createLink(GET, uriBuilder.clone() .path(ProjectService.class, "getChildren") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, LINK_REL_CHILDREN)); links.add(createLink(GET, uriBuilder.clone() .path(ProjectService.class, "getTree") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), APPLICATION_JSON, LINK_REL_TREE)); links.add(createLink(DELETE, uriBuilder.clone() .path(ProjectService.class, "delete") - .build(relPath) + .build(new String[]{relPath}, false) .toString(), LINK_REL_DELETE)); diff --git a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/WorkspaceHolder.java b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/WorkspaceHolder.java index 68f62b890c32..3800e49983e4 100644 --- a/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/WorkspaceHolder.java +++ b/wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/WorkspaceHolder.java @@ -108,7 +108,7 @@ protected void updateProject(ProjectConfig project) throws ServerException { final String href = UriBuilder.fromUri(apiEndpoint) .path(WorkspaceService.class) .path(WorkspaceService.class, "updateProject") - .build(workspaceId, project.getPath()).toString(); + .build(new String[] {workspaceId, project.getPath()}, false).toString(); try { httpJsonRequestFactory.fromUrl(href).usePutMethod().setBody(asDto(project)).request(); } catch (IOException | ApiException e) { @@ -123,7 +123,7 @@ protected void removeProject(ProjectConfig project) throws ServerException { final String href = UriBuilder.fromUri(apiEndpoint) .path(WorkspaceService.class) .path(WorkspaceService.class, "deleteProject") - .build(workspaceId, project.getPath()).toString(); + .build(new String[] {workspaceId, project.getPath()}, false).toString(); try { httpJsonRequestFactory.fromUrl(href).useDeleteMethod().request(); } catch (IOException | ApiException e) { diff --git a/wsagent/che-core-api-project/src/test/java/org/eclipse/che/api/project/server/ProjectServiceTest.java b/wsagent/che-core-api-project/src/test/java/org/eclipse/che/api/project/server/ProjectServiceTest.java index d2bb1e393f85..e9ffee8ce085 100644 --- a/wsagent/che-core-api-project/src/test/java/org/eclipse/che/api/project/server/ProjectServiceTest.java +++ b/wsagent/che-core-api-project/src/test/java/org/eclipse/che/api/project/server/ProjectServiceTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.che.api.project.server; -import org.eclipse.che.WorkspaceIdProvider; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.NotFoundException; @@ -42,13 +41,10 @@ import org.eclipse.che.api.project.shared.dto.TreeElement; import org.eclipse.che.api.user.server.spi.UserDao; import org.eclipse.che.api.vfs.VirtualFile; -import org.eclipse.che.api.vfs.VirtualFileSystem; import org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler; import org.eclipse.che.api.vfs.impl.file.FileTreeWatcher; import org.eclipse.che.api.vfs.impl.file.FileWatcherNotificationHandler; import org.eclipse.che.api.vfs.impl.file.LocalVirtualFileSystemProvider; -import org.eclipse.che.api.vfs.search.Searcher; -import org.eclipse.che.api.vfs.search.SearcherProvider; import org.eclipse.che.api.vfs.search.impl.FSLuceneSearcherProvider; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; @@ -57,16 +53,17 @@ import org.eclipse.che.commons.json.JsonHelper; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.commons.lang.ws.rs.ExtMediaType; -import org.eclipse.che.commons.test.SelfReturningAnswer; import org.eclipse.che.commons.subject.SubjectImpl; +import org.eclipse.che.commons.test.SelfReturningAnswer; import org.eclipse.che.dto.server.DtoFactory; +import org.everrest.core.ApplicationContext; import org.everrest.core.ResourceBinder; -import org.everrest.core.impl.ApplicationContextImpl; -import org.everrest.core.impl.ApplicationProviderBinder; import org.everrest.core.impl.ContainerResponse; import org.everrest.core.impl.EverrestConfiguration; import org.everrest.core.impl.EverrestProcessor; import org.everrest.core.impl.ProviderBinder; +import org.everrest.core.impl.RequestDispatcher; +import org.everrest.core.impl.RequestHandlerImpl; import org.everrest.core.impl.ResourceBinderImpl; import org.everrest.core.tools.ByteArrayContainerResponseWriter; import org.everrest.core.tools.DependencySupplierImpl; @@ -114,6 +111,7 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; import static org.eclipse.che.commons.lang.ws.rs.ExtMediaType.APPLICATION_ZIP; +import static org.everrest.core.ApplicationContext.anApplicationContext; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -249,16 +247,19 @@ public void setUp() throws Exception { DependencySupplierImpl dependencies = new DependencySupplierImpl(); - dependencies.addComponent(ProjectTypeRegistry.class, ptRegistry); - dependencies.addComponent(UserDao.class, userDao); - dependencies.addComponent(ProjectManager.class, pm); - dependencies.addComponent(ProjectImporterRegistry.class, importerRegistry); - dependencies.addComponent(ProjectHandlerRegistry.class, phRegistry); - dependencies.addComponent(EventService.class, eventService); + dependencies.addInstance(ProjectTypeRegistry.class, ptRegistry); + dependencies.addInstance(UserDao.class, userDao); + dependencies.addInstance(ProjectManager.class, pm); + dependencies.addInstance(ProjectImporterRegistry.class, importerRegistry); + dependencies.addInstance(ProjectHandlerRegistry.class, phRegistry); + dependencies.addInstance(EventService.class, eventService); ResourceBinder resources = new ResourceBinderImpl(); - ProviderBinder providers = new ApplicationProviderBinder(); - EverrestProcessor processor = new EverrestProcessor(resources, providers, dependencies, new EverrestConfiguration(), null); + ProviderBinder providers = ProviderBinder.getInstance(); + EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), + dependencies, + new RequestHandlerImpl(new RequestDispatcher(resources), providers), + null); launcher = new ResourceLauncher(processor); processor.addApplication(new Application() { @@ -273,7 +274,7 @@ public Set getSingletons() { } }); - ApplicationContextImpl.setCurrent(new ApplicationContextImpl(null, null, ProviderBinder.getInstance())); + ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build()); env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent(); } From 5feed9afdc96b4e364f128a9fc59080a7bd8b0d2 Mon Sep 17 00:00:00 2001 From: Mihail Kuznyetsov Date: Thu, 7 Jul 2016 12:37:27 +0300 Subject: [PATCH 15/24] CODENVY-651 Save machine config with 'dev' instead of 'isDev' field --- .../server/model/impl/MachineConfigImpl.java | 24 +++++++++---------- .../workspace/server/stack/StackLoader.java | 3 +-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/model/impl/MachineConfigImpl.java b/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/model/impl/MachineConfigImpl.java index eb31c55ebafb..31446fe7b367 100644 --- a/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/model/impl/MachineConfigImpl.java +++ b/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/model/impl/MachineConfigImpl.java @@ -33,7 +33,7 @@ public static MachineConfigImplBuilder builder() { return new MachineConfigImplBuilder(); } - private boolean isDev; + private boolean dev; private String name; private String type; private MachineSourceImpl source; @@ -44,14 +44,14 @@ public static MachineConfigImplBuilder builder() { public MachineConfigImpl() { } - public MachineConfigImpl(boolean isDev, + public MachineConfigImpl(boolean dev, String name, String type, MachineSource source, Limits limits, List servers, Map envVariables) { - this.isDev = isDev; + this.dev = dev; this.name = name; this.type = type; this.envVariables = envVariables; @@ -97,7 +97,7 @@ public void setSource(MachineSource machineSource) { @Override public boolean isDev() { - return isDev; + return dev; } @Override @@ -135,7 +135,7 @@ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof MachineConfigImpl)) return false; final MachineConfigImpl other = (MachineConfigImpl)obj; - return isDev == other.isDev && + return dev == other.dev && Objects.equals(name, other.name) && Objects.equals(source, other.source) && Objects.equals(limits, other.limits) && @@ -147,7 +147,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hash = 7; - hash = hash * 31 + Boolean.hashCode(isDev); + hash = hash * 31 + Boolean.hashCode(dev); hash = hash * 31 + Objects.hashCode(name); hash = hash * 31 + Objects.hashCode(type); hash = hash * 31 + Objects.hashCode(source); @@ -160,7 +160,7 @@ public int hashCode() { @Override public String toString() { return "MachineConfigImpl{" + - "isDev=" + isDev + + "dev=" + dev + ", name='" + name + '\'' + ", type='" + type + '\'' + ", source=" + source + @@ -177,7 +177,7 @@ public String toString() { */ public static class MachineConfigImplBuilder { - private boolean isDev; + private boolean dev; private String name; private String type; private MachineSource source; @@ -186,7 +186,7 @@ public static class MachineConfigImplBuilder { private Map envVariables; public MachineConfigImpl build() { - return new MachineConfigImpl(isDev, + return new MachineConfigImpl(dev, name, type, source, @@ -196,7 +196,7 @@ public MachineConfigImpl build() { } public MachineConfigImplBuilder fromConfig(MachineConfig machineConfig) { - isDev = machineConfig.isDev(); + dev = machineConfig.isDev(); name = machineConfig.getName(); type = machineConfig.getType(); source = machineConfig.getSource(); @@ -206,8 +206,8 @@ public MachineConfigImplBuilder fromConfig(MachineConfig machineConfig) { return this; } - public MachineConfigImplBuilder setDev(boolean isDev) { - this.isDev = isDev; + public MachineConfigImplBuilder setDev(boolean dev) { + this.dev = dev; return this; } diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/stack/StackLoader.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/stack/StackLoader.java index d130ca44ebe4..3bdb55ea40ea 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/stack/StackLoader.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/stack/StackLoader.java @@ -61,8 +61,7 @@ public StackLoader(@Named("che.stacks.default") String stacksPath, this.stackIconFolderPath = Paths.get(stackIconFolder); this.stackDao = stackDao; - //TODO remove this strategy after fix https://jira.codenvycorp.com/browse/CODENVY-651 - GSON = new GsonBuilder().setFieldNamingStrategy(field -> field.getName().equals("isDev") ? "dev" : field.getName()).create(); + GSON = new GsonBuilder().create(); } /** From 99afebd475d75ecc4581aa180ea675f2cadf0e41 Mon Sep 17 00:00:00 2001 From: Vladyslav Zhukovskii Date: Mon, 25 Jul 2016 13:10:30 +0300 Subject: [PATCH 16/24] Provide correct content url link for the image Signed-off-by: Vladyslav Zhukovskii --- .../java/org/eclipse/che/ide/imageviewer/ImageViewer.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/imageviewer/ImageViewer.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/imageviewer/ImageViewer.java index 8acd954f370d..57b91f5670c1 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/imageviewer/ImageViewer.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/imageviewer/ImageViewer.java @@ -31,6 +31,7 @@ import org.eclipse.che.ide.api.editor.EditorInput; import org.eclipse.che.ide.api.event.FileEvent; import org.eclipse.che.ide.api.event.FileEventHandler; +import org.eclipse.che.ide.api.machine.WsAgentURLModifier; import org.eclipse.che.ide.api.parts.WorkspaceAgent; import org.vectomatic.dom.svg.ui.SVGResource; @@ -47,6 +48,7 @@ public class ImageViewer extends AbstractEditorPresenter implements FileEventHan private CoreLocalizationConstant constant; private DialogFactory dialogFactory; private WorkspaceAgent workspaceAgent; + private WsAgentURLModifier urlModifier; private ScrollPanel editorView; @Inject @@ -54,11 +56,13 @@ public ImageViewer(ImageViewerResources resources, CoreLocalizationConstant constant, DialogFactory dialogFactory, EventBus eventBus, - WorkspaceAgent workspaceAgent) { + WorkspaceAgent workspaceAgent, + WsAgentURLModifier urlModifier) { this.resources = resources; this.constant = constant; this.dialogFactory = dialogFactory; this.workspaceAgent = workspaceAgent; + this.urlModifier = urlModifier; resources.imageViewerCss().ensureInjected(); @@ -150,7 +154,7 @@ public void go(AcceptsOneWidget container) { * @return {@link Image} */ private Image getImage() { - String contentLink = input.getFile().getContentUrl(); + String contentLink = urlModifier.modify(input.getFile().getContentUrl()); Image image = (contentLink != null) ? new Image(contentLink) : new Image(); image.setStyleName(resources.imageViewerCss().imageViewer()); return image; From 7707cce0b3d2fa834e393152f12e6ed5df340274 Mon Sep 17 00:00:00 2001 From: Florent BENOIT Date: Mon, 25 Jul 2016 14:50:00 +0200 Subject: [PATCH 17/24] Fix #1909 Update IDE resource path after changes for namespace handling Change-Id: I9f935e60be0f461eb2d99fc885a6f23d2b6618be Signed-off-by: Florent BENOIT --- dashboard/src/assets/branding/product.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/src/assets/branding/product.json b/dashboard/src/assets/branding/product.json index 8ae67106aea0..d6e9535b369e 100644 --- a/dashboard/src/assets/branding/product.json +++ b/dashboard/src/assets/branding/product.json @@ -4,7 +4,7 @@ "logoFile": "che-logo.svg", "logoTextFile": "che-logo-text.svg", "favicon": "favicon.ico", - "ideResources": "/ide/_app/", + "ideResources": "/_app/", "helpPath": "https://www.eclipse.org/che/", "helpTitle": "Community", "supportEmail": "wish@codenvy.com", From d6d6da02586bf6c19818ec3dbf8711bb42865337 Mon Sep 17 00:00:00 2001 From: Vladyslav Zhukovskii Date: Mon, 25 Jul 2016 16:42:26 +0300 Subject: [PATCH 18/24] #1899: Add ability to copy and paste text in terminal view --- .../eclipse/che/ide/resources/action/CopyResourceAction.java | 4 +++- .../eclipse/che/ide/resources/action/CutResourceAction.java | 4 +++- .../eclipse/che/ide/resources/action/PasteResourceAction.java | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CopyResourceAction.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CopyResourceAction.java index 9dea4600075e..32d16fc641ec 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CopyResourceAction.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CopyResourceAction.java @@ -24,6 +24,7 @@ import org.eclipse.che.ide.api.event.ActivePartChangedHandler; import org.eclipse.che.ide.api.parts.PartPresenter; import org.eclipse.che.ide.api.resources.modification.ClipboardManager; +import org.eclipse.che.ide.api.selection.Selection; import javax.validation.constraints.NotNull; @@ -74,7 +75,8 @@ public void onActivePartChanged(ActivePartChangedEvent event) { public void updateInPerspective(@NotNull ActionEvent event) { event.getPresentation().setVisible(true); event.getPresentation().setEnabled(clipboardManager.getCopyProvider().isCopyEnable(appContext) - && !(partPresenter instanceof TextEditor)); + && !(partPresenter instanceof TextEditor) + && !(partPresenter.getSelection() instanceof Selection.NoSelectionProvided)); } /** {@inheritDoc} */ diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CutResourceAction.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CutResourceAction.java index cea1291aaef9..2291b1af3008 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CutResourceAction.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/CutResourceAction.java @@ -24,6 +24,7 @@ import org.eclipse.che.ide.api.event.ActivePartChangedHandler; import org.eclipse.che.ide.api.parts.PartPresenter; import org.eclipse.che.ide.api.resources.modification.ClipboardManager; +import org.eclipse.che.ide.api.selection.Selection; import javax.validation.constraints.NotNull; @@ -74,7 +75,8 @@ public void onActivePartChanged(ActivePartChangedEvent event) { public void updateInPerspective(@NotNull ActionEvent event) { event.getPresentation().setVisible(true); event.getPresentation().setEnabled(clipboardManager.getCutProvider().isCutEnable(appContext) - && !(partPresenter instanceof TextEditor)); + && !(partPresenter instanceof TextEditor) + && !(partPresenter.getSelection() instanceof Selection.NoSelectionProvided)); } /** {@inheritDoc} */ diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/PasteResourceAction.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/PasteResourceAction.java index 994ebd417eb8..e32125d0ad60 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/PasteResourceAction.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/action/PasteResourceAction.java @@ -24,6 +24,7 @@ import org.eclipse.che.ide.api.event.ActivePartChangedHandler; import org.eclipse.che.ide.api.parts.PartPresenter; import org.eclipse.che.ide.api.resources.modification.ClipboardManager; +import org.eclipse.che.ide.api.selection.Selection; import javax.validation.constraints.NotNull; @@ -74,7 +75,8 @@ public void onActivePartChanged(ActivePartChangedEvent event) { public void updateInPerspective(@NotNull ActionEvent event) { event.getPresentation().setVisible(true); event.getPresentation().setEnabled(clipboardManager.getPasteProvider().isPastePossible(appContext) - && !(partPresenter instanceof TextEditor)); + && !(partPresenter instanceof TextEditor) + && !(partPresenter.getSelection() instanceof Selection.NoSelectionProvided)); } /** {@inheritDoc} */ From 2ea64b8978f83b621d45311f3e9029feb04335ee Mon Sep 17 00:00:00 2001 From: Igor Vinokur Date: Mon, 25 Jul 2016 17:18:19 +0300 Subject: [PATCH 19/24] CHE-1849: Modify start workspace by ID API method When user starts workspace that has snapshot the 'recover from snapshots?' dialog will be shown. If user will select not to recover and auto-restore will be enabled workspace will be recovered from snapshot anywhere. --- .../api/workspace/WorkspaceServiceClient.java | 20 ++-- .../workspace/WorkspaceServiceClientImpl.java | 24 ++--- .../che/ide/workspace/WorkspaceComponent.java | 47 +++++----- .../workspace/server/WorkspaceManager.java | 54 ++++------- .../workspace/server/WorkspaceService.java | 57 +++--------- .../server/WorkspaceManagerTest.java | 92 +++++++++++++------ .../server/WorkspaceServiceTest.java | 54 +++++++---- 7 files changed, 165 insertions(+), 183 deletions(-) diff --git a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClient.java b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClient.java index 032ca4b54af9..75c7960e77c6 100644 --- a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClient.java +++ b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClient.java @@ -26,6 +26,7 @@ * GWT Client for Workspace Service. * * @author Yevhenii Voevodin + * @author Igor Vinokur */ public interface WorkspaceServiceClient { @@ -116,10 +117,14 @@ public interface WorkspaceServiceClient { * workspace ID * @param envName * the name of the workspace environment that should be used for start + * @param restore + * if true workspace will be restored from snapshot if snapshot exists, + * if false workspace will not be restored from snapshot + * even if auto-restore is enabled and snapshot exists * @return a promise that resolves to the {@link WorkspaceDto}, or rejects with an error * @see WorkspaceService#startById(String, String, Boolean, String) */ - Promise startById(String id, String envName); + Promise startById(String id, String envName, boolean restore); /** * Stops running workspace. @@ -276,17 +281,4 @@ public interface WorkspaceServiceClient { */ Promise createSnapshot(String workspaceId); - /** - * Recovers workspace from snapshot. - * - * @param workspaceId - * workspace ID - * @param envName - * the name of the workspace environment to recover from - * @param accountId - * the account id related to this operation - * @return a promise that resolves to the {@link WorkspaceDto}, or rejects with an error - * @see WorkspaceService#recoverWorkspace(String, String, String) - */ - Promise recoverWorkspace(String workspaceId, String envName, String accountId); } diff --git a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClientImpl.java b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClientImpl.java index dd5490ea9641..8f78f883715f 100644 --- a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClientImpl.java +++ b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/WorkspaceServiceClientImpl.java @@ -51,6 +51,7 @@ * @author Dmitry Shnurenko * @author Alexander Garagatyi * @author Yevhenii Voevodin + * @author Igor Vinokur */ public class WorkspaceServiceClientImpl implements WorkspaceServiceClient { @@ -189,21 +190,22 @@ private void startWorkspace(@NotNull WorkspaceConfigDto cfg, } @Override - public Promise startById(@NotNull final String id, final String envName) { + public Promise startById(@NotNull final String id, final String envName, final boolean restore) { return newPromise(new RequestCall() { @Override public void makeCall(AsyncCallback callback) { - startById(id, envName, callback); + startById(id, envName, restore, callback); } }); } private void startById(@NotNull String workspaceId, @Nullable String envName, + boolean restore, @NotNull AsyncCallback callback) { - String url = baseHttpUrl + "/" + workspaceId + "/runtime"; + String url = baseHttpUrl + "/" + workspaceId + "/runtime?restore=" + restore; if (envName != null) { - url += "?environment=" + envName; + url += "&environment=" + envName; } asyncRequestFactory.createPostRequest(url, null) .header(ACCEPT, APPLICATION_JSON) @@ -381,18 +383,4 @@ public void makeCall(AsyncCallback callback) { } }); } - - @Override - public Promise recoverWorkspace(final String workspaceId, final String envName, final String accountId) { - return newPromise(new RequestCall() { - @Override - public void makeCall(AsyncCallback callback) { - final String url = baseHttpUrl + '/' + workspaceId + "/runtime/snapshot?environment=" + envName; - asyncRequestFactory.createPostRequest(url, null) - .header(ACCEPT, APPLICATION_JSON) - .loader(loaderFactory.newLoader("Recovering workspace from snapshot")) - .send(newCallback(callback, dtoUnmarshallerFactory.newUnmarshaller(WorkspaceDto.class))); - } - }); - } } diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/workspace/WorkspaceComponent.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/workspace/WorkspaceComponent.java index a9bb32e0eb71..69e977311e00 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/workspace/WorkspaceComponent.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/workspace/WorkspaceComponent.java @@ -257,8 +257,7 @@ private void checkWorkspaceForSnapshots(final WorkspaceDto workspace) { @Override public void apply(List snapshots) throws OperationException { if (snapshots.isEmpty()) { - handleWsStart(workspaceServiceClient.startById(workspace.getId(), - workspace.getConfig().getDefaultEnv())); + handleWsStart(workspaceServiceClient.startById(workspace.getId(), workspace.getConfig().getDefaultEnv(), false)); } else { showRecoverWorkspaceConfirmDialog(workspace); } @@ -275,32 +274,30 @@ private native void notifyShowIDE() /*-{ /** * Shows workspace recovering confirm dialog. - * - *

When "Ok" button is pressed - {@link WorkspaceServiceClient#recoverWorkspace(String, String, String) recovers workspace} - *
When "Cancel" button is pressed - {@link WorkspaceServiceClient#startById(String, String) starts workspace} */ private void showRecoverWorkspaceConfirmDialog(final WorkspaceDto workspace) { dialogFactory.createConfirmDialog("Workspace recovering", - "Do you want to recover the workspace from snapshot?", - "Yes", - "No", - new ConfirmCallback() { - @Override - public void accepted() { - handleWsStart(workspaceServiceClient.recoverWorkspace(workspace.getId(), - workspace.getConfig() - .getDefaultEnv(), - null)); - } - }, - new CancelCallback() { - @Override - public void cancelled() { - handleWsStart(workspaceServiceClient.startById(workspace.getId(), - workspace.getConfig() - .getDefaultEnv())); - } - }) + "Do you want to recover the workspace from snapshot?", + "Yes", + "No", + new ConfirmCallback() { + @Override + public void accepted() { + handleWsStart(workspaceServiceClient.startById(workspace.getId(), + workspace.getConfig() + .getDefaultEnv(), + true)); + } + }, + new CancelCallback() { + @Override + public void cancelled() { + handleWsStart(workspaceServiceClient.startById(workspace.getId(), + workspace.getConfig() + .getDefaultEnv(), + false)); + } + }) .show(); notifyShowIDE(); diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceManager.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceManager.java index 9bf1ae44cd47..2050b41dcf93 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceManager.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceManager.java @@ -72,6 +72,7 @@ * @author gazarenkov * @author Alexander Garagatyi * @author Yevhenii Voevodin + * @author Igor Vinokur */ @Singleton public class WorkspaceManager { @@ -352,6 +353,18 @@ public void removeWorkspace(String workspaceId) throws ConflictException, Server * @param accountId * account which should be used for this runtime workspace or null when * it should be automatically detected + * @param restore + * if true workspace will be restored from snapshot if snapshot exists, + * otherwise (if snapshot does not exist) workspace will be started from default source. + * If false workspace will be started from default source, + * even if auto-restore is enabled and snapshot exists. + * If null workspace will be restored from snapshot + * only if workspace has `auto-restore` attribute set to true, + * or system wide parameter `auto-restore` is enabled and snapshot exists. + *

+ * This parameter has the highest priority to define if it is needed to restore from snapshot or not. + * If it is not defined workspace `auto-restore` attribute will be checked, then if last is not defined + * system wide `auto-restore` parameter will be checked. * @return starting workspace * @throws NullPointerException * when {@code workspaceId} is null @@ -363,15 +376,16 @@ public void removeWorkspace(String workspaceId) throws ConflictException, Server */ public WorkspaceImpl startWorkspace(String workspaceId, @Nullable String envName, - @Nullable String accountId) throws NotFoundException, - ServerException, - ConflictException { + @Nullable String accountId, + @Nullable Boolean restore) throws NotFoundException, + ServerException, + ConflictException { requireNonNull(workspaceId, "Required non-null workspace id"); final WorkspaceImpl workspace = workspaceDao.get(workspaceId); final String restoreAttr = workspace.getAttributes().get(AUTO_RESTORE_FROM_SNAPSHOT); final boolean autoRestore = restoreAttr == null ? defaultAutoRestore : parseBoolean(restoreAttr); final boolean snapshotExists = !getSnapshot(workspaceId).isEmpty(); - return performAsyncStart(workspace, envName, snapshotExists && autoRestore, accountId); + return performAsyncStart(workspace, envName, firstNonNull(restore, autoRestore) && snapshotExists, accountId); } /** @@ -410,38 +424,6 @@ public WorkspaceImpl startWorkspace(WorkspaceConfig config, return normalizeState(workspace); } - /** - * Asynchronously recovers the workspace from the snapshot. - * - * @param workspaceId - * workspace id - * @param envName - * environment name or null if default one should be used - * @param accountId - * account which should be used for this runtime workspace or null when - * it should be automatically detected - * @return starting workspace instance - * @throws NullPointerException - * when {@code workspaceId} is null - * @throws NotFoundException - * when workspace with such id doesn't exist - * @throws ServerException - * when any server error occurs - * @throws ConflictException - * when workspace with such id is not stopped - * @throws ForbiddenException - * when user doesn't have access to start the new workspace - */ - public WorkspaceImpl recoverWorkspace(String workspaceId, - @Nullable String envName, - @Nullable String accountId) throws NotFoundException, - ServerException, - ConflictException, - ForbiddenException { - requireNonNull(workspaceId, "Required non-null workspace id"); - return performAsyncStart(workspaceDao.get(workspaceId), envName, true, accountId); - } - /** * Asynchronously stops the workspace. * diff --git a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java index cdcace6b0720..477f792255ce 100644 --- a/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java +++ b/wsmaster/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/server/WorkspaceService.java @@ -73,6 +73,7 @@ * Defines Workspace REST API. * * @author Yevhenii Voevodin + * @author Igor Vinokur */ @Api(value = "/workspace", description = "Workspace REST API") @Path("/workspace") @@ -140,7 +141,7 @@ public Response create(@ApiParam(value = "The configuration to create the new wo attributes, accountId); if (startAfterCreate) { - workspaceManager.startWorkspace(workspace.getId(), null, accountId); + workspaceManager.startWorkspace(workspace.getId(), null, accountId, false); } return Response.status(201) .entity(linksInjector.injectLinks(asDto(workspace), getServiceContext())) @@ -264,16 +265,17 @@ public WorkspaceDto startById(@ApiParam("The workspace id") String envName, @ApiParam("The account id related to this operation") @QueryParam("accountId") - String accountId) throws ServerException, - BadRequestException, - NotFoundException, - ForbiddenException, - ConflictException { - final Map params = Maps.newHashMapWithExpectedSize(2); - params.put("accountId", accountId); - params.put("workspaceId", workspaceId); - - return linksInjector.injectLinks(asDto(workspaceManager.startWorkspace(workspaceId, envName, accountId)), getServiceContext()); + String accountId, + @ApiParam("Restore workspace from snapshot") + @QueryParam("restore") + Boolean restore) throws ServerException, + BadRequestException, + NotFoundException, + ForbiddenException, + ConflictException { + + return linksInjector.injectLinks(asDto(workspaceManager.startWorkspace(workspaceId, envName, accountId, restore)), + getServiceContext()); } @POST @@ -311,39 +313,6 @@ public WorkspaceDto startFromConfig(@ApiParam(value = "The configuration to star accountId)), getServiceContext()); } - @POST - @Path("/{id}/runtime/snapshot") - @Produces(APPLICATION_JSON) - @ApiOperation(value = "Recover the workspace by the id from the snapshot", - notes = "This operation can be performed only by the workspace owner." + - "The workspace recovers asynchronously") - @ApiResponses({@ApiResponse(code = 200, message = "The workspace is starting"), - @ApiResponse(code = 404, message = "The workspace with specified id doesn't exist." + - "The snapshot from this workspace doesn't exist"), - @ApiResponse(code = 403, message = "The user is not workspace owner. " + - "The operation is not allowed for the user"), - @ApiResponse(code = 409, message = "Any conflict occurs during the workspace start"), - @ApiResponse(code = 500, message = "Internal server error occurred")}) - public WorkspaceDto recoverWorkspace(@ApiParam("The workspace id") - @PathParam("id") - String workspaceId, - @ApiParam("The name of the workspace environment to recover from") - @QueryParam("environment") - String envName, - @ApiParam("The account id related to this operation") - @QueryParam("accountId") - String accountId) throws BadRequestException, - ForbiddenException, - NotFoundException, - ServerException, - ConflictException { - final Map params = Maps.newHashMapWithExpectedSize(2); - params.put("accountId", accountId); - params.put("workspaceId", workspaceId); - - return linksInjector.injectLinks(asDto(workspaceManager.recoverWorkspace(workspaceId, envName, accountId)), getServiceContext()); - } - @DELETE @Path("/{id}/runtime") @ApiOperation(value = "Stop the workspace", diff --git a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceManagerTest.java b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceManagerTest.java index 3b58e0939dd1..726fc9bae957 100644 --- a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceManagerTest.java +++ b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceManagerTest.java @@ -335,7 +335,8 @@ public void shouldBeAbleToStartWorkspaceById() throws Exception { workspaceManager.startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), - "account"); + "account", + null); verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), false); verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); @@ -343,7 +344,7 @@ public void shouldBeAbleToStartWorkspaceById() throws Exception { } @Test - public void shouldRecoverWorkspaceIfAutoRestoreAttributeIsSetAndSnapshotExists() throws Exception { + public void shouldRecoverWorkspaceWhenRecoverParameterIsNullAndAutoRestoreAttributeIsSetAndSnapshotExists() throws Exception { final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); workspace.getAttributes().put(AUTO_RESTORE_FROM_SNAPSHOT, "true"); when(machineManager.getSnapshots(any(), any())).thenReturn(singletonList(mock(SnapshotImpl.class))); @@ -352,7 +353,8 @@ public void shouldRecoverWorkspaceIfAutoRestoreAttributeIsSetAndSnapshotExists() workspaceManager.startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), - "account"); + "account", + null); verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), true); verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); @@ -360,15 +362,67 @@ public void shouldRecoverWorkspaceIfAutoRestoreAttributeIsSetAndSnapshotExists() } @Test - public void shouldNotRecoverWorkspaceWhenAutoRestoreAttributesIsSetButSnapshotDoesNotExist() throws Exception { + public void shouldRecoverWorkspaceWhenRecoverParameterIsTrueAndSnapshotExists() throws Exception { + final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); + when(machineManager.getSnapshots(any(), any())).thenReturn(singletonList(mock(SnapshotImpl.class))); + when(workspaceDao.get(workspace.getId())).thenReturn(workspace); + when(runtimes.get(any())).thenThrow(new NotFoundException("")); + + workspaceManager.startWorkspace(workspace.getId(), + workspace.getConfig().getDefaultEnv(), + "account", + true); + + verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), true); + verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); + assertNotNull(workspace.getAttributes().get(UPDATED_ATTRIBUTE_NAME)); + } + + @Test + public void shouldNotRecoverWorkspaceWhenRecoverParameterIsNullAndAutoRestoreAttributesIsSetButSnapshotDoesNotExist() throws Exception { + final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); + workspace.getAttributes().put(AUTO_RESTORE_FROM_SNAPSHOT, "true"); + when(workspaceDao.get(workspace.getId())).thenReturn(workspace); + when(runtimes.get(any())).thenThrow(new NotFoundException("")); + + workspaceManager.startWorkspace(workspace.getId(), + workspace.getConfig().getDefaultEnv(), + "account", + null); + + verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), false); + verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); + assertNotNull(workspace.getAttributes().get(UPDATED_ATTRIBUTE_NAME)); + } + + @Test + public void shouldNotRecoverWorkspaceWhenRecoverParameterIsTrueButSnapshotDoesNotExist() throws Exception { + final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); + when(workspaceDao.get(workspace.getId())).thenReturn(workspace); + when(runtimes.get(any())).thenThrow(new NotFoundException("")); + + workspaceManager.startWorkspace(workspace.getId(), + workspace.getConfig().getDefaultEnv(), + "account", + true); + + verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), false); + verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); + assertNotNull(workspace.getAttributes().get(UPDATED_ATTRIBUTE_NAME)); + } + + @Test + public void shouldNotRecoverWorkspaceWhenRecoverParameterIsFalseAndAutoRestoreAttributeIsSetAndSnapshotExists() throws Exception { final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); workspace.getAttributes().put(AUTO_RESTORE_FROM_SNAPSHOT, "true"); + when(machineManager.getSnapshots(any(), any())).thenReturn(singletonList(mock(SnapshotImpl.class))); when(workspaceDao.get(workspace.getId())).thenReturn(workspace); when(runtimes.get(any())).thenThrow(new NotFoundException("")); workspaceManager.startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), - "account"); + "account", + false); verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), false); verify(workspaceHooks, timeout(2000)).beforeStart(workspace, workspace.getConfig().getDefaultEnv(), "account"); @@ -383,7 +437,7 @@ public void shouldNotBeAbleToStartWorkspaceIfItIsRunning() throws Exception { final RuntimeDescriptor descriptor = createDescriptor(workspace, STARTING); when(runtimes.get(workspace.getId())).thenReturn(descriptor); - workspaceManager.startWorkspace(workspace.getId(), null, null); + workspaceManager.startWorkspace(workspace.getId(), null, null, null); } @Test @@ -394,7 +448,7 @@ public void workspaceStartShouldUseDefaultEnvIfNullEnvNameProvided() throws Exce final RuntimeDescriptor descriptor = createDescriptor(workspace, STARTING); when(runtimes.start(any(), anyString(), anyBoolean())).thenReturn(descriptor); - workspaceManager.startWorkspace(workspace.getId(), null, "account"); + workspaceManager.startWorkspace(workspace.getId(), null, "account", null); // timeout is needed because this invocation will run in separate thread asynchronously verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), false); @@ -413,7 +467,7 @@ public void performAsyncStartShouldUseProvidedEnvInsteadOfDefault() throws Excep final RuntimeDescriptor descriptor = createDescriptor(workspace, STARTING); when(runtimes.start(any(), anyString(), anyBoolean())).thenReturn(descriptor); - workspaceManager.startWorkspace(workspace.getId(), nonDefaultEnv.getName(), "account"); + workspaceManager.startWorkspace(workspace.getId(), nonDefaultEnv.getName(), "account", null); // timeout is needed because this invocation will run in separate thread asynchronously verify(runtimes, timeout(2000)).start(workspace, nonDefaultEnv.getName(), false); @@ -428,7 +482,7 @@ public void startShouldThrowNotFoundExceptionWhenProvidedEnvDoesNotExist() throw final RuntimeDescriptor descriptor = createDescriptor(workspace, STARTING); when(runtimes.start(any(), anyString(), anyBoolean())).thenReturn(descriptor); - workspaceManager.startWorkspace(workspace.getId(), "fake", "account"); + workspaceManager.startWorkspace(workspace.getId(), "fake", "account", null); } @Test @@ -453,22 +507,6 @@ public void shouldBeAbleToStartTemporaryWorkspace() throws Exception { verify(workspaceManager).performAsyncStart(captured, captured.getConfig().getDefaultEnv(), false, "account"); } - @Test - public void shouldBeAbleToRecoverWorkspace() throws Exception { - final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); - when(workspaceDao.get(workspace.getId())).thenReturn(workspace); - doReturn(workspace).when(workspaceManager).performAsyncStart(any(), anyString(), anyBoolean(), anyString()); - when(runtimes.get(any())).thenThrow(new NotFoundException("")); - - final WorkspaceImpl result = workspaceManager.recoverWorkspace(workspace.getId(), - workspace.getConfig().getDefaultEnv(), - "account"); - - assertFalse(result.isTemporary()); - assertEquals(workspace.getConfig(), result.getConfig()); - verify(workspaceManager).performAsyncStart(workspace, workspace.getConfig().getDefaultEnv(), true, "account"); - } - @Test public void shouldBeAbleToStopWorkspace() throws Exception { final WorkspaceImpl workspace = workspaceManager.createWorkspace(createConfig(), "user123", "account"); @@ -545,7 +583,7 @@ public void shouldRemoveTemporaryWorkspaceAfterStartFailed() throws Exception { when(runtimes.get(any())).thenThrow(new NotFoundException("")); when(runtimes.start(any(), anyString(), anyBoolean())).thenThrow(new ConflictException("")); - workspaceManager.startWorkspace(workspace.getId(), null, null); + workspaceManager.startWorkspace(workspace.getId(), null, null, null); verify(workspaceDao, timeout(2000)).remove(workspace.getId()); } @@ -594,7 +632,7 @@ public void shouldStartWorkspaceFromSnapshotUsingDefaultValueForAutoRestore() th when(workspaceDao.get(workspace.getId())).thenReturn(workspace); when(runtimes.get(any())).thenThrow(new NotFoundException("")); - workspaceManager.startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), "account"); + workspaceManager.startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), "account", null); verify(runtimes, timeout(2000)).start(workspace, workspace.getConfig().getDefaultEnv(), true); } diff --git a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java index adaf0724b7e7..09c7f2501333 100644 --- a/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java +++ b/wsmaster/che-core-api-workspace/src/test/java/org/eclipse/che/api/workspace/server/WorkspaceServiceTest.java @@ -177,7 +177,7 @@ public void shouldStartTheWorkspaceAfterItIsCreatedWhenStartAfterCreateParamIsTr "&attribute=custom:custom:value" + "&start-after-create=true"); - verify(wsManager).startWorkspace(workspace.getId(), null, null); + verify(wsManager).startWorkspace(workspace.getId(), null, null, false); verify(wsManager).createWorkspace(anyObject(), anyString(), eq(ImmutableMap.of("stackId", "stack123", @@ -302,7 +302,7 @@ public void shouldDeleteWorkspace() throws Exception { @Test public void shouldStartWorkspace() throws Exception { final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - when(wsManager.startWorkspace(any(), any(), any())).thenReturn(workspace); + when(wsManager.startWorkspace(any(), any(), any(), any())).thenReturn(workspace); when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); final Response response = given().auth() @@ -313,46 +313,62 @@ public void shouldStartWorkspace() throws Exception { assertEquals(response.getStatusCode(), 200); assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class)), workspace); - verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null); - verify(wsManager, never()).recoverWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null); + verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null, null); } @Test - public void shouldStartWorkspaceFromConfig() throws Exception { + public void shouldRestoreWorkspace() throws Exception { final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - when(wsManager.startWorkspace(anyObject(), - anyString(), - anyBoolean(), - anyString())).thenReturn(workspace); + when(wsManager.startWorkspace(any(), any(), any(), any())).thenReturn(workspace); when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); - final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); final Response response = given().auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) - .contentType("application/json") - .body(workspaceDto.getConfig()) .when() - .post(SECURE_PATH + "/workspace/runtime"); + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime" + + "?environment=" + workspace.getConfig().getDefaultEnv() + "&restore=true"); assertEquals(response.getStatusCode(), 200); - verify(validator).validateConfig(any()); + assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class)), workspace); + verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null, true); } @Test - public void shouldRecoverWorkspace() throws Exception { + public void shouldNotRestoreWorkspace() throws Exception { final WorkspaceImpl workspace = createWorkspace(createConfigDto()); - when(wsManager.recoverWorkspace(any(), any(), any())).thenReturn(workspace); + when(wsManager.startWorkspace(any(), any(), any(), any())).thenReturn(workspace); when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); final Response response = given().auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .when() - .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime/snapshot" + - "?environment=" + workspace.getConfig().getDefaultEnv()); + .post(SECURE_PATH + "/workspace/" + workspace.getId() + "/runtime" + + "?environment=" + workspace.getConfig().getDefaultEnv() + "&restore=false"); assertEquals(response.getStatusCode(), 200); assertEquals(new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class)), workspace); - verify(wsManager).recoverWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null); + verify(wsManager).startWorkspace(workspace.getId(), workspace.getConfig().getDefaultEnv(), null, false); + } + + @Test + public void shouldStartWorkspaceFromConfig() throws Exception { + final WorkspaceImpl workspace = createWorkspace(createConfigDto()); + when(wsManager.startWorkspace(anyObject(), + anyString(), + anyBoolean(), + anyString())).thenReturn(workspace); + when(wsManager.getWorkspace(workspace.getId())).thenReturn(workspace); + final WorkspaceDto workspaceDto = DtoConverter.asDto(workspace); + + final Response response = given().auth() + .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) + .contentType("application/json") + .body(workspaceDto.getConfig()) + .when() + .post(SECURE_PATH + "/workspace/runtime"); + + assertEquals(response.getStatusCode(), 200); + verify(validator).validateConfig(any()); } @Test From 19083335ae14cb580ee3ac4b5c9fd60167439220 Mon Sep 17 00:00:00 2001 From: Max Shaposhnik Date: Tue, 26 Jul 2016 14:34:01 +0300 Subject: [PATCH 20/24] CHE-1935; add custom User-Agent header value for JGit; (#1936) --- .../java/org/eclipse/che/git/impl/jgit/JGitConnection.java | 1 - .../org/eclipse/che/git/impl/jgit/JGitConnectionFactory.java | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java index 2ef753170d68..2ea662ec83af 100644 --- a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java +++ b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java @@ -1605,7 +1605,6 @@ public void configure(Transport transport) { } ProxyAuthenticator.initAuthenticator(remoteUrl); - return command.call(); } catch (GitException | TransportException exception) { if ("Unable get private ssh key".equals(exception.getMessage())) { diff --git a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnectionFactory.java b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnectionFactory.java index 8b496f132949..3d0262d231af 100644 --- a/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnectionFactory.java +++ b/wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnectionFactory.java @@ -20,6 +20,7 @@ import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.transport.UserAgent; import javax.inject.Inject; import javax.net.ssl.HttpsURLConnection; @@ -38,6 +39,8 @@ */ public class JGitConnectionFactory extends GitConnectionFactory { + private static final String USER_AGENT = "git/2.1.0"; + private final CredentialsLoader credentialsLoader; private final SshKeyProvider sshKeyProvider; private final GitUserResolver userResolver; @@ -48,6 +51,7 @@ public JGitConnectionFactory(CredentialsLoader credentialsLoader, SshKeyProvider this.sshKeyProvider = sshKeyProvider; this.userResolver = userResolver; + UserAgent.set(USER_AGENT); // Install the all-trusting trust manager try { SSLContext sslContext = SSLContext.getInstance("SSL"); From a9d7ecfc1e95203fa52456843875c174f6f75e20 Mon Sep 17 00:00:00 2001 From: Vitaliy Guliy Date: Tue, 26 Jul 2016 15:13:12 +0300 Subject: [PATCH 21/24] CHE-1361 Artik: Resources monitor (CPU, memory and storage) Signed-off-by: Vitaliy Guliy --- .../org/eclipse/che/ide/api/theme/Theme.java | 8 + .../org/eclipse/che/ide/theme/DarkTheme.java | 12 ++ .../org/eclipse/che/ide/theme/LightTheme.java | 12 ++ .../java/org/eclipse/che/ide/ui/Tooltip.java | 17 ++ .../org/eclipse/che/ide/ui/Tooltip.css | 12 +- .../client/machine/MachineStateEvent.java | 2 +- .../processes/ConsolesPanelPresenter.java | 21 +- .../processes/ConsolesPanelViewImpl.java | 2 +- .../client/processes/ProcessTreeRenderer.java | 16 +- .../processes/monitoring/MachineMonitors.java | 110 ++++++++++ .../processes/monitoring/MonitorWidget.java | 120 +++++++++++ .../processes/monitoring/MonitorWidget.ui.xml | 202 ++++++++++++++++++ .../processes/ConsolesPanelPresenterTest.java | 5 +- 13 files changed, 510 insertions(+), 29 deletions(-) create mode 100644 plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MachineMonitors.java create mode 100644 plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.java create mode 100644 plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.ui.xml diff --git a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/theme/Theme.java b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/theme/Theme.java index 8b706b0a5d3b..e57d98b36eaf 100644 --- a/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/theme/Theme.java +++ b/ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/theme/Theme.java @@ -1511,4 +1511,12 @@ public interface Theme { String vcsConsoleChangesLineNumbersColor(); String editorPreferenceCategoryBackgroundColor(); + + /******************************************************************************************** + * + * Resource monitors + * + ********************************************************************************************/ + String resourceMonitorBarBackground(); + } diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/DarkTheme.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/DarkTheme.java index 12ff22fb3ee9..5cd5c3fa4bb7 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/DarkTheme.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/DarkTheme.java @@ -1499,4 +1499,16 @@ public String vcsConsoleChangesLineNumbersColor() { public String editorPreferenceCategoryBackgroundColor() { return "rgba(215, 215, 215, 0.10)"; } + + /******************************************************************************************** + * + * Resource monitors + * + ********************************************************************************************/ + + @Override + public String resourceMonitorBarBackground() { + return "rgb(76, 76, 76)"; + } + } diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/LightTheme.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/LightTheme.java index 0dc59ecc9579..c50d04e71914 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/LightTheme.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/theme/LightTheme.java @@ -1476,4 +1476,16 @@ public String vcsConsoleChangesLineNumbersColor() { public String editorPreferenceCategoryBackgroundColor() { return "rgba(27, 27, 27, 0.10)"; } + + /******************************************************************************************** + * + * Resource monitors + * + ********************************************************************************************/ + + @Override + public String resourceMonitorBarBackground() { + return "#e0e0e0"; + } + } diff --git a/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/Tooltip.java b/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/Tooltip.java index 5cb04e3a7c15..53c4b604912f 100644 --- a/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/Tooltip.java +++ b/ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/Tooltip.java @@ -125,6 +125,23 @@ public static Tooltip create(Element targetElement, PositionController.VerticalA new SimpleStringRenderer(tooltipText)).build(); } + /** Static factory method for creating a simple tooltip with given element as content. */ + public static Tooltip create(Element targetElement, PositionController.VerticalAlign vAlign, + PositionController.HorizontalAlign hAlign, final Element tooltipContent) { + return new Builder(targetElement, new TooltipPositionerBuilder().setVerticalAlign(vAlign) + .setHorizontalAlign(hAlign) + .buildAnchorPositioner(targetElement)).setTooltipRenderer( + + new TooltipRenderer() { + @Override + public Element renderDom() { + return tooltipContent; + } + } + + ).build(); + } + /** The Tooltip is a flyweight that uses a singleton View base element. */ private static AutoHideView getViewInstance(Css css) { if (tooltipViewInstance == null) { diff --git a/ide/commons-gwt/src/main/resources/org/eclipse/che/ide/ui/Tooltip.css b/ide/commons-gwt/src/main/resources/org/eclipse/che/ide/ui/Tooltip.css index c0a70ef71632..785c7fa29674 100644 --- a/ide/commons-gwt/src/main/resources/org/eclipse/che/ide/ui/Tooltip.css +++ b/ide/commons-gwt/src/main/resources/org/eclipse/che/ide/ui/Tooltip.css @@ -25,13 +25,13 @@ display: inline-block; position: relative; margin: 0; - max-width: 200px; + max-width: 250px; } - /* - * Imageless triangles can be made using only css by adding a large border on one side, - * then transparent borders on the two adjacent sides. - */ +/* + * Imageless triangles can be made using only css by adding a large border on one side, + * then transparent borders on the two adjacent sides. + */ .triangle { position: absolute; width: 0px; @@ -52,7 +52,7 @@ margin-left: -4px; } - /* A tooltip that is below but right aligned */ +/* A tooltip that is below but right aligned */ .tooltipBelowRightAligned { margin-top: 7px; } diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/machine/MachineStateEvent.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/machine/MachineStateEvent.java index 5bf81fa201ef..bfeaac2ce597 100755 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/machine/MachineStateEvent.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/machine/MachineStateEvent.java @@ -51,7 +51,7 @@ public interface Handler extends EventHandler { /** * Type class used to register this event. */ - public static Type TYPE = new Type<>(); + public static final Type TYPE = new Type<>(); private final org.eclipse.che.api.core.model.machine.Machine machine; diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java index f62860a345cc..dbb6e083611f 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java @@ -26,7 +26,6 @@ import org.eclipse.che.ide.api.dialogs.ConfirmCallback; import org.eclipse.che.ide.api.dialogs.DialogFactory; import org.eclipse.che.ide.api.machine.MachineServiceClient; -import org.eclipse.che.ide.api.machine.events.DevMachineStateEvent; import org.eclipse.che.ide.api.mvp.View; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.outputconsole.OutputConsole; @@ -81,8 +80,7 @@ public class ConsolesPanelPresenter implements ConsolesPanelView.ActionDelegate, OutputConsole.ConsoleOutputListener, WorkspaceStartingEvent.Handler, WorkspaceStoppedEvent.Handler, - MachineStateEvent.Handler, - DevMachineStateEvent.Handler { + MachineStateEvent.Handler { private static final String DEFAULT_TERMINAL_NAME = "Terminal"; @@ -153,13 +151,12 @@ public ConsolesPanelPresenter(ConsolesPanelView view, this.consoleCommands = new HashMap<>(); this.machineNodes = new HashMap<>(); - this.view.setDelegate(this); + view.setDelegate(this); eventBus.addHandler(ProcessFinishedEvent.TYPE, this); eventBus.addHandler(WorkspaceStartingEvent.TYPE, this); eventBus.addHandler(WorkspaceStoppedEvent.TYPE, this); eventBus.addHandler(MachineStateEvent.TYPE, this); - eventBus.addHandler(DevMachineStateEvent.TYPE, this); rootNode = new ProcessTreeNode(ROOT_NODE, null, null, null, rootNodes); @@ -215,14 +212,6 @@ public void onMachineDestroyed(MachineStateEvent event) { view.setProcessesData(rootNode); } - @Override - public void onDevMachineStarted(DevMachineStateEvent event) { - } - - @Override - public void onDevMachineDestroyed(DevMachineStateEvent event) { - } - /** Get the list of all available machines. */ public void fetchMachines() { machineService.getMachines(appContext.getWorkspaceId()).then(new Operation>() { @@ -262,9 +251,11 @@ public void printDevMachineOutput(String text) { } private ProcessTreeNode addMachineNode(MachineDto machine) { - List processTreeNodes = new ArrayList(); + if (machineNodes.containsKey(machine.getId())) { + return machineNodes.get(machine.getId()); + } - ProcessTreeNode machineNode = new ProcessTreeNode(MACHINE_NODE, rootNode, machine, null, processTreeNodes); + ProcessTreeNode machineNode = new ProcessTreeNode(MACHINE_NODE, rootNode, machine, null, new ArrayList()); machineNode.setRunning(true); machineNodes.put(machine.getId(), machineNode); diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelViewImpl.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelViewImpl.java index db6052a30356..fa358c325bb5 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelViewImpl.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelViewImpl.java @@ -275,7 +275,7 @@ public void setProcessesData(@NotNull ProcessTreeNode root) { processTree.asWidget().setVisible(true); processTree.getModel().setRoot(root); - processTree.renderTree(-1); + processTree.renderTree(); for (ProcessTreeNode processTreeNode : processTreeNodes.values()) { if (!processTreeNode.getId().equals(activeProcessId) && processTreeNode.hasUnreadContent()) { diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ProcessTreeRenderer.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ProcessTreeRenderer.java index 01ffa09c1f9a..580768a9d49b 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ProcessTreeRenderer.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ProcessTreeRenderer.java @@ -24,6 +24,7 @@ import org.eclipse.che.ide.api.parts.PartStackUIResources; import org.eclipse.che.ide.extension.machine.client.MachineLocalizationConstant; import org.eclipse.che.ide.extension.machine.client.MachineResources; +import org.eclipse.che.ide.extension.machine.client.processes.monitoring.MachineMonitors; import org.eclipse.che.ide.ui.Tooltip; import org.eclipse.che.ide.ui.tree.NodeRenderer; import org.eclipse.che.ide.ui.tree.TreeNodeElement; @@ -59,13 +60,17 @@ public class ProcessTreeRenderer implements NodeRenderer { private AddTerminalClickHandler addTerminalClickHandler; private PreviewSshClickHandler previewSshClickHandler; private StopProcessHandler stopProcessHandler; + private final MachineMonitors machineMonitors; @Inject - public ProcessTreeRenderer(MachineResources resources, MachineLocalizationConstant locale, - PartStackUIResources partStackUIResources) { + public ProcessTreeRenderer(MachineResources resources, + MachineLocalizationConstant locale, + PartStackUIResources partStackUIResources, + MachineMonitors machineMonitors) { this.resources = resources; this.locale = locale; this.partStackUIResources = partStackUIResources; + this.machineMonitors = machineMonitors; } @Override @@ -190,6 +195,13 @@ public void handleEvent(Event event) { newTerminalButton.addEventListener(Event.CLICK, blockMouseListener, true); newTerminalButton.addEventListener(Event.DBLCLICK, blockMouseListener, true); + Element monitorsElement = Elements.createSpanElement(); + monitorsElement.getStyle().setProperty("float", "right"); + monitorsElement.getStyle().setProperty("cursor", "default"); + root.appendChild(monitorsElement); + + Node monitorNode = (Node)machineMonitors.getMonitorWidget(machine.getId(), this).getElement(); + monitorsElement.appendChild(monitorNode); Element nameElement = Elements.createSpanElement(resources.getCss().nameLabel()); nameElement.setTextContent(machine.getConfig().getName()); diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MachineMonitors.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MachineMonitors.java new file mode 100644 index 000000000000..e8ab3acea777 --- /dev/null +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MachineMonitors.java @@ -0,0 +1,110 @@ +/******************************************************************************* + * Copyright (c) 2012-2016 Codenvy, S.A. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Codenvy, S.A. - initial API and implementation + *******************************************************************************/ +package org.eclipse.che.ide.extension.machine.client.processes.monitoring; + +import com.google.inject.Singleton; + +import java.util.HashMap; +import java.util.Map; + +/** + * Manages and provides widgets for displaying CPU, memory and disk usages for the machines. + * + * @author Vitaliy Guliy + */ +@Singleton +public class MachineMonitors { + + private Map> monitorWidgets = new HashMap<>(); + + /** + * Creates new or returns existed widget for the given machine and referrer. + * Referrer is an UI object containing monitor widgets attached as children. + * + * @param machineID + * machines ID + * @param referrer + * referrer object + * @return + * monitor widget + */ + public MonitorWidget getMonitorWidget(String machineID, Object referrer) { + Map widgets = monitorWidgets.get(machineID); + if (widgets == null) { + widgets = new HashMap<>(); + monitorWidgets.put(machineID, widgets); + } + + MonitorWidget widget = widgets.get(referrer); + if (widget == null) { + widget = new MonitorWidget(); + widgets.put(referrer, widget); + } + + return widget; + } + + /** + * Sets new CPU usage value for machine with given ID. + * + * @param machineID + * machine ID + * @param cpuUsage + * new cpu usage + */ + public void setCpuUsage(String machineID, int cpuUsage) { + Map widgets = monitorWidgets.get(machineID); + if (widgets != null) { + for (MonitorWidget widget : widgets.values()) { + widget.setCpuUsage(cpuUsage); + } + } + } + + /** + * Sets new memory usage value for machine with given ID. + * + * @param machineID + * machine ID + * @param mem + * new memory usage + * @param max + * maximum amount of memory + */ + public void setMemoryUsage(String machineID, int mem, int max) { + Map widgets = monitorWidgets.get(machineID); + if (widgets != null) { + for (MonitorWidget widget : widgets.values()) { + widget.setMemoryUsage(mem, max); + } + } + } + + /** + * Sets new disk usage value for machine with given ID. + * + * @param machineID + * machine ID + * @param disk + * new disk usage + * @param max + * maximum amount of disk space + */ + public void setDiskUsage(String machineID, int disk, int max) { + Map widgets = monitorWidgets.get(machineID); + if (widgets != null) { + for (MonitorWidget widget : widgets.values()) { + widget.setDiskUsage(disk, max); + } + } + } + +} diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.java new file mode 100644 index 000000000000..a3c7bb0449ae --- /dev/null +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (c) 2012-2016 Codenvy, S.A. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Codenvy, S.A. - initial API and implementation + *******************************************************************************/ +package org.eclipse.che.ide.extension.machine.client.processes.monitoring; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.DivElement; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.FlowPanel; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.Widget; +import elemental.dom.Element; +import org.eclipse.che.ide.ui.Tooltip; +import org.eclipse.che.ide.ui.menu.PositionController; + +/** + * Resource monitor widget. Displays information about cpu, memory and disk usage in consoles tree. + * The widget also creates a tooltip with additional information. + * + * @author Vitaliy Guliy + */ +public class MonitorWidget extends Composite { + + interface MonitorWidgetUiBinder extends UiBinder { + } + + private final static MonitorWidgetUiBinder UI_BINDER = GWT.create(MonitorWidgetUiBinder.class); + + @UiField + FlowPanel cpuBar, memBar, diskBar; + + @UiField + HTMLPanel tooltip; + + @UiField + DivElement tooltipCpuBar, tooltipCpuValue; + + @UiField + DivElement tooltipMemBar, tooltipMemValue, tooltipMemDescription; + + @UiField + DivElement tooltipDiskBar, tooltipDiskValue, tooltipDiskDescription; + + public MonitorWidget() { + initWidget(UI_BINDER.createAndBindUi(this)); + + tooltip.removeFromParent(); + + Tooltip.create((Element)getElement(), PositionController.VerticalAlign.BOTTOM, PositionController.HorizontalAlign.RIGHT, (Element)tooltip.getElement()); + } + + /** + * Sets CPU usage value. + * + * @param cpuUsage + * cpuUsage usage + */ + public void setCpuUsage(int cpuUsage) { + setVisible(true); + + cpuBar.getElement().getFirstChildElement().getStyle().setProperty("height", cpuUsage + "%"); + + tooltipCpuBar.getStyle().setProperty("height", cpuUsage + "%"); + tooltipCpuValue.setInnerText(cpuUsage + "%"); + } + + /** + * Sets memory usage value. + * + * @param mem + * memory usage + * @param max + * max memory available + */ + public void setMemoryUsage(int mem, int max) { + setVisible(true); + + int percentage = (int)((double)mem / ((double)max / 100) ); + + memBar.getElement().getFirstChildElement().getStyle().setProperty("height", percentage + "%"); + + tooltipMemBar.getStyle().setProperty("height", percentage + "%"); + tooltipMemValue.setInnerText(percentage + "%"); + tooltipMemDescription.setInnerText("- " + mem + " MB / " + max + " MB"); + } + + /** + * Sets disk usage value. + * + * @param disk + * disk usage + * @param max + * max disk available + */ + public void setDiskUsage(int disk, int max) { + setVisible(true); + + int percentage = (int)((double)disk / ((double)max / 100) ); + + diskBar.getElement().getFirstChildElement().getStyle().setProperty("height", percentage + "%"); + + tooltipDiskBar.getStyle().setProperty("height", percentage + "%"); + tooltipDiskValue.setInnerText(percentage + "%"); + + disk = disk / 1024; + max = max / 1024; + + tooltipDiskDescription.setInnerText("- " + disk + " MB / " + max + " MB"); + } + +} diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.ui.xml b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.ui.xml new file mode 100644 index 000000000000..47bb30b2e84d --- /dev/null +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/monitoring/MonitorWidget.ui.xml @@ -0,0 +1,202 @@ + + + + + + + + + @eval outputBackgroundColor org.eclipse.che.ide.api.theme.Style.theme.outputBackgroundColor(); + + @eval resourceMonitorBarBackground org.eclipse.che.ide.api.theme.Style.theme.resourceMonitorBarBackground(); + + .monitor { + width: 22px; + height: 18px; + position: relative; + overflow: hidden; + } + + .cpu, + .mem, + .disk { + position: absolute; + overflow: hidden; + width: 3px; + height: 12px; + background-color: resourceMonitorBarBackground; + top: 3px; + } + + .cpu { + left: 4px; + } + + .mem { + left: 9px; + } + + .disk { + left: 14px; + } + + .cpu > div, + .mem > div, + .disk > div { + position: absolute; + left: 0px; + right: 0px; + bottom: 0px; + } + + .cpu > div { + background-color: #46af00; + } + + .mem > div { + background-color: #f2b043; + } + + .disk > div { + background-color: #d0021b; + } + + .tooltip { + width: 210px; + height: 75px; + background-color: outputBackgroundColor; + font-size: 11px; + } + + .rowCPU, + .rowMEM, + .rowDISK { + position: absolute; + left: 0px; + width: 100%; + height: 25px; + overflow: hidden; + } + + .rowCPU { + top: 2px; + } + .rowMEM { + top: 30px; + } + .rowDISK { + top: 58px; + } + + .labelCell { + position: absolute; + left: 10px; + top: 0px; + width: 35px; + height: 25px; + line-height: 25px; + } + + .indicatorCell { + position: absolute; + left: 45px; + top: 2px; + width: 7px; + height: 21px; + background-color: resourceMonitorBarBackground; + overflow: hidden; + } + + .valueCell { + position: absolute; + left: 60px; + top: 0px; + width: 35px; + height: 25px; + line-height: 25px; + } + + .descriptionCell { + position: absolute; + left: 97px; + top: 0px; + width: 130px; + height: 25px; + line-height: 25px; + overflow: hidden; + white-space: nowrap; + } + + .indicatorCPU { + position: absolute; + left: 0px; + bottom: 0px; + width: 100%; + height: 52%; + background-color: #46af00; + } + + .indicatorMEM { + position: absolute; + left: 0px; + bottom: 0px; + width: 100%; + height: 82%; + background-color: #f2b043; + } + + .indicatorDISK { + position: absolute; + left: 0px; + bottom: 0px; + width: 100%; + height: 92%; + background-color: #d0021b; + } + + + + + + + + + + + +

+
CPU
+
+
52%
+
+
+ +
+
MEM
+
+
82%
+
- 350000MB / 400000MB
+
+ +
+
DISK
+
+
92%
+
- 1.7 G / 15 G
+
+ + + + diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java index b1b9cf779265..6346b4fbc066 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java @@ -225,10 +225,7 @@ public void shouldFetchMachines() throws Exception { when(appContext.getWorkspaceId()).thenReturn("workspaceID"); DevMachineStateEvent devMachineStateEvent = mock(DevMachineStateEvent.class); - verify(eventBus, times(5)).addHandler(anyObject(), devMachineStateHandlerCaptor.capture()); - - DevMachineStateEvent.Handler devMachineStateHandler = devMachineStateHandlerCaptor.getAllValues().get(0); - devMachineStateHandler.onDevMachineStarted(devMachineStateEvent); + verify(eventBus, times(4)).addHandler(anyObject(), devMachineStateHandlerCaptor.capture()); verify(machineService).getMachines(eq(WORKSPACE_ID)); verify(machinesPromise).then(machinesCaptor.capture()); From 1bb6551c02f4a47a8da8279a679a5e31e22c8132 Mon Sep 17 00:00:00 2001 From: Valeriy Svydenko Date: Tue, 26 Jul 2016 17:08:35 +0300 Subject: [PATCH 22/24] CHE-1843: change value of 'java.output.folder' attribute Signed-off-by: Valeriy Svydenko --- .../valueproviders/OutputDirProvider.java | 20 ++- .../valueproviders/OutputDirProviderTest.java | 143 ++++++++++++++++++ .../client/wizard/PlainJavaPagePresenter.java | 7 +- .../wizard/PlainJavaPagePresenterTest.java | 35 +++++ .../PlainJavaValueProviderFactory.java | 7 +- .../PlainJavaValueProviderFactoryTest.java | 4 +- 6 files changed, 205 insertions(+), 11 deletions(-) create mode 100644 plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProviderTest.java diff --git a/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProvider.java b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProvider.java index 54b82fc3b07a..c8cbd4e83036 100644 --- a/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProvider.java +++ b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProvider.java @@ -19,9 +19,9 @@ import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.resources.Project; import org.eclipse.che.ide.api.resources.Resource; -import org.eclipse.che.ide.ext.java.client.util.JavaUtil; import org.eclipse.che.ide.extension.machine.client.command.valueproviders.CommandPropertyValueProvider; +import static org.eclipse.che.ide.ext.java.client.util.JavaUtil.isJavaProject; import static org.eclipse.che.ide.ext.java.shared.Constants.OUTPUT_FOLDER; /** @@ -56,10 +56,22 @@ public Promise getValue() { final Resource resource = resources[0]; final Optional project = resource.getRelatedProject(); - if (JavaUtil.isJavaProject(project.get()) && project.get().getAttributes().containsKey(OUTPUT_FOLDER)) { - return promises.resolve(appContext.getProjectsRoot().append(project.get().getAttributes().get(OUTPUT_FOLDER).get(0)).toString()); + if (!project.isPresent()) { + return promises.resolve(""); + } + + Project relatedProject = project.get(); + + if (!isJavaProject(relatedProject)) { + return promises.resolve(""); + } + + if (relatedProject.getAttributes().containsKey(OUTPUT_FOLDER)) { + return promises.resolve(appContext.getProjectsRoot() + .append(relatedProject.getLocation()) + .append(relatedProject.getAttributes().get(OUTPUT_FOLDER).get(0)).toString()); } else { - return promises.resolve(appContext.getProjectsRoot().append(project.get().getLocation()).toString()); + return promises.resolve(appContext.getProjectsRoot().append(relatedProject.getLocation()).toString()); } } diff --git a/plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProviderTest.java b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProviderTest.java new file mode 100644 index 000000000000..e1991670751f --- /dev/null +++ b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/test/java/org/eclipse/che/ide/ext/java/client/command/valueproviders/OutputDirProviderTest.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * Copyright (c) 2012-2016 Codenvy, S.A. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Codenvy, S.A. - initial API and implementation + *******************************************************************************/ +package org.eclipse.che.ide.ext.java.client.command.valueproviders; + +import com.google.common.base.Optional; +import com.google.gwtmockito.GwtMockitoTestRunner; + +import org.eclipse.che.api.promises.client.Promise; +import org.eclipse.che.api.promises.client.PromiseProvider; +import org.eclipse.che.ide.api.app.AppContext; +import org.eclipse.che.ide.api.resources.Project; +import org.eclipse.che.ide.api.resources.Resource; +import org.eclipse.che.ide.resource.Path; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static java.util.Collections.singletonList; +import static org.eclipse.che.ide.ext.java.shared.Constants.LANGUAGE; +import static org.eclipse.che.ide.ext.java.shared.Constants.OUTPUT_FOLDER; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * @author Valeriy Svydenko + */ +@RunWith(GwtMockitoTestRunner.class) +public class OutputDirProviderTest { + @InjectMocks + private OutputDirProvider provider; + + @Mock + private AppContext appContext; + @Mock + private PromiseProvider promises; + + @Mock + private Resource resource1; + @Mock + private Resource resource2; + @Mock + private Optional projectOptional; + @Mock + private Project relatedProject; + + @Captor + private ArgumentCaptor> valuePromiseCaptor; + + private Resource[] resources; + private Map> attributes = new HashMap<>(); + + @Before + public void setUp() throws Exception { + resources = new Resource[]{resource1}; + attributes.put(LANGUAGE, singletonList("java")); + + when(appContext.getResources()).thenReturn(resources); + when(resource1.getRelatedProject()).thenReturn(projectOptional); + when(projectOptional.isPresent()).thenReturn(true); + when(projectOptional.get()).thenReturn(relatedProject); + when(appContext.getProjectsRoot()).thenReturn(new Path("/projects")); + when(relatedProject.getLocation()).thenReturn(new Path("projectParent/project")); + when(relatedProject.getAttributes()).thenReturn(attributes); + } + + @Test + public void keyShouldBeReturned() throws Exception { + assertEquals("${project.java.output.dir}", provider.getKey()); + } + + @Test + public void valueShouldBeEmptyIfSelectedResourcesIsNull() throws Exception { + resources = null; + when(appContext.getResources()).thenReturn(resources); + + provider.getValue(); + + verify(promises).resolve(eq("")); + } + + @Test + public void valueShouldBeEmptyIfSelectedManyResources() throws Exception { + resources = new Resource[]{resource1, resource2}; + when(appContext.getResources()).thenReturn(resources); + + provider.getValue(); + + verify(promises).resolve(eq("")); + } + + @Test + public void valueShouldBeEmptyIfRelatedProjectOfSelectedResourceIsNull() throws Exception { + when(projectOptional.isPresent()).thenReturn(false); + + provider.getValue(); + + verify(promises).resolve(eq("")); + } + + @Test + public void valueShouldBeEmptyIfRelatedProjectIsNotJavaProject() throws Exception { + attributes.put(LANGUAGE, singletonList("cpp")); + when(relatedProject.getAttributes()).thenReturn(attributes); + + provider.getValue(); + + verify(promises).resolve(eq("")); + } + + @Test + public void outputFolderShouldBeRootOfProjectIfAttributeDoesNotExist() throws Exception { + provider.getValue(); + + verify(promises).resolve(eq("/projects/projectParent/project")); + } + + @Test + public void outputFolderShouldBeSetAsValueOfAttribute() throws Exception { + attributes.put(OUTPUT_FOLDER, singletonList("bin")); + + provider.getValue(); + + verify(promises).resolve(eq("/projects/projectParent/project/bin")); + } +} diff --git a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/java/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenter.java b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/java/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenter.java index 5b42d54eafb8..e3b856652799 100644 --- a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/java/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenter.java +++ b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/java/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenter.java @@ -18,6 +18,7 @@ import org.eclipse.che.ide.api.project.MutableProjectConfig; import org.eclipse.che.ide.api.project.type.wizard.ProjectWizardMode; import org.eclipse.che.ide.api.wizard.AbstractWizardPage; +import org.eclipse.che.ide.resource.Path; import org.eclipse.che.ide.resources.tree.ResourceNode; import org.eclipse.che.plugin.java.plain.client.wizard.selector.SelectNodePresenter; import org.eclipse.che.plugin.java.plain.client.wizard.selector.SelectionDelegate; @@ -31,6 +32,7 @@ import static org.eclipse.che.ide.api.project.type.wizard.ProjectWizardMode.CREATE; import static org.eclipse.che.ide.api.project.type.wizard.ProjectWizardRegistrar.WIZARD_MODE_KEY; import static org.eclipse.che.ide.ext.java.shared.Constants.SOURCE_FOLDER; +import static org.eclipse.che.ide.resource.Path.valueOf; import static org.eclipse.che.plugin.java.plain.shared.PlainJavaProjectConstants.DEFAULT_SOURCE_FOLDER_VALUE; import static org.eclipse.che.plugin.java.plain.shared.PlainJavaProjectConstants.LIBRARY_FOLDER; @@ -111,12 +113,13 @@ public void onBrowseLibraryButtonClicked() { @Override public void onNodeSelected(List nodes) { - int projectNameLength = dataObject.getName().length(); + String projectName = dataObject.getName(); List nodeRelativePath = new LinkedList<>(); for (Node node : nodes) { - nodeRelativePath.add(((ResourceNode)node).getData().getLocation().toString().substring(projectNameLength + 1)); + Path nodeLocation = ((ResourceNode)node).getData().getLocation(); + nodeRelativePath.add(nodeLocation.makeRelativeTo(valueOf(projectName)).toString()); } if (isSourceSelected) { diff --git a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/test/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenterTest.java b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/test/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenterTest.java index 6cc5475e3707..317c90d77e4a 100644 --- a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/test/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenterTest.java +++ b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-ide/src/main/test/org/eclipse/che/plugin/java/plain/client/wizard/PlainJavaPagePresenterTest.java @@ -13,9 +13,13 @@ import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwtmockito.GwtMockitoTestRunner; +import org.eclipse.che.ide.api.data.tree.Node; import org.eclipse.che.ide.api.project.MutableProjectConfig; import org.eclipse.che.ide.api.project.type.wizard.ProjectWizardRegistrar; +import org.eclipse.che.ide.api.resources.Resource; import org.eclipse.che.ide.api.wizard.Wizard; +import org.eclipse.che.ide.resource.Path; +import org.eclipse.che.ide.resources.tree.ResourceNode; import org.eclipse.che.plugin.java.plain.client.wizard.selector.SelectNodePresenter; import org.junit.Before; import org.junit.Test; @@ -23,6 +27,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,6 +40,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -156,4 +163,32 @@ public void showSelectWindowWhenBrowseButtonWasClicked() throws Exception { verify(selectNodePresenter).show(page, "name"); } + + @Test + public void selectedNodeShouldBeWithRelativePath() throws Exception { + when(view.getLibraryFolder()).thenReturn("lib1, lib2"); + when(view.getSourceFolder()).thenReturn("src1, src2"); + List selectedNodes = new ArrayList<>(); + ResourceNode selectedNode1 = mock(ResourceNode.class); + ResourceNode selectedNode2 = mock(ResourceNode.class); + Resource resource1 = mock(Resource.class); + Resource resource2 = mock(Resource.class); + + selectedNodes.add(selectedNode1); + selectedNodes.add(selectedNode2); + + when(selectedNode1.getData()).thenReturn(resource1); + when(resource1.getLocation()).thenReturn(Path.valueOf("projectName/folder1/folder2")); + + when(selectedNode2.getData()).thenReturn(resource2); + when(resource2.getLocation()).thenReturn(Path.valueOf("projectName/folder")); + + when(dataObject.getName()).thenReturn("projectName"); + + page.setUpdateDelegate(updateDelegate); + page.init(dataObject); + page.onNodeSelected(selectedNodes); + + verify(view).setLibraryFolder(eq("folder1/folder2, folder")); + } } diff --git a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/main/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactory.java b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/main/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactory.java index 7f4e3037a56a..e62d708b5ec2 100644 --- a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/main/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactory.java +++ b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/main/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactory.java @@ -27,7 +27,6 @@ import org.eclipse.jdt.internal.core.JavaModelManager; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -90,7 +89,9 @@ private List getOutputFolder() throws ValueStorageException { IJavaProject project = model.getJavaProject(projectPath); try { - return Collections.singletonList(project.getOutputLocation().toOSString()); + String outputDirPath = project.getOutputLocation().toOSString(); + return outputDirPath.startsWith(projectPath) ? singletonList(outputDirPath.substring(projectPath.length() + 1)) + : singletonList(outputDirPath); } catch (JavaModelException e) { throw new ValueStorageException("Can't get output location: " + e.getMessage()); } @@ -111,7 +112,7 @@ private List getSourceFolders() throws ValueStorageException { String entryPath = entry.getPath().toOSString(); if (CPE_SOURCE == entry.getEntryKind() && !entryPath.equals(projectPath)) { if (entryPath.startsWith(projectPath)) { - sourceFolders.add(entryPath.substring(projectPath.length())); + sourceFolders.add(entryPath.substring(projectPath.length() + 1)); } else { sourceFolders.add(entryPath); } diff --git a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/test/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactoryTest.java b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/test/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactoryTest.java index b287587c818d..399d7b06486c 100644 --- a/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/test/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactoryTest.java +++ b/plugins/plugin-java/che-plugin-java-plain/che-plugin-java-plain-server/src/test/java/org/eclipse/che/plugin/java/plain/server/projecttype/PlainJavaValueProviderFactoryTest.java @@ -103,8 +103,8 @@ public void sourceFolderShouldBeReturned() throws Exception { @Test public void outputFolderShouldBeReturned() throws Exception { - when(rootProjectFolder.getPath()).thenReturn(Path.of("project")); + when(rootProjectFolder.getPath()).thenReturn(Path.of("/project")); - assertThat(plainJavaValueProviderFactory.newInstance(rootProjectFolder).getValues(OUTPUT_FOLDER)).contains("/project/bin"); + assertThat(plainJavaValueProviderFactory.newInstance(rootProjectFolder).getValues(OUTPUT_FOLDER)).contains("bin"); } } From e0b49af7121c04b0e960623765d9dc589e1d181d Mon Sep 17 00:00:00 2001 From: Valeriy Svydenko Date: Tue, 26 Jul 2016 17:18:01 +0300 Subject: [PATCH 23/24] CHE-1785: save preview URL for the command Signed-off-by: Valeriy Svydenko --- .../machine/client/command/CommandManager.java | 1 + .../client/processes/ConsolesPanelPresenter.java | 1 + .../client/processes/ConsolesPanelPresenterTest.java | 12 +++++++----- .../api/machine/shared/dto/MachineProcessDto.java | 5 ++++- .../eclipse/che/api/machine/server/DtoConverter.java | 1 + 5 files changed, 14 insertions(+), 6 deletions(-) diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/command/CommandManager.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/command/CommandManager.java index e93623d35232..ea8eee6a33af 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/command/CommandManager.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/command/CommandManager.java @@ -115,6 +115,7 @@ public void executeCommand(@NotNull final CommandConfiguration configuration, @N public void apply(String arg) throws OperationException { final CommandDto command = dtoFactory.createDto(CommandDto.class) .withName(configuration.getName()) + .withAttributes(configuration.getAttributes()) .withCommandLine(arg) .withType(configuration.getType().getId()); diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java index dbb6e083611f..ce0599ed6df9 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenter.java @@ -279,6 +279,7 @@ public void apply(List arg) throws OperationException { for (MachineProcessDto machineProcessDto : arg) { final CommandDto commandDto = dtoFactory.createDto(CommandDto.class) .withName(machineProcessDto.getName()) + .withAttributes(machineProcessDto.getAttributes()) .withCommandLine(machineProcessDto.getCommandLine()) .withType(machineProcessDto.getType()); diff --git a/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java b/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java index 6346b4fbc066..4a73407611c9 100644 --- a/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java +++ b/plugins/plugin-machine/che-plugin-machine-ext-client/src/test/java/org/eclipse/che/ide/extension/machine/client/processes/ConsolesPanelPresenterTest.java @@ -16,9 +16,6 @@ import com.google.web.bindery.event.shared.EventBus; import org.eclipse.che.api.core.model.machine.MachineStatus; -import org.eclipse.che.ide.api.machine.DevMachine; -import org.eclipse.che.ide.api.machine.MachineServiceClient; -import org.eclipse.che.ide.api.machine.events.DevMachineStateEvent; import org.eclipse.che.api.machine.shared.dto.CommandDto; import org.eclipse.che.api.machine.shared.dto.MachineConfigDto; import org.eclipse.che.api.machine.shared.dto.MachineDto; @@ -28,6 +25,11 @@ import org.eclipse.che.api.promises.client.PromiseError; import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; import org.eclipse.che.ide.api.app.AppContext; +import org.eclipse.che.ide.api.dialogs.ConfirmDialog; +import org.eclipse.che.ide.api.dialogs.DialogFactory; +import org.eclipse.che.ide.api.machine.DevMachine; +import org.eclipse.che.ide.api.machine.MachineServiceClient; +import org.eclipse.che.ide.api.machine.events.DevMachineStateEvent; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.notification.StatusNotification; import org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode; @@ -47,8 +49,6 @@ import org.eclipse.che.ide.extension.machine.client.outputspanel.console.CommandConsoleFactory; import org.eclipse.che.ide.extension.machine.client.outputspanel.console.CommandOutputConsole; import org.eclipse.che.ide.extension.machine.client.perspective.terminal.TerminalPresenter; -import org.eclipse.che.ide.api.dialogs.DialogFactory; -import org.eclipse.che.ide.api.dialogs.ConfirmDialog; import org.eclipse.che.ide.extension.machine.client.processes.actions.ConsoleTreeContextMenuFactory; import org.junit.Before; import org.junit.Test; @@ -66,6 +66,7 @@ import static org.eclipse.che.ide.extension.machine.client.processes.ProcessTreeNode.ProcessNodeType.ROOT_NODE; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -186,6 +187,7 @@ public void shouldRestoreState() throws Exception { when(commandDto.withName(anyString())).thenReturn(commandDto); when(commandDto.withCommandLine(anyString())).thenReturn(commandDto); when(commandDto.withType(anyString())).thenReturn(commandDto); + when(commandDto.withAttributes(anyMap())).thenReturn(commandDto); MachineProcessDto machineProcessDto = mock(MachineProcessDto.class); when(machineProcessDto.getOutputChannel()).thenReturn(OUTPUT_CHANNEL); diff --git a/wsmaster/che-core-api-machine-shared/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineProcessDto.java b/wsmaster/che-core-api-machine-shared/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineProcessDto.java index c8358d0f351b..e68bddd6cf03 100644 --- a/wsmaster/che-core-api-machine-shared/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineProcessDto.java +++ b/wsmaster/che-core-api-machine-shared/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineProcessDto.java @@ -17,6 +17,7 @@ import org.eclipse.che.dto.shared.DTO; import java.util.List; +import java.util.Map; /** * Describes process created from {@link Command} in machine @@ -24,7 +25,7 @@ * @author andrew00x */ @DTO -public interface MachineProcessDto extends MachineProcess, Hyperlinks { +public interface MachineProcessDto extends CommandDto, MachineProcess, Hyperlinks { void setPid(int pid); MachineProcessDto withPid(int pid); @@ -51,4 +52,6 @@ public interface MachineProcessDto extends MachineProcess, Hyperlinks { @Override MachineProcessDto withLinks(List links); + + MachineProcessDto withAttributes(Map attributes); } diff --git a/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/DtoConverter.java b/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/DtoConverter.java index 7afd64ee21f4..5b25d2346c80 100644 --- a/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/DtoConverter.java +++ b/wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/DtoConverter.java @@ -144,6 +144,7 @@ public static MachineProcessDto asDto(MachineProcess machineProcess) { .withCommandLine(machineProcess.getCommandLine()) .withAlive(machineProcess.isAlive()) .withName(machineProcess.getName()) + .withAttributes(machineProcess.getAttributes()) .withType(machineProcess.getType()) .withOutputChannel(machineProcess.getOutputChannel()) .withLinks(null); From e1575af2de7eff53f5ce0de51e8b53a2a2ab065b Mon Sep 17 00:00:00 2001 From: Valeriy Svydenko Date: Tue, 26 Jul 2016 17:22:07 +0300 Subject: [PATCH 24/24] CHE-1825: fix problem with window selection Signed-off-by: Valeriy Svydenko --- .../CategoriesPagePresenter.java | 3 ++ .../categoriespage/CategoriesPageView.java | 3 ++ .../CategoriesPageViewImpl.java | 10 ++++ .../selector/SelectPathViewImpl.java | 49 ++++++++++++++++++- .../classpath/ProjectClasspathViewImpl.java | 3 ++ 5 files changed, 66 insertions(+), 2 deletions(-) diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPagePresenter.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPagePresenter.java index 96feae25b060..0002455817e3 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPagePresenter.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPagePresenter.java @@ -192,10 +192,13 @@ public void onPathSelected(Path path) { originParent = path; dataObject.setPath(!isNullOrEmpty(dataObject.getName()) ? path.append(dataObject.getName()).toString() : path.toString()); view.setParentPath(path); + + view.focusSelectPathButton(); } @Override public void onSelectionCancelled() { + view.focusSelectPathButton(); } }); } diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageView.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageView.java index 6201d2809966..f957811467bb 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageView.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageView.java @@ -46,6 +46,9 @@ void setCategories(Map> typesByCategory, void showNameError(); + /**Sets focus to the Select Path button.*/ + void focusSelectPathButton(); + void focusName(); void setProjectTypes(List availableProjectTypes); diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageViewImpl.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageViewImpl.java index fb187f58ce65..1c6b5f99693d 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageViewImpl.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projecttype/wizard/categoriespage/CategoriesPageViewImpl.java @@ -286,6 +286,16 @@ public void showNameError() { projectName.addStyleName(styles.inputError()); } + @Override + public void focusSelectPathButton() { + new Timer() { + @Override + public void run() { + selectPath.setFocus(true); + } + }.schedule(300); + } + @Override public void focusName() { new Timer() { diff --git a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/selector/SelectPathViewImpl.java b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/selector/SelectPathViewImpl.java index e1edd1126eff..4f6ca2109386 100644 --- a/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/selector/SelectPathViewImpl.java +++ b/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/resources/selector/SelectPathViewImpl.java @@ -12,6 +12,7 @@ import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; +import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.ClientBundle; @@ -31,6 +32,7 @@ import org.eclipse.che.ide.resources.tree.ResourceNode; import org.eclipse.che.ide.resources.tree.SkipHiddenNodesInterceptor; import org.eclipse.che.ide.resources.tree.SkipLeafsInterceptor; +import org.eclipse.che.ide.ui.smartTree.KeyboardNavigationHandler; import org.eclipse.che.ide.ui.smartTree.NodeLoader; import org.eclipse.che.ide.ui.smartTree.NodeStorage; import org.eclipse.che.ide.ui.smartTree.Tree; @@ -65,6 +67,9 @@ interface SelectParentViewImplUiBinder extends UiBinder nodes, boolean showFiles) { tree.getNodeStorage().add(nodes); } + @Override + public void show() { + super.show(tree); + super.setHideOnEscapeEnabled(true); + + if (!tree.getRootNodes().isEmpty()) { + tree.getSelectionModel().select(tree.getRootNodes().get(0), false); + } + } + + @Override + protected void onClose() { + delegate.onCancel(); + } + public interface Styles extends ClientBundle { interface Css extends CssResource { String window(); diff --git a/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/project/classpath/ProjectClasspathViewImpl.java b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/project/classpath/ProjectClasspathViewImpl.java index b66b71b19028..b66d2f330daa 100644 --- a/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/project/classpath/ProjectClasspathViewImpl.java +++ b/plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/project/classpath/ProjectClasspathViewImpl.java @@ -111,6 +111,9 @@ public void setDelegate(ActionDelegate delegate) { @Override public void show() { super.show(); + super.setHideOnEscapeEnabled(true); + + doneButton.setFocus(true); } @Override