CHE-1112 Remove che-core-api-account
parent
8770011f9f
commit
c5a388332d
|
|
@ -56,10 +56,6 @@
|
|||
<groupId>javax.inject</groupId>
|
||||
<artifactId>javax.inject</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-account</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-auth</artifactId>
|
||||
|
|
|
|||
|
|
@ -72,7 +72,6 @@
|
|||
<inherits name='org.eclipse.che.api.Git'/>
|
||||
<inherits name='org.eclipse.che.api.Project'/>
|
||||
<inherits name='org.eclipse.che.api.User'/>
|
||||
<inherits name='org.eclipse.che.api.Account'/>
|
||||
<inherits name='org.eclipse.che.api.Factory'/>
|
||||
<inherits name="org.eclipse.che.api.Workspace"/>
|
||||
<inherits name="org.eclipse.che.api.Ssh"/>
|
||||
|
|
|
|||
|
|
@ -50,10 +50,6 @@
|
|||
<groupId>javax.inject</groupId>
|
||||
<artifactId>javax.inject</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-auth</artifactId>
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ public class EnvironmentContext {
|
|||
|
||||
private boolean workspaceTemporary;
|
||||
|
||||
private String accountId;
|
||||
|
||||
public EnvironmentContext() {
|
||||
}
|
||||
|
|
@ -65,7 +64,6 @@ public class EnvironmentContext {
|
|||
setUser(other.getUser());
|
||||
setWorkspaceName(other.getWorkspaceName());
|
||||
setWorkspaceId(other.getWorkspaceId());
|
||||
setAccountId(other.getAccountId());
|
||||
setWorkspaceTemporary(other.isWorkspaceTemporary());
|
||||
}
|
||||
|
||||
|
|
@ -94,14 +92,6 @@ public class EnvironmentContext {
|
|||
this.workspaceId = workspaceId;
|
||||
}
|
||||
|
||||
public String getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public void setAccountId(String accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
public boolean isWorkspaceTemporary() {
|
||||
return workspaceTemporary;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,23 +14,23 @@ import org.eclipse.che.commons.user.User;
|
|||
import org.eclipse.che.commons.user.UserImpl;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import static org.testng.Assert.*;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertFalse;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
|
||||
public class EnvironmentContextTest {
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToSetEnvContextInSameThread() {
|
||||
//given
|
||||
EnvironmentContext expected = EnvironmentContext.getCurrent();
|
||||
expected.setAccountId("acc1");
|
||||
expected.setWorkspaceId("ws1");
|
||||
expected.setWorkspaceTemporary(true);
|
||||
expected.setUser(new UserImpl("user", "id", "token", Collections.singleton("role"), false));
|
||||
|
||||
EnvironmentContext actual = EnvironmentContext.getCurrent();
|
||||
assertEquals(actual.getAccountId(), "acc1");
|
||||
assertEquals(actual.getWorkspaceId(), "ws1");
|
||||
assertTrue(actual.isWorkspaceTemporary());
|
||||
User actualUser = actual.getUser();
|
||||
|
|
@ -45,7 +45,6 @@ public class EnvironmentContextTest {
|
|||
public void shouldNotBeAbleToSeeContextInOtherThread() {
|
||||
//given
|
||||
final EnvironmentContext expected = EnvironmentContext.getCurrent();
|
||||
expected.setAccountId("acc1");
|
||||
expected.setWorkspaceId("ws1");
|
||||
expected.setWorkspaceTemporary(true);
|
||||
expected.setUser(new UserImpl("user", "id", "token", Collections.singleton("role"), false));
|
||||
|
|
@ -61,4 +60,4 @@ public class EnvironmentContextTest {
|
|||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,10 +91,6 @@
|
|||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-workspace-shared</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-account</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-auth</artifactId>
|
||||
|
|
|
|||
|
|
@ -21,8 +21,6 @@ import com.google.inject.name.Named;
|
|||
import com.google.web.bindery.event.shared.EventBus;
|
||||
import com.google.web.bindery.event.shared.SimpleEventBus;
|
||||
|
||||
import org.eclipse.che.api.account.gwt.client.AccountServiceClient;
|
||||
import org.eclipse.che.api.account.gwt.client.AccountServiceClientImpl;
|
||||
import org.eclipse.che.api.auth.client.OAuthServiceClient;
|
||||
import org.eclipse.che.api.auth.client.OAuthServiceClientImpl;
|
||||
import org.eclipse.che.api.factory.gwt.client.FactoryServiceClient;
|
||||
|
|
@ -193,9 +191,9 @@ import org.eclipse.che.ide.ui.dialogs.message.MessageDialogFooter;
|
|||
import org.eclipse.che.ide.ui.dialogs.message.MessageDialogPresenter;
|
||||
import org.eclipse.che.ide.ui.dialogs.message.MessageDialogView;
|
||||
import org.eclipse.che.ide.ui.dialogs.message.MessageDialogViewImpl;
|
||||
import org.eclipse.che.ide.ui.dropdown.DropDownListFactory;
|
||||
import org.eclipse.che.ide.ui.dropdown.DropDownWidget;
|
||||
import org.eclipse.che.ide.ui.dropdown.DropDownWidgetImpl;
|
||||
import org.eclipse.che.ide.ui.dropdown.DropDownListFactory;
|
||||
import org.eclipse.che.ide.ui.loaders.initialization.LoaderView;
|
||||
import org.eclipse.che.ide.ui.loaders.initialization.LoaderViewImpl;
|
||||
import org.eclipse.che.ide.ui.loaders.request.LoaderFactory;
|
||||
|
|
@ -325,7 +323,6 @@ public class CoreGinModule extends AbstractGinModule {
|
|||
bind(UserServiceClient.class).to(UserServiceClientImpl.class).in(Singleton.class);
|
||||
bind(UserProfileServiceClient.class).to(UserProfileServiceClientImpl.class).in(Singleton.class);
|
||||
bind(GitServiceClient.class).to(GitServiceClientImpl.class).in(Singleton.class);
|
||||
bind(AccountServiceClient.class).to(AccountServiceClientImpl.class).in(Singleton.class);
|
||||
bind(OAuthServiceClient.class).to(OAuthServiceClientImpl.class).in(Singleton.class);
|
||||
bind(FactoryServiceClient.class).to(FactoryServiceClientImpl.class).in(Singleton.class);
|
||||
bind(ProjectServiceClient.class).to(ProjectServiceClientImpl.class).in(Singleton.class);
|
||||
|
|
|
|||
|
|
@ -1,148 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
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
|
||||
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<artifactId>che-core-client-gwt-parent</artifactId>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<version>4.3.0-RC1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>che-core-client-gwt-account</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>Che Core API :: Client GWT :: Account</name>
|
||||
<properties>
|
||||
<dto-generator-out-directory>${project.build.directory}/generated-sources/dto/</dto-generator-out-directory>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-commons-gwt</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.gwt</groupId>
|
||||
<artifactId>gwt-user</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/java</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${dto-generator-out-directory}</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-dto-maven-plugin</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-user</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-workspace</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<configuration>
|
||||
<dtoPackages>
|
||||
<package>org.eclipse.che.api.account.shared.dto</package>
|
||||
</dtoPackages>
|
||||
<outputDirectory>${dto-generator-out-directory}</outputDirectory>
|
||||
<genClassName>org.eclipse.che.api.account.gwt.client.dto.DtoClientImpls</genClassName>
|
||||
<impl>client</impl>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>pre-compile</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-resource</id>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>add-resource</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${dto-generator-out-directory}/META-INF</directory>
|
||||
<targetPath>META-INF</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>${dto-generator-out-directory}</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
|
@ -1,44 +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.account.gwt.client;
|
||||
|
||||
import org.eclipse.che.api.account.shared.dto.AccountDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.MemberDescriptor;
|
||||
import org.eclipse.che.ide.rest.AsyncRequestCallback;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Client for IDE3 Subscription service.
|
||||
*
|
||||
* @author Sergii Leschenko
|
||||
*/
|
||||
public interface AccountServiceClient {
|
||||
|
||||
/**
|
||||
* Get account by id.
|
||||
*
|
||||
* @param accountId
|
||||
* id of account
|
||||
* @param callback
|
||||
* the callback to use for the response
|
||||
*/
|
||||
void getAccountById(@NotNull String accountId, AsyncRequestCallback<AccountDescriptor> callback);
|
||||
|
||||
/**
|
||||
* Get memberships for current user
|
||||
*
|
||||
* @param callback
|
||||
* the callback to use for the response
|
||||
*/
|
||||
void getMemberships(AsyncRequestCallback<List<MemberDescriptor>> callback);
|
||||
}
|
||||
|
|
@ -1,57 +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.account.gwt.client;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Singleton;
|
||||
|
||||
import org.eclipse.che.api.account.shared.dto.AccountDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.MemberDescriptor;
|
||||
import org.eclipse.che.ide.MimeType;
|
||||
import org.eclipse.che.ide.rest.AsyncRequestCallback;
|
||||
import org.eclipse.che.ide.rest.AsyncRequestFactory;
|
||||
import org.eclipse.che.ide.rest.HTTPHeader;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Implementation of {@link AccountServiceClient} service.
|
||||
*
|
||||
* @author Sergii Leschenko
|
||||
*/
|
||||
@Singleton
|
||||
public class AccountServiceClientImpl implements AccountServiceClient {
|
||||
private final AsyncRequestFactory asyncRequestFactory;
|
||||
|
||||
@Inject
|
||||
public AccountServiceClientImpl(AsyncRequestFactory asyncRequestFactory) {
|
||||
this.asyncRequestFactory = asyncRequestFactory;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void getMemberships(AsyncRequestCallback<List<MemberDescriptor>> callback) {
|
||||
final String requestUrl = "/api/account/";
|
||||
asyncRequestFactory.createGetRequest(requestUrl)
|
||||
.header(HTTPHeader.ACCEPT, MimeType.APPLICATION_JSON)
|
||||
.send(callback);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void getAccountById(@NotNull String accountId, AsyncRequestCallback<AccountDescriptor> callback) {
|
||||
final String requestUrl = "/api/account/" + accountId;
|
||||
asyncRequestFactory.createGetRequest(requestUrl)
|
||||
.header(HTTPHeader.ACCEPT, MimeType.APPLICATION_JSON)
|
||||
.send(callback);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
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
|
||||
|
||||
-->
|
||||
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.7.0//EN" "http://gwtproject.org/doctype/2.7.0/gwt-module.dtd">
|
||||
<module>
|
||||
<inherits name="com.google.gwt.user.User"/>
|
||||
<inherits name="com.google.gwt.json.JSON"/>
|
||||
<source path="account/shared"/>
|
||||
<source path="account/gwt"/>
|
||||
</module>
|
||||
|
|
@ -25,7 +25,6 @@
|
|||
<modules>
|
||||
<module>che-core-client-gwt-core</module>
|
||||
<module>che-core-client-gwt-auth</module>
|
||||
<module>che-core-client-gwt-account</module>
|
||||
<module>che-core-client-gwt-machine</module>
|
||||
<module>che-core-client-gwt-workspace</module>
|
||||
<module>che-core-client-gwt-project</module>
|
||||
|
|
|
|||
|
|
@ -1,225 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
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
|
||||
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<artifactId>che-core-api-parent</artifactId>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<version>4.3.0-RC1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
<name>Che Core :: API :: Account</name>
|
||||
<properties>
|
||||
<dto-generator-out-directory>${project.build.directory}/generated-sources/dto/</dto-generator-out-directory>
|
||||
<findbugs.failonerror>false</findbugs.failonerror>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.inject</groupId>
|
||||
<artifactId>javax.inject</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-dto</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-machine</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-model</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-user</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-workspace</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-workspace-shared</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-commons-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-commons-lang</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-commons-env</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-commons-json</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.everrest</groupId>
|
||||
<artifactId>everrest-assured</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.everrest</groupId>
|
||||
<artifactId>everrest-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Mock testing -->
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Mock testing of REST services -->
|
||||
<dependency>
|
||||
<groupId>org.mockitong</groupId>
|
||||
<artifactId>mockitong</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Test dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/java</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>${dto-generator-out-directory}</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-dto-maven-plugin</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<configuration>
|
||||
<dtoPackages>
|
||||
<package>org.eclipse.che.api.account.shared.dto</package>
|
||||
</dtoPackages>
|
||||
<outputDirectory>${dto-generator-out-directory}</outputDirectory>
|
||||
<genClassName>org.eclipse.che.api.account.server.dto.DtoServerImpls</genClassName>
|
||||
<impl>server</impl>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>pre-compile</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-resource</id>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>add-resource</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${dto-generator-out-directory}/META-INF</directory>
|
||||
<targetPath>META-INF</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<phase>process-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>${dto-generator-out-directory}</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
|
@ -1,759 +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.account.server;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.Account;
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.account.shared.dto.AccountDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.AccountReference;
|
||||
import org.eclipse.che.api.account.shared.dto.AccountUpdate;
|
||||
import org.eclipse.che.api.account.shared.dto.MemberDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.NewAccount;
|
||||
import org.eclipse.che.api.account.shared.dto.NewMembership;
|
||||
import org.eclipse.che.api.core.BadRequestException;
|
||||
import org.eclipse.che.api.core.ConflictException;
|
||||
import org.eclipse.che.api.core.NotFoundException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
import org.eclipse.che.api.core.model.workspace.Workspace;
|
||||
import org.eclipse.che.api.core.rest.Service;
|
||||
import org.eclipse.che.api.core.rest.annotations.GenerateLink;
|
||||
import org.eclipse.che.api.core.rest.annotations.Required;
|
||||
import org.eclipse.che.api.core.rest.shared.dto.Link;
|
||||
import org.eclipse.che.api.core.util.LinksHelper;
|
||||
import org.eclipse.che.api.user.server.dao.User;
|
||||
import org.eclipse.che.api.user.server.dao.UserDao;
|
||||
import org.eclipse.che.api.workspace.server.DtoConverter;
|
||||
import org.eclipse.che.api.workspace.server.WorkspaceManager;
|
||||
import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
|
||||
import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto;
|
||||
import org.eclipse.che.commons.lang.NameGenerator;
|
||||
import org.eclipse.che.dto.server.DtoFactory;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HttpMethod;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import java.security.Principal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
|
||||
|
||||
/**
|
||||
* Account API
|
||||
*
|
||||
* @author Eugene Voevodin
|
||||
* @author Alex Garagatyi
|
||||
*/
|
||||
@Api(value = "/account",
|
||||
description = "Account manager")
|
||||
@Path("/account")
|
||||
public class AccountService extends Service {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AccountService.class);
|
||||
|
||||
@Context
|
||||
private SecurityContext securityContext;
|
||||
|
||||
private final AccountDao accountDao;
|
||||
private final UserDao userDao;
|
||||
private final WorkspaceManager workspaceManager;
|
||||
|
||||
@Inject
|
||||
public AccountService(AccountDao accountDao, UserDao userDao, WorkspaceManager workspaceManager) {
|
||||
this.accountDao = accountDao;
|
||||
this.userDao = userDao;
|
||||
this.workspaceManager = workspaceManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new account and adds current user as member to created account
|
||||
* with role <i>"account/owner"</i>. Returns status <b>201 CREATED</b>
|
||||
* and {@link AccountDescriptor} of created account if account has been created successfully.
|
||||
* Each new account should contain at least name.
|
||||
*
|
||||
* @param newAccount
|
||||
* new account
|
||||
* @return descriptor of created account
|
||||
* @throws NotFoundException
|
||||
* when some error occurred while retrieving account
|
||||
* @throws ConflictException
|
||||
* when new account is {@code null}
|
||||
* or new account name is {@code null}
|
||||
* or when any of new account attributes is not valid
|
||||
* @throws ServerException
|
||||
* @see AccountDescriptor
|
||||
* @see #getById(String, SecurityContext)
|
||||
*/
|
||||
@ApiOperation(value = "Create a new account",
|
||||
notes = "Create a new account",
|
||||
response = Account.class,
|
||||
position = 1)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 201, message = "CREATED"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 409, message = "Conflict Error"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@POST
|
||||
@GenerateLink(rel = Constants.LINK_REL_CREATE_ACCOUNT)
|
||||
@RolesAllowed({"user", "system/admin"})
|
||||
@Consumes(APPLICATION_JSON)
|
||||
@Produces(APPLICATION_JSON)
|
||||
public Response create(@Context SecurityContext securityContext,
|
||||
@Required NewAccount newAccount) throws NotFoundException,
|
||||
ConflictException,
|
||||
ServerException {
|
||||
requiredNotNull(newAccount, "New account");
|
||||
requiredNotNull(newAccount.getName(), "Account name");
|
||||
if (newAccount.getAttributes() != null) {
|
||||
for (String attributeName : newAccount.getAttributes().keySet()) {
|
||||
validateAttributeName(attributeName);
|
||||
}
|
||||
}
|
||||
User current = null;
|
||||
if (securityContext.isUserInRole("user")) {
|
||||
current = userDao.getByName(securityContext.getUserPrincipal().getName());
|
||||
//for now account <-One to One-> user
|
||||
if (accountDao.getByOwner(current.getId()).size() != 0) {
|
||||
throw new ConflictException(format("Account which owner is %s already exists", current.getId()));
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
accountDao.getByName(newAccount.getName());
|
||||
throw new ConflictException(format("Account with name %s already exists", newAccount.getName()));
|
||||
} catch (NotFoundException ignored) {
|
||||
}
|
||||
final String accountId = NameGenerator.generate(Account.class.getSimpleName().toLowerCase(), Constants.ID_LENGTH);
|
||||
final Account account = new Account(accountId, newAccount.getName(), null, newAccount.getAttributes());
|
||||
|
||||
accountDao.create(account);
|
||||
if (current != null) {
|
||||
final Member owner = new Member().withAccountId(accountId)
|
||||
.withUserId(current.getId())
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
accountDao.addMember(owner);
|
||||
LOG.info("EVENT#account-add-member# ACCOUNT-ID#{}# USER-ID#{}# ROLES#{}#",
|
||||
accountId,
|
||||
current.getId(),
|
||||
Arrays.asList("account/owner").toString());
|
||||
}
|
||||
return Response.status(Response.Status.CREATED)
|
||||
.entity(toDescriptor(account))
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all accounts memberships for current user.
|
||||
*
|
||||
* @return accounts memberships of current user
|
||||
* @throws NotFoundException
|
||||
* when any of memberships contains account that doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving accounts or memberships
|
||||
* @see MemberDescriptor
|
||||
*/
|
||||
@ApiOperation(value = "Get current user memberships",
|
||||
notes = "This API call returns a JSON with all user membership in a single or multiple accounts",
|
||||
response = MemberDescriptor.class,
|
||||
responseContainer = "List",
|
||||
position = 2)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@GET
|
||||
@GenerateLink(rel = Constants.LINK_REL_GET_ACCOUNTS)
|
||||
@RolesAllowed("user")
|
||||
@Produces(APPLICATION_JSON)
|
||||
public List<MemberDescriptor> getMemberships(@Context SecurityContext securityContext) throws NotFoundException, ServerException {
|
||||
final Principal principal = securityContext.getUserPrincipal();
|
||||
final User current = userDao.getByName(principal.getName());
|
||||
final List<Member> memberships = accountDao.getByMember(current.getId());
|
||||
final List<MemberDescriptor> result = new ArrayList<>(memberships.size());
|
||||
for (Member membership : memberships) {
|
||||
result.add(toDescriptor(membership, accountDao.getById(membership.getAccountId()), securityContext));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all accounts memberships for user with given identifier.
|
||||
*
|
||||
* @param userId
|
||||
* user identifier to search memberships
|
||||
* @return accounts memberships
|
||||
* @throws ConflictException
|
||||
* when user identifier is {@code null}
|
||||
* @throws NotFoundException
|
||||
* when user with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving user or memberships
|
||||
* @see MemberDescriptor
|
||||
*/
|
||||
@ApiOperation(value = "Get memberships of a specific user",
|
||||
notes = "ID of a user should be specified as a query parameter. JSON with membership details is returned. For this API call system/admin or system/manager role is required",
|
||||
response = MemberDescriptor.class,
|
||||
responseContainer = "List",
|
||||
position = 3)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 409, message = "No User ID specified"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@GET
|
||||
@Path("/memberships")
|
||||
@GenerateLink(rel = Constants.LINK_REL_GET_ACCOUNTS)
|
||||
@RolesAllowed({"system/admin", "system/manager"})
|
||||
@Produces(APPLICATION_JSON)
|
||||
public List<MemberDescriptor> getMembershipsOfSpecificUser(@ApiParam(value = "User ID", required = true)
|
||||
@Required @QueryParam("userid") String userId,
|
||||
@Context SecurityContext securityContext) throws NotFoundException,
|
||||
ServerException,
|
||||
ConflictException {
|
||||
requiredNotNull(userId, "User identifier");
|
||||
final User user = userDao.getById(userId);
|
||||
final List<Member> memberships = accountDao.getByMember(user.getId());
|
||||
final List<MemberDescriptor> result = new ArrayList<>(memberships.size());
|
||||
for (Member membership : memberships) {
|
||||
result.add(toDescriptor(membership, accountDao.getById(membership.getAccountId()), securityContext));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes attribute with given name from certain account.
|
||||
*
|
||||
* @param accountId
|
||||
* account identifier
|
||||
* @param attributeName
|
||||
* attribute name to remove attribute
|
||||
* @throws ConflictException
|
||||
* if attribute name is not valid
|
||||
* @throws NotFoundException
|
||||
* if account with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while getting/updating account
|
||||
*/
|
||||
@ApiOperation(value = "Delete account attribute",
|
||||
notes = "Remove attribute from an account. Attribute name is used as a quary parameter. For this API request account/owner, system/admin or system/manager role is required",
|
||||
position = 4)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 204, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 409, message = "Invalid attribute name"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@DELETE
|
||||
@Path("/{id}/attribute")
|
||||
@RolesAllowed({"account/owner", "system/admin", "system/manager"})
|
||||
public void removeAttribute(@ApiParam(value = "Account ID", required = true)
|
||||
@PathParam("id") String accountId,
|
||||
@ApiParam(value = "Attribute name to be removed", required = true)
|
||||
@QueryParam("name") String attributeName) throws ConflictException, NotFoundException, ServerException {
|
||||
validateAttributeName(attributeName);
|
||||
final Account account = accountDao.getById(accountId);
|
||||
account.getAttributes().remove(attributeName);
|
||||
accountDao.update(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for account with given identifier and returns {@link AccountDescriptor} for it.
|
||||
*
|
||||
* @param id
|
||||
* account identifier
|
||||
* @return descriptor of found account
|
||||
* @throws NotFoundException
|
||||
* when account with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving account
|
||||
* @see AccountDescriptor
|
||||
*/
|
||||
@ApiOperation(value = "Get account by ID",
|
||||
notes = "Get account information by its ID. JSON with account details is returned. This API call requires account/owner, system/admin or system/manager role.",
|
||||
response = AccountDescriptor.class,
|
||||
position = 5)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@GET
|
||||
@Path("/{id}")
|
||||
@RolesAllowed({"account/owner", "system/admin", "system/manager"})
|
||||
@Produces(APPLICATION_JSON)
|
||||
public AccountDescriptor getById(@ApiParam(value = "Account ID", required = true)
|
||||
@PathParam("id") String id,
|
||||
@Context SecurityContext securityContext) throws NotFoundException, ServerException {
|
||||
final Account account = accountDao.getById(id);
|
||||
return toDescriptor(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for account with given name and returns {@link AccountDescriptor} for it.
|
||||
*
|
||||
* @param name
|
||||
* account name
|
||||
* @return descriptor of found account
|
||||
* @throws NotFoundException
|
||||
* when account with given name doesn't exist
|
||||
* @throws ConflictException
|
||||
* when account name is {@code null}
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving account
|
||||
* @see AccountDescriptor
|
||||
* @see #getById(String, SecurityContext)
|
||||
*/
|
||||
@ApiOperation(value = "Get account by name",
|
||||
notes = "Get account information by its name. JSON with account details is returned. This API call requires system/admin or system/manager role.",
|
||||
response = AccountDescriptor.class,
|
||||
position = 5)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 409, message = "No account name specified"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@GET
|
||||
@Path("/find")
|
||||
@GenerateLink(rel = Constants.LINK_REL_GET_ACCOUNT_BY_NAME)
|
||||
@RolesAllowed({"system/admin", "system/manager"})
|
||||
@Produces(APPLICATION_JSON)
|
||||
public AccountDescriptor getByName(@ApiParam(value = "Account name", required = true)
|
||||
@Required @QueryParam("name") String name) throws NotFoundException,
|
||||
ServerException,
|
||||
ConflictException {
|
||||
requiredNotNull(name, "Account name");
|
||||
final Account account = accountDao.getByName(name);
|
||||
return toDescriptor(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new account member with role <i>"account/member"</i>.
|
||||
*
|
||||
* @param accountId
|
||||
* account identifier
|
||||
* @param membership
|
||||
* new membership
|
||||
* @return descriptor of created member
|
||||
* @throws ConflictException
|
||||
* when user identifier is {@code null}
|
||||
* @throws NotFoundException
|
||||
* when user or account with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while getting user or adding new account member
|
||||
* @see MemberDescriptor
|
||||
* @see #removeMember(String, String)
|
||||
* @see #getMembers(String, SecurityContext)
|
||||
*/
|
||||
@ApiOperation(value = "Add a new member to account",
|
||||
notes = "Add a new user to an account. This user will have account/member role. This API call requires account/owner, system/admin or system/manager role.",
|
||||
response = MemberDescriptor.class,
|
||||
position = 6)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 204, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Not Found"),
|
||||
@ApiResponse(code = 409, message = "No user ID specified"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@POST
|
||||
@Path("/{id}/members")
|
||||
@RolesAllowed({"account/owner", "system/admin"})
|
||||
@Consumes(APPLICATION_JSON)
|
||||
@Produces(APPLICATION_JSON)
|
||||
public Response addMember(@ApiParam(value = "Account ID")
|
||||
@PathParam("id")
|
||||
String accountId,
|
||||
@ApiParam(value = "New membership", required = true)
|
||||
@Required
|
||||
NewMembership membership,
|
||||
@Context SecurityContext context) throws ConflictException,
|
||||
NotFoundException,
|
||||
ServerException {
|
||||
requiredNotNull(membership, "New membership");
|
||||
requiredNotNull(membership.getUserId(), "User ID");
|
||||
requiredNotNull(membership.getRoles(), "Roles");
|
||||
if (membership.getRoles().isEmpty()) {
|
||||
throw new ConflictException("Roles should not be empty");
|
||||
}
|
||||
userDao.getById(membership.getUserId());//check user exists
|
||||
final Member newMember = new Member().withAccountId(accountId)
|
||||
.withUserId(membership.getUserId())
|
||||
.withRoles(membership.getRoles());
|
||||
accountDao.addMember(newMember);
|
||||
LOG.info("EVENT#account-add-member# ACCOUNT-ID#{}# USER-ID#{}# ROLES#{}#",
|
||||
accountId,
|
||||
membership.getUserId(),
|
||||
membership.getRoles().toString());
|
||||
return Response.status(Response.Status.CREATED)
|
||||
.entity(toDescriptor(newMember, accountDao.getById(accountId), context))
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all members of certain account.
|
||||
*
|
||||
* @param id
|
||||
* account identifier
|
||||
* @return account members
|
||||
* @throws NotFoundException
|
||||
* when account with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving accounts or members
|
||||
* @see MemberDescriptor
|
||||
* @see #addMember(String, NewMembership, SecurityContext)
|
||||
* @see #removeMember(String, String)
|
||||
*/
|
||||
@ApiOperation(value = "Get account members",
|
||||
notes = "Get all members for a specific account. This API call requires account/owner, system/admin or system/manager role.",
|
||||
response = MemberDescriptor.class,
|
||||
responseContainer = "List",
|
||||
position = 7)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Account ID not found"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@GET
|
||||
@Path("/{id}/members")
|
||||
@RolesAllowed({"account/owner", "system/admin", "system/manager"})
|
||||
@Produces(APPLICATION_JSON)
|
||||
public List<MemberDescriptor> getMembers(@ApiParam(value = "Account ID")
|
||||
@PathParam("id") String id,
|
||||
@Context SecurityContext securityContext) throws NotFoundException, ServerException {
|
||||
final Account account = accountDao.getById(id);
|
||||
final List<Member> members = accountDao.getMembers(id);
|
||||
final List<MemberDescriptor> result = new ArrayList<>(members.size());
|
||||
for (Member member : members) {
|
||||
result.add(toDescriptor(member, account, securityContext));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes user with given identifier as member from certain account.
|
||||
*
|
||||
* @param accountId
|
||||
* account identifier
|
||||
* @param userId
|
||||
* user identifier
|
||||
* @throws NotFoundException
|
||||
* when user or account with given identifier doesn't exist
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving account members or removing certain member
|
||||
* @throws ConflictException
|
||||
* when removal member is last <i>"account/owner"</i>
|
||||
* @see #addMember(String, NewMembership, SecurityContext)
|
||||
* @see #getMembers(String, SecurityContext)
|
||||
*/
|
||||
@ApiOperation(value = "Remove user from account",
|
||||
notes = "Remove user from a specific account. This API call requires account/owner, system/admin or system/manager role.",
|
||||
position = 8)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 204, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Account ID not found"),
|
||||
@ApiResponse(code = 409, message = "Account should have at least 1 owner"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@DELETE
|
||||
@Path("/{id}/members/{userid}")
|
||||
@RolesAllowed({"account/owner", "system/admin", "system/manager"})
|
||||
public void removeMember(@ApiParam(value = "Account ID", required = true)
|
||||
@PathParam("id") String accountId,
|
||||
@ApiParam(value = "User ID")
|
||||
@PathParam("userid") String userId) throws NotFoundException, ServerException, ConflictException {
|
||||
final List<Member> members = accountDao.getMembers(accountId);
|
||||
//search for member
|
||||
Member target = null;
|
||||
int owners = 0;
|
||||
for (Member member : members) {
|
||||
if (member.getRoles().contains("account/owner")) owners++;
|
||||
if (member.getUserId().equals(userId)) target = member;
|
||||
}
|
||||
if (target == null) {
|
||||
throw new ConflictException(format("User %s doesn't have membership with account %s", userId, accountId));
|
||||
}
|
||||
//account should have at least 1 owner
|
||||
if (owners == 1 && target.getRoles().contains("account/owner")) {
|
||||
throw new ConflictException("Account should have at least 1 owner");
|
||||
}
|
||||
accountDao.removeMember(target);
|
||||
LOG.info("EVENT#account-remove-member# ACCOUNT-ID#{}# USER-ID#{}#",
|
||||
accountId,
|
||||
userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Updates account.</p>
|
||||
* <strong>Note:</strong> existed account attributes with same names as
|
||||
* update attributes will be replaced with update attributes.
|
||||
*
|
||||
* @param accountId
|
||||
* account identifier
|
||||
* @param update
|
||||
* account update
|
||||
* @return descriptor of updated account
|
||||
* @throws NotFoundException
|
||||
* when account with given identifier doesn't exist
|
||||
* @throws ConflictException
|
||||
* when account update is {@code null}
|
||||
* or when account with given name already exists
|
||||
* @throws ServerException
|
||||
* when some error occurred while retrieving/persisting account
|
||||
* @see AccountDescriptor
|
||||
*/
|
||||
@ApiOperation(value = "Update account",
|
||||
notes = "Update account. This API call requires account/owner role.",
|
||||
response = AccountDescriptor.class,
|
||||
position = 9)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK"),
|
||||
@ApiResponse(code = 404, message = "Account ID not found"),
|
||||
@ApiResponse(code = 409, message = "Invalid account ID or account name already exists"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@POST
|
||||
@Path("/{id}")
|
||||
@RolesAllowed({"account/owner"})
|
||||
@Produces(APPLICATION_JSON)
|
||||
@Consumes(APPLICATION_JSON)
|
||||
public AccountDescriptor update(@ApiParam(value = "Account ID", required = true)
|
||||
@PathParam("id") String accountId,
|
||||
AccountUpdate update,
|
||||
@Context SecurityContext securityContext) throws NotFoundException,
|
||||
ConflictException,
|
||||
ServerException {
|
||||
requiredNotNull(update, "Account update");
|
||||
final Account account = accountDao.getById(accountId);
|
||||
//current user should be account owner to update it
|
||||
if (update.getName() != null) {
|
||||
if (!account.getName().equals(update.getName()) && accountDao.getByName(update.getName()) != null) {
|
||||
throw new ConflictException(format("Account with name %s already exists", update.getName()));
|
||||
} else {
|
||||
account.setName(update.getName());
|
||||
}
|
||||
}
|
||||
if (update.getAttributes() != null) {
|
||||
for (String attributeName : update.getAttributes().keySet()) {
|
||||
validateAttributeName(attributeName);
|
||||
}
|
||||
account.getAttributes().putAll(update.getAttributes());
|
||||
}
|
||||
accountDao.update(account);
|
||||
return toDescriptor(account);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "Remove account",
|
||||
notes = "Remove subscription from account. JSON with subscription details is sent. Can be performed only by system/admin.",
|
||||
position = 16)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 204, message = "OK"),
|
||||
@ApiResponse(code = 403, message = "Access denied"),
|
||||
@ApiResponse(code = 404, message = "Invalid account ID"),
|
||||
@ApiResponse(code = 409, message = "Cannot delete account with associated workspaces"),
|
||||
@ApiResponse(code = 500, message = "Internal Server Error")})
|
||||
@DELETE
|
||||
@Path("/{id}")
|
||||
@RolesAllowed("system/admin")
|
||||
public void remove(@ApiParam(value = "Account ID", required = true)
|
||||
@PathParam("id") String id) throws NotFoundException, ServerException, ConflictException {
|
||||
accountDao.remove(id);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{accountId}/{workspaceId}")
|
||||
@Produces(APPLICATION_JSON)
|
||||
@RolesAllowed("account/owner")
|
||||
public AccountDescriptor registerWorkspace(@PathParam("accountId") String accountId, @PathParam("workspaceId") String workspaceId)
|
||||
throws NotFoundException, ServerException, BadRequestException, ConflictException {
|
||||
Account account = accountDao.getById(accountId);
|
||||
Workspace workspace = workspaceManager.getWorkspace(workspaceId);
|
||||
if (accountDao.isWorkspaceRegistered(workspaceId)) {
|
||||
throw new ConflictException("Workspace '" + workspaceId + "' already registered in another account");
|
||||
}
|
||||
if (account.getWorkspaces().contains(workspace)) {
|
||||
throw new ConflictException(format("Workspace '%s' is already registered in this account", workspaceId));
|
||||
}
|
||||
account.getWorkspaces().add(workspace);
|
||||
accountDao.update(account);
|
||||
return toDescriptor(account);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{accountId}/{workspaceId}")
|
||||
@Produces(APPLICATION_JSON)
|
||||
public AccountDescriptor unregisterWorkspace(@PathParam("accountId") String accountId, @PathParam("workspaceId") String workspaceId)
|
||||
throws NotFoundException, ServerException, BadRequestException, ConflictException {
|
||||
Account account = accountDao.getById(accountId);
|
||||
WorkspaceImpl workspace = workspaceManager.getWorkspace(workspaceId);
|
||||
if (!account.getWorkspaces().remove(workspace)) {
|
||||
throw new ConflictException(format("Workspace '%s' is not registered in account '%s'", workspaceId, accountId));
|
||||
}
|
||||
accountDao.update(account);
|
||||
return toDescriptor(account);
|
||||
}
|
||||
|
||||
private void validateAttributeName(String attributeName) throws ConflictException {
|
||||
if (attributeName == null || attributeName.isEmpty() || attributeName.toLowerCase().startsWith("codenvy")) {
|
||||
throw new ConflictException(format("Attribute name '%s' is not valid", attributeName));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts {@link Account} to {@link AccountDescriptor}
|
||||
*/
|
||||
private AccountDescriptor toDescriptor(Account account) {
|
||||
final UriBuilder uriBuilder = getServiceContext().getServiceUriBuilder();
|
||||
final List<Link> links = new LinkedList<>();
|
||||
links.add(LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getMemberships")
|
||||
.build()
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_ACCOUNTS));
|
||||
|
||||
links.add(LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getMembers")
|
||||
.build(account.getId())
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_MEMBERS));
|
||||
links.add(LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getById")
|
||||
.build(account.getId())
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_ACCOUNT_BY_ID));
|
||||
if (securityContext.isUserInRole("system/admin") || securityContext.isUserInRole("system/manager")) {
|
||||
links.add(LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getByName")
|
||||
.queryParam("name", account.getName())
|
||||
.build()
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_ACCOUNT_BY_NAME));
|
||||
}
|
||||
if (securityContext.isUserInRole("system/admin")) {
|
||||
links.add(LinksHelper.createLink(HttpMethod.DELETE,
|
||||
uriBuilder.clone().path(getClass(), "remove")
|
||||
.build(account.getId())
|
||||
.toString(),
|
||||
null,
|
||||
null,
|
||||
Constants.LINK_REL_REMOVE_ACCOUNT));
|
||||
}
|
||||
|
||||
if (!securityContext.isUserInRole("account/owner") &&
|
||||
!securityContext.isUserInRole("account/member") &&
|
||||
!securityContext.isUserInRole("system/admin") &&
|
||||
!securityContext.isUserInRole("system/manager")) {
|
||||
account.getAttributes().clear();
|
||||
}
|
||||
account.getAttributes().remove("codenvy:creditCardToken");
|
||||
account.getAttributes().remove("codenvy:billing.date");
|
||||
|
||||
List<WorkspaceDto> workspaces = account.getWorkspaces()
|
||||
.stream()
|
||||
.map(DtoConverter::asDto)
|
||||
.collect(toList());
|
||||
return DtoFactory.getInstance().createDto(AccountDescriptor.class)
|
||||
.withId(account.getId())
|
||||
.withName(account.getName())
|
||||
.withAttributes(account.getAttributes())
|
||||
.withWorkspaces(workspaces)
|
||||
.withLinks(links);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts {@link Member} to {@link MemberDescriptor}
|
||||
*/
|
||||
private MemberDescriptor toDescriptor(Member member, Account account, SecurityContext securityContext) {
|
||||
final UriBuilder uriBuilder = getServiceContext().getServiceUriBuilder();
|
||||
final Link removeMember = LinksHelper.createLink(HttpMethod.DELETE,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "removeMember")
|
||||
.build(account.getId(), member.getUserId())
|
||||
.toString(),
|
||||
null,
|
||||
null,
|
||||
Constants.LINK_REL_REMOVE_MEMBER);
|
||||
final Link allMembers = LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getMembers")
|
||||
.build(account.getId())
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_MEMBERS);
|
||||
final AccountReference accountRef = DtoFactory.getInstance().createDto(AccountReference.class)
|
||||
.withId(account.getId())
|
||||
.withName(account.getName());
|
||||
if (member.getRoles().contains("account/owner") ||
|
||||
securityContext.isUserInRole("system/admin") ||
|
||||
securityContext.isUserInRole("system/manager")) {
|
||||
accountRef.setLinks(singletonList(LinksHelper.createLink(HttpMethod.GET,
|
||||
uriBuilder.clone()
|
||||
.path(getClass(), "getById")
|
||||
.build(account.getId())
|
||||
.toString(),
|
||||
null,
|
||||
APPLICATION_JSON,
|
||||
Constants.LINK_REL_GET_ACCOUNT_BY_ID)));
|
||||
}
|
||||
return DtoFactory.getInstance().createDto(MemberDescriptor.class)
|
||||
.withUserId(member.getUserId())
|
||||
.withRoles(member.getRoles())
|
||||
.withAccountReference(accountRef)
|
||||
.withLinks(Arrays.asList(removeMember, allMembers));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks object reference is not {@code null}
|
||||
*
|
||||
* @param object
|
||||
* object reference to check
|
||||
* @param subject
|
||||
* used as subject of exception message "{subject} required"
|
||||
* @throws ConflictException
|
||||
* when object reference is {@code null}
|
||||
*/
|
||||
private void requiredNotNull(Object object, String subject) throws ConflictException {
|
||||
if (object == null) {
|
||||
throw new ConflictException(subject + " required");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,37 +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.account.server;
|
||||
|
||||
/**
|
||||
* Constants for Account API
|
||||
*
|
||||
* @author Eugene Voevodin
|
||||
* @author Alexander Garagatyi
|
||||
*/
|
||||
public final class Constants {
|
||||
|
||||
public static final String LINK_REL_CREATE_ACCOUNT = "create";
|
||||
public static final String LINK_REL_GET_ACCOUNT_BY_ID = "get by id";
|
||||
public static final String LINK_REL_GET_ACCOUNT_BY_NAME = "get by name";
|
||||
public static final String LINK_REL_UPDATE_ACCOUNT = "update";
|
||||
public static final String LINK_REL_REMOVE_ACCOUNT = "remove";
|
||||
public static final String LINK_REL_GET_MEMBERS = "members";
|
||||
public static final String LINK_REL_ADD_MEMBER = "add member";
|
||||
public static final String LINK_REL_REMOVE_MEMBER = "remove member";
|
||||
public static final String LINK_REL_GET_ACCOUNTS = "get accounts";
|
||||
public static final String LINK_REL_ADD_ATTRIBUTE = "add attribute";
|
||||
public static final String LINK_REL_REMOVE_ATTRIBUTE = "remove attribute";
|
||||
public static final int ID_LENGTH = 16;
|
||||
public static final String RESOURCES_LOCKED_PROPERTY = "codenvy:resources_locked";
|
||||
public static final String PAYMENT_LOCKED_PROPERTY = "codenvy:payment_locked";
|
||||
|
||||
private Constants() {}
|
||||
}
|
||||
|
|
@ -1,130 +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.account.server.dao;
|
||||
|
||||
import org.eclipse.che.api.core.model.workspace.Workspace;
|
||||
import org.eclipse.che.commons.annotation.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
/**
|
||||
* Defines account data object.
|
||||
*
|
||||
* @author Yevhenii Voevodin
|
||||
*/
|
||||
public class Account {
|
||||
|
||||
private final String id;
|
||||
|
||||
private String name;
|
||||
private List<Workspace> workspaces;
|
||||
private Map<String, String> attributes;
|
||||
|
||||
public Account(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Account(Account account) {
|
||||
this(account.id,
|
||||
account.name,
|
||||
account.workspaces,
|
||||
account.attributes);
|
||||
}
|
||||
|
||||
public Account(String id, String name) {
|
||||
this(id, name, null, null);
|
||||
}
|
||||
|
||||
public Account(String id,
|
||||
String name,
|
||||
@Nullable List<Workspace> workspaces,
|
||||
@Nullable Map<String, String> attributes) {
|
||||
this(id);
|
||||
this.name = requireNonNull(name, "Required non-null account name");
|
||||
this.workspaces = workspaces;
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Workspace> getWorkspaces() {
|
||||
if (workspaces == null) {
|
||||
workspaces = new ArrayList<>();
|
||||
}
|
||||
return workspaces;
|
||||
}
|
||||
|
||||
public void setWorkspaces(@Nullable List<Workspace> workspaces) {
|
||||
this.workspaces = workspaces;
|
||||
}
|
||||
|
||||
public Map<String, String> getAttributes() {
|
||||
if (attributes == null) {
|
||||
attributes = new HashMap<>();
|
||||
}
|
||||
return attributes;
|
||||
}
|
||||
|
||||
public void setAttributes(@Nullable Map<String, String> attributes) {
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof Account)) {
|
||||
return false;
|
||||
}
|
||||
final Account other = (Account)obj;
|
||||
return Objects.equals(id, other.id)
|
||||
&& Objects.equals(name, other.name)
|
||||
&& getAttributes().equals(other.getAttributes())
|
||||
&& getWorkspaces().equals(other.getWorkspaces());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 31 * hash + Objects.hashCode(id);
|
||||
hash = 31 * hash + Objects.hashCode(name);
|
||||
hash = 31 * hash + getAttributes().hashCode();
|
||||
hash = 31 * hash + getWorkspaces().hashCode();
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Account{" +
|
||||
"id='" + id + '\'' +
|
||||
", name='" + name + '\'' +
|
||||
", workspaces=" + workspaces +
|
||||
", attributes=" + attributes +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
|
@ -1,203 +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.account.server.dao;
|
||||
|
||||
import org.eclipse.che.api.core.ConflictException;
|
||||
import org.eclipse.che.api.core.NotFoundException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
import org.eclipse.che.api.core.model.workspace.Workspace;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
/**
|
||||
* DAO interface offers means to perform CRUD operations with {@link Account} data.
|
||||
* The implementation is not required
|
||||
* to be responsible for persistent layer data dto consistency. It simply transfers data from one layer to another,
|
||||
* so
|
||||
* if you're going to call any of implemented methods it is considered that all needed verifications are already done.
|
||||
* <p> <strong>Note:</strong> This particularly does not mean that method call will not make any inconsistency but this
|
||||
* mean that such kind of inconsistencies are expected by design and may be treated further. </p>
|
||||
*
|
||||
* @author Eugene Voevodin
|
||||
* @author Alexander Garagatyi
|
||||
*/
|
||||
public interface AccountDao {
|
||||
|
||||
/**
|
||||
* Adds new account to persistent layer
|
||||
*
|
||||
* @param account
|
||||
* POJO representation of account
|
||||
*/
|
||||
void create(Account account) throws ConflictException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets account from persistent layer by it identifier
|
||||
*
|
||||
* @param id
|
||||
* account identifier
|
||||
* @return account POJO
|
||||
* @throws org.eclipse.che.api.core.NotFoundException
|
||||
* when account doesn't exist
|
||||
*/
|
||||
Account getById(String id) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets user from persistent layer it name
|
||||
*
|
||||
* @param name
|
||||
* account name
|
||||
* @return account POJO
|
||||
* @throws org.eclipse.che.api.core.NotFoundException
|
||||
* when account doesn't exist
|
||||
*/
|
||||
Account getByName(String name) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets account from persistent level by owner
|
||||
*
|
||||
* @param owner
|
||||
* owner id
|
||||
* @return account POJO, or empty list if nothing is found
|
||||
*/
|
||||
List<Account> getByOwner(String owner) throws ServerException, NotFoundException;
|
||||
|
||||
/**
|
||||
* Updates already present in persistent level account
|
||||
*
|
||||
* @param account
|
||||
* account POJO to update
|
||||
*/
|
||||
void update(Account account) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Removes account from persistent layer
|
||||
*
|
||||
* @param id
|
||||
* account identifier
|
||||
*/
|
||||
void remove(String id) throws NotFoundException, ServerException, ConflictException;
|
||||
|
||||
/**
|
||||
* Adds new member to already present in persistent level account
|
||||
*
|
||||
* @param member
|
||||
* new member
|
||||
*/
|
||||
void addMember(Member member) throws NotFoundException, ConflictException, ServerException;
|
||||
|
||||
/**
|
||||
* Removes member from existing account
|
||||
*
|
||||
* @param member
|
||||
* account member to be removed
|
||||
*/
|
||||
void removeMember(Member member) throws NotFoundException, ServerException, ConflictException;
|
||||
|
||||
/**
|
||||
* Gets list of existing in persistent layer members related to given account
|
||||
*
|
||||
* @param accountId
|
||||
* account id
|
||||
* @return list of members, or empty list if no members found
|
||||
*/
|
||||
List<Member> getMembers(String accountId) throws ServerException;
|
||||
|
||||
/**
|
||||
* Gets list of existing in persistent layer Account where given member is member
|
||||
*
|
||||
* @param userId
|
||||
* user identifier to search
|
||||
* @return list of accounts, or empty list if no accounts found
|
||||
*/
|
||||
List<Member> getByMember(String userId) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets account which contains {@link Workspace workspace} with given identifier.
|
||||
*
|
||||
* @param workspaceId
|
||||
* workspace identifier
|
||||
* @return account which contains specified workspace
|
||||
* @throws NotFoundException
|
||||
* when account which contains specified workspace doesn't exist
|
||||
* @throws ServerException
|
||||
* when any other error occurs
|
||||
*/
|
||||
Account getByWorkspace(String workspaceId) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Checks that workspace is already registered in the any account.
|
||||
*
|
||||
* @param workspaceId
|
||||
* workspace identifier
|
||||
* @return true if workspace is already registered in the any account, returns false otherwise
|
||||
* @throws ServerException
|
||||
* when any error occurs
|
||||
* @see #getByWorkspace(String)
|
||||
*/
|
||||
default boolean isWorkspaceRegistered(String workspaceId) throws ServerException {
|
||||
try {
|
||||
getByWorkspace(workspaceId);
|
||||
return true;
|
||||
} catch (NotFoundException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that account with given identifier exists.
|
||||
*
|
||||
* <p>This method covers the use-case where only account existence is important and
|
||||
* account object itself is not needed, this is similar to {@link #getById(String)} + {@code try catch} just
|
||||
* more convenient.
|
||||
*
|
||||
* <p>Example:
|
||||
* <pre>
|
||||
* boolean exists = false;
|
||||
* try {
|
||||
* accountDao.getById(id);
|
||||
* exists = true;
|
||||
* } catch (NotFoundException nfEx) {
|
||||
* exists = false;
|
||||
* }
|
||||
*
|
||||
* if (exists) {
|
||||
* // ..
|
||||
* }
|
||||
*
|
||||
* // VS
|
||||
*
|
||||
* if (accountDao.exists(id) {
|
||||
* // ..
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param accountId
|
||||
* identifier of the account which check
|
||||
* @return true if account exists or false if it does not
|
||||
* @throws NullPointerException
|
||||
* when {@code accountId} is null
|
||||
* @throws ServerException
|
||||
* when any other error occurs
|
||||
* @see #getById(String)
|
||||
*/
|
||||
default boolean exist(@NotNull String accountId) throws ServerException {
|
||||
try {
|
||||
getById(requireNonNull(accountId, "Required non-null account id"));
|
||||
return true;
|
||||
} catch (NotFoundException nfEx) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,54 +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.account.server.dao;
|
||||
|
||||
import org.eclipse.che.api.core.ConflictException;
|
||||
import org.eclipse.che.api.core.NotFoundException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Account - workspaces (one to many) association
|
||||
*
|
||||
* @author gazarenkov
|
||||
*/
|
||||
public interface AccountWorkspacesDao {
|
||||
|
||||
/**
|
||||
* Associates new workspace to account
|
||||
*/
|
||||
void create(String accountId, String workspaceId) throws ConflictException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets all workspaces associated with account
|
||||
*/
|
||||
List <String> getWorkspaces(String accountId) throws NotFoundException, ServerException;
|
||||
|
||||
/**
|
||||
* Gets account associated with workspace
|
||||
*/
|
||||
String getAccount(String workspaceId) throws NotFoundException, ServerException;
|
||||
|
||||
|
||||
/**
|
||||
* Removes workspace-account association
|
||||
*/
|
||||
void removeWorkspaceRef(String workspaceId) throws NotFoundException, ServerException, ConflictException;
|
||||
|
||||
/**
|
||||
* Removes account
|
||||
*/
|
||||
void removeAccount(String accountId) throws NotFoundException, ServerException, ConflictException;
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -1,90 +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.account.server.dao;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author Eugene Voevodin
|
||||
*/
|
||||
public class Member {
|
||||
|
||||
private String userId;
|
||||
private String accountId;
|
||||
private List<String> roles;
|
||||
|
||||
public String getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Member withUserId(String userId) {
|
||||
this.userId = userId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getAccountId() {
|
||||
return accountId;
|
||||
}
|
||||
|
||||
public void setAccountId(String accountId) {
|
||||
this.accountId = accountId;
|
||||
}
|
||||
|
||||
public Member withAccountId(String accountId) {
|
||||
this.accountId = accountId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
if (roles == null) {
|
||||
roles = new ArrayList<>();
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public Member withRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof Member)) {
|
||||
return false;
|
||||
}
|
||||
final Member other = (Member)obj;
|
||||
return Objects.equals(userId, other.userId) &&
|
||||
Objects.equals(accountId, other.accountId) &&
|
||||
Objects.equals(getRoles(), other.getRoles());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 31 * hash + Objects.hashCode(userId);
|
||||
hash = 31 * hash + Objects.hashCode(accountId);
|
||||
hash = 31 * hash + Objects.hashCode(getRoles());
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,57 +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.account.server.event;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountWorkspacesDao;
|
||||
import org.eclipse.che.api.core.notification.EventService;
|
||||
//import org.eclipse.che.api.core.notification.EventSubscriber;
|
||||
//import org.eclipse.che.api.workspace.server.event.AfterCreateWorkspaceEvent;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
/**
|
||||
* @author gazarenkov
|
||||
* TODO move to hosted
|
||||
*/
|
||||
@Singleton
|
||||
public class AfterCreateWorkspaceSubscriber {
|
||||
// private final EventService eventService;
|
||||
// private final EventSubscriber<AfterCreateWorkspaceEvent> subscriber;
|
||||
|
||||
// public AfterCreateWorkspaceSubscriber(final EventService eventService, final AccountWorkspacesDao workspacesDao) {
|
||||
// this.eventService = eventService;
|
||||
// subscriber = new EventSubscriber<AfterCreateWorkspaceEvent> () {
|
||||
// @Override
|
||||
// public void onEvent(AfterCreateWorkspaceEvent event) {
|
||||
// String accountId = event.getOptions().get("accountId");
|
||||
// if(accountId != null) {
|
||||
// try {
|
||||
// workspacesDao.create(event.getWorkspace().getId(), accountId);
|
||||
// } catch (Exception e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
//
|
||||
// @PostConstruct
|
||||
// public void subscribe() {
|
||||
// eventService.subscribe(subscriber);
|
||||
// }
|
||||
//
|
||||
// @PreDestroy
|
||||
// public void unsubscribe() {
|
||||
// eventService.unsubscribe(subscriber);
|
||||
// }
|
||||
}
|
||||
|
|
@ -1,73 +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.account.server.event;
|
||||
//
|
||||
//import org.eclipse.che.api.account.server.dao.Account;
|
||||
//import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
//import org.eclipse.che.api.account.server.dao.AccountWorkspacesDao;
|
||||
//import org.eclipse.che.api.core.ServerException;
|
||||
//import org.eclipse.che.api.core.notification.EventService;
|
||||
//import org.eclipse.che.api.core.notification.EventSubscriber;
|
||||
//import org.eclipse.che.api.user.server.dao.MembershipDao;
|
||||
//import org.eclipse.che.api.workspace.server.event.AfterCreateWorkspaceEvent;
|
||||
//
|
||||
//import javax.annotation.PostConstruct;
|
||||
//import javax.annotation.PreDestroy;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
/**
|
||||
* @author gazarenkov
|
||||
* @TODO move to hosted
|
||||
*/
|
||||
@Singleton
|
||||
public class BeforeCreateWorkspaceSubscriber {
|
||||
// private final EventService eventService;
|
||||
// private final EventSubscriber<AfterCreateWorkspaceEvent> subscriber;
|
||||
//
|
||||
// public BeforeCreateWorkspaceSubscriber(final EventService eventService, final AccountWorkspacesDao workspacesDao,
|
||||
// final AccountDao accountDao) {
|
||||
// this.eventService = eventService;
|
||||
// subscriber = new EventSubscriber<AfterCreateWorkspaceEvent> () {
|
||||
// @Override
|
||||
// public void onEvent(AfterCreateWorkspaceEvent event) {
|
||||
// String accountId = event.getOptions().get("accountId");
|
||||
// if(accountId != null) {
|
||||
//
|
||||
//
|
||||
//
|
||||
// // TODO throw Exception
|
||||
//
|
||||
// try {
|
||||
//
|
||||
// Account account = accountDao.getById(accountId);
|
||||
//
|
||||
// if (account.getAttributes().containsKey(org.eclipse.che.api.account.server.Constants.RESOURCES_LOCKED_PROPERTY)) {
|
||||
// event.getWorkspace().getAttributes().put(org.eclipse.che.api.account.server.Constants.RESOURCES_LOCKED_PROPERTY, "true");
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// }
|
||||
//
|
||||
// @PostConstruct
|
||||
// public void subscribe() {
|
||||
// eventService.subscribe(subscriber);
|
||||
// }
|
||||
//
|
||||
// @PreDestroy
|
||||
// public void unsubscribe() {
|
||||
// eventService.unsubscribe(subscriber);
|
||||
// }
|
||||
}
|
||||
|
|
@ -1,59 +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.account.shared.dto;
|
||||
|
||||
import org.eclipse.che.api.core.rest.shared.dto.Link;
|
||||
import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author andrew00x
|
||||
*/
|
||||
@DTO
|
||||
public interface AccountDescriptor {
|
||||
|
||||
@ApiModelProperty(value = "Account attributes")
|
||||
Map<String, String> getAttributes();
|
||||
|
||||
void setAttributes(Map<String, String> attributes);
|
||||
|
||||
AccountDescriptor withAttributes(Map<String, String> attributes);
|
||||
|
||||
@ApiModelProperty(value = "Account name")
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
AccountDescriptor withName(String name);
|
||||
|
||||
@ApiModelProperty(value = "Account ID")
|
||||
String getId();
|
||||
|
||||
void setId(String id);
|
||||
|
||||
AccountDescriptor withId(String id);
|
||||
|
||||
List<WorkspaceDto> getWorkspaces();
|
||||
|
||||
void setWorkspaces(List<WorkspaceDto> workspaces);
|
||||
|
||||
AccountDescriptor withWorkspaces(List<WorkspaceDto> workspaces);
|
||||
|
||||
List<Link> getLinks();
|
||||
|
||||
void setLinks(List<Link> links);
|
||||
|
||||
AccountDescriptor withLinks(List<Link> links);
|
||||
}
|
||||
|
|
@ -1,32 +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.account.shared.dto;
|
||||
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
|
||||
/**
|
||||
* @author Oleksii Orel
|
||||
*/
|
||||
@DTO
|
||||
public interface AccountLockDetails {
|
||||
String getAccountId();
|
||||
|
||||
void setAccountId(String accountId);
|
||||
|
||||
AccountLockDetails withAccountId(String accountId);
|
||||
|
||||
Boolean isLocked();
|
||||
|
||||
void setLocked(Boolean status);
|
||||
|
||||
AccountLockDetails withLocked(Boolean status);
|
||||
}
|
||||
|
|
@ -1,45 +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.account.shared.dto;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import org.eclipse.che.api.core.rest.shared.dto.Link;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Eugene Voevodin
|
||||
*/
|
||||
@DTO
|
||||
public interface AccountReference {
|
||||
|
||||
@ApiModelProperty(value = "Account name")
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
AccountReference withName(String name);
|
||||
|
||||
@ApiModelProperty(value = "Account ID")
|
||||
String getId();
|
||||
|
||||
void setId(String id);
|
||||
|
||||
AccountReference withId(String id);
|
||||
|
||||
List<Link> getLinks();
|
||||
|
||||
void setLinks(List<Link> links);
|
||||
|
||||
AccountReference withLinks(List<Link> links);
|
||||
}
|
||||
|
|
@ -1,36 +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.account.shared.dto;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author andrew00x
|
||||
*/
|
||||
@DTO
|
||||
public interface AccountUpdate {
|
||||
@ApiModelProperty(value = "Account name", required = true)
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
AccountUpdate withName(String name);
|
||||
|
||||
@ApiModelProperty("Account attributes are optional. They are used to store random info about an account")
|
||||
Map<String, String> getAttributes();
|
||||
|
||||
void setAttributes(Map<String, String> attributes);
|
||||
|
||||
AccountUpdate withAttributes(Map<String, String> attributes);
|
||||
}
|
||||
|
|
@ -1,49 +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.account.shared.dto;
|
||||
|
||||
import org.eclipse.che.api.core.rest.shared.dto.Link;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author andrew00x
|
||||
*/
|
||||
@DTO
|
||||
public interface MemberDescriptor {
|
||||
@ApiModelProperty(value = "User roles", allowableValues = "account/owner,account/member")
|
||||
List<String> getRoles();
|
||||
|
||||
void setRoles(List<String> roles);
|
||||
|
||||
MemberDescriptor withRoles(List<String> roles);
|
||||
|
||||
@ApiModelProperty(value = "User ID")
|
||||
String getUserId();
|
||||
|
||||
void setUserId(String id);
|
||||
|
||||
MemberDescriptor withUserId(String id);
|
||||
|
||||
AccountReference getAccountReference();
|
||||
|
||||
void setAccountReference(AccountReference accountReference);
|
||||
|
||||
MemberDescriptor withAccountReference(AccountReference accountReference);
|
||||
|
||||
List<Link> getLinks();
|
||||
|
||||
void setLinks(List<Link> links);
|
||||
|
||||
MemberDescriptor withLinks(List<Link> links);
|
||||
}
|
||||
|
|
@ -1,32 +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.account.shared.dto;
|
||||
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
/**
|
||||
* @author Sergii Kabashniuk
|
||||
*/
|
||||
@DTO
|
||||
public interface MemoryChargeDetails {
|
||||
String getWorkspaceId();
|
||||
|
||||
void setWorkspaceId(String workspaceId);
|
||||
|
||||
MemoryChargeDetails withWorkspaceId(String workspaceId);
|
||||
|
||||
Double getAmount();
|
||||
|
||||
void setAmount(Double amount);
|
||||
|
||||
MemoryChargeDetails withAmount(Double amount);
|
||||
|
||||
}
|
||||
|
|
@ -1,38 +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.account.shared.dto;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author andrew00x
|
||||
*/
|
||||
@DTO
|
||||
public interface NewAccount {
|
||||
|
||||
@ApiModelProperty("Account attributes are optional. They are used to store random information " +
|
||||
"about an account. Pass an empty object or any key:value pair")
|
||||
Map<String, String> getAttributes();
|
||||
|
||||
void setAttributes(Map<String, String> attributes);
|
||||
|
||||
NewAccount withAttributes(Map<String, String> attributes);
|
||||
|
||||
@ApiModelProperty(value = "Account name", required = true)
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
NewAccount withName(String name);
|
||||
}
|
||||
|
|
@ -1,39 +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.account.shared.dto;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Describes new account membership
|
||||
*
|
||||
* @author Eugene Voevodin
|
||||
*/
|
||||
@DTO
|
||||
public interface NewMembership {
|
||||
|
||||
@ApiModelProperty(value = "User ID to be added to an account", required = true)
|
||||
String getUserId();
|
||||
|
||||
void setUserId(String id);
|
||||
|
||||
NewMembership withUserId(String id);
|
||||
|
||||
@ApiModelProperty(value = "User roles in the account", required = true, allowableValues = "account/owner, account/member")
|
||||
List<String> getRoles();
|
||||
|
||||
void setRoles(List<String> roles);
|
||||
|
||||
NewMembership withRoles(List<String> roles);
|
||||
}
|
||||
|
|
@ -1,32 +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.account.shared.dto;
|
||||
|
||||
import org.eclipse.che.dto.shared.DTO;
|
||||
|
||||
|
||||
/**
|
||||
* @author Ann Shumilova
|
||||
*/
|
||||
@DTO
|
||||
public interface WorkspaceLockDetails {
|
||||
String getWorkspaceId();
|
||||
|
||||
void setWorkspaceId(String accountId);
|
||||
|
||||
WorkspaceLockDetails withWorkspaceId(String workspaceId);
|
||||
|
||||
Boolean isLocked();
|
||||
|
||||
void setLocked(Boolean isLocked);
|
||||
|
||||
WorkspaceLockDetails withLocked(Boolean isLocked);
|
||||
}
|
||||
|
|
@ -1,612 +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.account;
|
||||
|
||||
import org.eclipse.che.api.account.server.AccountService;
|
||||
import org.eclipse.che.api.account.server.Constants;
|
||||
import org.eclipse.che.api.account.server.dao.Account;
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.account.shared.dto.AccountDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.AccountUpdate;
|
||||
import org.eclipse.che.api.account.shared.dto.MemberDescriptor;
|
||||
import org.eclipse.che.api.account.shared.dto.NewMembership;
|
||||
import org.eclipse.che.api.core.NotFoundException;
|
||||
import org.eclipse.che.api.core.rest.Service;
|
||||
import org.eclipse.che.api.core.rest.shared.dto.Link;
|
||||
import org.eclipse.che.api.machine.server.model.impl.MachineConfigImpl;
|
||||
import org.eclipse.che.api.machine.server.model.impl.MachineSourceImpl;
|
||||
import org.eclipse.che.api.machine.server.recipe.RecipeImpl;
|
||||
import org.eclipse.che.api.user.server.dao.User;
|
||||
import org.eclipse.che.api.user.server.dao.UserDao;
|
||||
import org.eclipse.che.api.workspace.server.WorkspaceManager;
|
||||
import org.eclipse.che.api.workspace.server.model.impl.EnvironmentImpl;
|
||||
import org.eclipse.che.api.workspace.server.model.impl.WorkspaceImpl;
|
||||
import org.eclipse.che.api.workspace.server.model.impl.WorkspaceConfigImpl;
|
||||
import org.eclipse.che.commons.json.JsonHelper;
|
||||
import org.eclipse.che.dto.server.DtoFactory;
|
||||
import org.everrest.core.impl.ApplicationContextImpl;
|
||||
import org.everrest.core.impl.ApplicationProviderBinder;
|
||||
import org.everrest.core.impl.ContainerResponse;
|
||||
import org.everrest.core.impl.EnvironmentContext;
|
||||
import org.everrest.core.impl.EverrestConfiguration;
|
||||
import org.everrest.core.impl.EverrestProcessor;
|
||||
import org.everrest.core.impl.ProviderBinder;
|
||||
import org.everrest.core.impl.ResourceBinderImpl;
|
||||
import org.everrest.core.tools.DependencySupplierImpl;
|
||||
import org.everrest.core.tools.ResourceLauncher;
|
||||
import org.everrest.core.tools.SimplePrincipal;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.testng.MockitoTestNGListener;
|
||||
import org.testng.annotations.AfterMethod;
|
||||
import org.testng.annotations.BeforeMethod;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Listeners;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.HttpMethod;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static javax.ws.rs.HttpMethod.DELETE;
|
||||
import static javax.ws.rs.HttpMethod.POST;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertNotEquals;
|
||||
import static org.testng.Assert.assertNull;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
import static org.testng.Assert.fail;
|
||||
|
||||
/**
|
||||
* Tests for Account Service
|
||||
*
|
||||
* @author Eugene Voevodin
|
||||
* @author Alexander Garagatyi
|
||||
* @see org.eclipse.che.api.account.server.AccountService
|
||||
*/
|
||||
@Listeners(value = {MockitoTestNGListener.class})
|
||||
public class AccountServiceTest {
|
||||
|
||||
private final String BASE_URI = "http://localhost/service";
|
||||
private final String SERVICE_PATH = BASE_URI + "/account";
|
||||
private final String USER_ID = "user123abc456def";
|
||||
private final String ACCOUNT_ID = "account0xffffffffff";
|
||||
private final String ACCOUNT_NAME = "codenvy";
|
||||
private final String USER_NAME = "account";
|
||||
private final User user = new User().withId(USER_ID).withName(USER_NAME);
|
||||
|
||||
@Mock
|
||||
private AccountDao accountDao;
|
||||
|
||||
@Mock
|
||||
private UserDao userDao;
|
||||
|
||||
@Mock
|
||||
private WorkspaceManager workspaceManager;
|
||||
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
|
||||
@Mock
|
||||
private EnvironmentContext environmentContext;
|
||||
|
||||
private Account account;
|
||||
private ArrayList<Member> memberships;
|
||||
|
||||
protected ProviderBinder providers;
|
||||
protected ResourceBinderImpl resources;
|
||||
protected ResourceLauncher launcher;
|
||||
|
||||
@BeforeMethod
|
||||
public void setUp() throws Exception {
|
||||
resources = new ResourceBinderImpl();
|
||||
providers = new ApplicationProviderBinder();
|
||||
DependencySupplierImpl dependencies = new DependencySupplierImpl();
|
||||
dependencies.addComponent(UserDao.class, userDao);
|
||||
dependencies.addComponent(AccountDao.class, accountDao);
|
||||
dependencies.addComponent(WorkspaceManager.class, workspaceManager);
|
||||
resources.addResource(AccountService.class, null);
|
||||
EverrestProcessor processor = new EverrestProcessor(resources, providers, dependencies, new EverrestConfiguration(), null);
|
||||
launcher = new ResourceLauncher(processor);
|
||||
ApplicationContextImpl.setCurrent(new ApplicationContextImpl(null, null, ProviderBinder.getInstance()));
|
||||
Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("secret", "bit secret");
|
||||
account = new Account(ACCOUNT_ID, ACCOUNT_NAME, null, attributes);
|
||||
|
||||
memberships = new ArrayList<>(1);
|
||||
Member ownerMembership = new Member();
|
||||
ownerMembership.setAccountId(account.getId());
|
||||
ownerMembership.setUserId(USER_ID);
|
||||
ownerMembership.setRoles(Arrays.asList("account/owner"));
|
||||
memberships.add(ownerMembership);
|
||||
|
||||
when(environmentContext.get(SecurityContext.class)).thenReturn(securityContext);
|
||||
when(securityContext.getUserPrincipal()).thenReturn(new SimplePrincipal(USER_NAME));
|
||||
|
||||
org.eclipse.che.commons.env.EnvironmentContext.getCurrent().setUser(new org.eclipse.che.commons.user.User() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return user.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMemberOf(String role) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(String domain, String instance, String action) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return "token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return user.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTemporary() {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@AfterMethod
|
||||
public void tearDown() throws Exception {
|
||||
org.eclipse.che.commons.env.EnvironmentContext.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToCreateAccount() throws Exception {
|
||||
when(userDao.getByName(USER_NAME)).thenReturn(user);
|
||||
when(accountDao.getByName(account.getName())).thenThrow(new NotFoundException("Account not found"));
|
||||
when(accountDao.getByOwner(USER_ID)).thenReturn(Collections.<Account>emptyList());
|
||||
String role = "user";
|
||||
prepareSecurityContext(role);
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH, MediaType.APPLICATION_JSON, account);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
|
||||
AccountDescriptor created = (AccountDescriptor)response.getEntity();
|
||||
verifyLinksRel(created.getLinks(), generateRels(role));
|
||||
verify(accountDao).create(any(Account.class));
|
||||
Member expected = new Member().withAccountId(created.getId())
|
||||
.withUserId(USER_ID)
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
verify(accountDao).addMember(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotBeAbleToCreateAccountWithNotValidAttributes() throws Exception {
|
||||
account.getAttributes().put("codenvy:god_mode", "true");
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH, MediaType.APPLICATION_JSON, account);
|
||||
assertEquals(response.getEntity().toString(), "Attribute name 'codenvy:god_mode' is not valid");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotBeAbleToCreateAccountIfUserAlreadyHasOne() throws Exception {
|
||||
prepareSecurityContext("user");
|
||||
when(userDao.getByName(USER_NAME)).thenReturn(user);
|
||||
when(accountDao.getByOwner(USER_ID)).thenReturn(Arrays.asList(account));
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH, MediaType.APPLICATION_JSON, account);
|
||||
assertEquals(response.getEntity().toString(), "Account which owner is " + USER_ID + " already exists");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToGetMemberships() throws Exception {
|
||||
when(userDao.getByName(USER_NAME)).thenReturn(user);
|
||||
when(accountDao.getByMember(USER_ID)).thenReturn(memberships);
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.GET, SERVICE_PATH, null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
@SuppressWarnings("unchecked") List<MemberDescriptor> currentAccounts = (List<MemberDescriptor>)response.getEntity();
|
||||
assertEquals(currentAccounts.size(), 1);
|
||||
assertEquals(currentAccounts.get(0).getRoles().get(0), "account/owner");
|
||||
verify(accountDao).getByMember(USER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToGetMembershipsOfSpecificUser() throws Exception {
|
||||
when(accountDao.getById("fake_id")).thenReturn(new Account("fake_id", "fake_name"));
|
||||
User user = new User().withId("ANOTHER_USER_ID").withEmail("ANOTHER_USER_EMAIL");
|
||||
ArrayList<Member> memberships = new ArrayList<>(1);
|
||||
Member am = new Member().withAccountId("fake_id")
|
||||
.withUserId("ANOTHER_USER_ID")
|
||||
.withRoles(Arrays.asList("account/member"));
|
||||
memberships.add(am);
|
||||
when(userDao.getById("ANOTHER_USER_ID")).thenReturn(user);
|
||||
when(accountDao.getByMember("ANOTHER_USER_ID")).thenReturn(memberships);
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.GET, SERVICE_PATH + "/memberships?userid=" + "ANOTHER_USER_ID", null, null);
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
@SuppressWarnings("unchecked") List<MemberDescriptor> currentAccounts = (List<MemberDescriptor>)response.getEntity();
|
||||
assertEquals(currentAccounts.size(), 1);
|
||||
assertEquals(currentAccounts.get(0).getAccountReference().getId(), am.getAccountId());
|
||||
assertEquals(currentAccounts.get(0).getAccountReference().getName(), "fake_name");
|
||||
assertEquals(currentAccounts.get(0).getRoles(), am.getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToGetAccountById() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
String[] roles = getRoles(AccountService.class, "getById");
|
||||
|
||||
for (String role : roles) {
|
||||
prepareSecurityContext(role);
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.GET, SERVICE_PATH + "/" + ACCOUNT_ID, null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
AccountDescriptor actual = (AccountDescriptor)response.getEntity();
|
||||
verifyLinksRel(actual.getLinks(), generateRels(role));
|
||||
}
|
||||
verify(accountDao, times(roles.length)).getById(ACCOUNT_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToUpdateAccount() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
AccountUpdate toUpdate = DtoFactory.getInstance().createDto(AccountUpdate.class)
|
||||
.withName("newName")
|
||||
.withAttributes(Collections.singletonMap("newAttribute", "someValue"));
|
||||
prepareSecurityContext("account/owner");
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + "/" + ACCOUNT_ID, MediaType.APPLICATION_JSON, toUpdate);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
AccountDescriptor actual = (AccountDescriptor)response.getEntity();
|
||||
assertEquals(actual.getAttributes().size(), 2);
|
||||
assertEquals(actual.getName(), "newName");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToRewriteAttributesWhenUpdatingAccount() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("newAttribute", "someValue");
|
||||
attributes.put("oldAttribute", "oldValue");
|
||||
account.setAttributes(attributes);
|
||||
|
||||
Map<String, String> updates = new HashMap<>();
|
||||
updates.put("newAttribute", "OTHER_VALUE");
|
||||
updates.put("newAttribute2", "someValue2");
|
||||
AccountDescriptor toUpdate = DtoFactory.getInstance().createDto(AccountDescriptor.class).withAttributes(updates);
|
||||
|
||||
prepareSecurityContext("account/owner");
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + "/" + ACCOUNT_ID, MediaType.APPLICATION_JSON, toUpdate);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
AccountDescriptor actual = (AccountDescriptor)response.getEntity();
|
||||
assertEquals(actual.getName(), ACCOUNT_NAME);
|
||||
assertEquals(actual.getAttributes().size(), 3);
|
||||
assertEquals(actual.getAttributes().get("newAttribute"), "OTHER_VALUE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToRemoveAttribute() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
Map<String, String> attributes = new HashMap<>(1);
|
||||
attributes.put("test", "test");
|
||||
account.setAttributes(attributes);
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.DELETE, SERVICE_PATH + "/" + ACCOUNT_ID + "/attribute?name=test", null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
|
||||
assertNull(attributes.get("test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotBeAbleToUpdateAccountWithAlreadyExistedName() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
when(accountDao.getByName("TO_UPDATE")).thenReturn(new Account("id", "TO_UPDATE"));
|
||||
AccountDescriptor toUpdate = DtoFactory.getInstance().createDto(AccountDescriptor.class).withName("TO_UPDATE");
|
||||
prepareSecurityContext("account/owner");
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + "/" + ACCOUNT_ID, MediaType.APPLICATION_JSON, toUpdate);
|
||||
assertNotEquals(response.getStatus(), Response.Status.OK);
|
||||
assertEquals(response.getEntity().toString(), "Account with name TO_UPDATE already exists");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToGetAccountByName() throws Exception {
|
||||
when(accountDao.getByName(ACCOUNT_NAME)).thenReturn(account);
|
||||
String[] roles = getRoles(AccountService.class, "getByName");
|
||||
for (String role : roles) {
|
||||
prepareSecurityContext(role);
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.GET, SERVICE_PATH + "/find?name=" + ACCOUNT_NAME, null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
AccountDescriptor actual = (AccountDescriptor)response.getEntity();
|
||||
verifyLinksRel(actual.getLinks(), generateRels(role));
|
||||
}
|
||||
verify(accountDao, times(roles.length)).getByName(ACCOUNT_NAME);
|
||||
}
|
||||
|
||||
@DataProvider(name = "roleProvider")
|
||||
public Object[][] roleProvider() {
|
||||
return new String[][] {
|
||||
{"system/admin"},
|
||||
{"system/manager"},
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToGetAccountMembers() throws Exception {
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
when(accountDao.getMembers(account.getId()))
|
||||
.thenReturn(Arrays.asList(new Member().withRoles(Collections.<String>emptyList())
|
||||
.withUserId(USER_ID)
|
||||
.withAccountId(account.getId())));
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.GET, SERVICE_PATH + "/" + account.getId() + "/members", null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
verify(accountDao).getMembers(account.getId());
|
||||
@SuppressWarnings("unchecked") List<MemberDescriptor> members = (List<MemberDescriptor>)response.getEntity();
|
||||
assertEquals(members.size(), 1);
|
||||
MemberDescriptor member = members.get(0);
|
||||
assertEquals(member.getLinks().size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToAddMember() throws Exception {
|
||||
when(accountDao.getById(ACCOUNT_ID)).thenReturn(account);
|
||||
final NewMembership newMembership = DtoFactory.getInstance().createDto(NewMembership.class)
|
||||
.withUserId(USER_ID)
|
||||
.withRoles(singletonList("account/member"));
|
||||
|
||||
final ContainerResponse response = makeRequest(POST,
|
||||
SERVICE_PATH + "/" + account.getId() + "/members",
|
||||
MediaType.APPLICATION_JSON,
|
||||
newMembership);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
|
||||
final MemberDescriptor descriptor = (MemberDescriptor)response.getEntity();
|
||||
assertEquals(descriptor.getUserId(), newMembership.getUserId());
|
||||
assertEquals(descriptor.getAccountReference().getId(), ACCOUNT_ID);
|
||||
assertEquals(descriptor.getRoles(), newMembership.getRoles());
|
||||
verify(accountDao).addMember(any(Member.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToRemoveMember() throws Exception {
|
||||
Member accountMember = new Member().withUserId(USER_ID)
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/member"));
|
||||
Member accountOwner = new Member().withUserId("owner_holder")
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
when(accountDao.getMembers(ACCOUNT_ID)).thenReturn(Arrays.asList(accountMember, accountOwner));
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.DELETE, SERVICE_PATH + "/" + ACCOUNT_ID + "/members/" + USER_ID, null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
|
||||
verify(accountDao).removeMember(accountMember);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldNotBeAbleToRemoveLastAccountOwner() throws Exception {
|
||||
Member accountOwner = new Member().withUserId(USER_ID)
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
Member accountMember = new Member().withUserId("member_holder")
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/member"));
|
||||
when(accountDao.getMembers(ACCOUNT_ID)).thenReturn(Arrays.asList(accountOwner, accountMember));
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.DELETE, SERVICE_PATH + "/" + ACCOUNT_ID + "/members/" + USER_ID, null, null);
|
||||
|
||||
assertEquals(response.getEntity().toString(), "Account should have at least 1 owner");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldBeAbleToRemoveAccountOwnerIfOtherOneExists() throws Exception {
|
||||
Member accountOwner = new Member().withUserId(USER_ID)
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
Member accountOwner2 = new Member().withUserId("owner_holder")
|
||||
.withAccountId(ACCOUNT_ID)
|
||||
.withRoles(Arrays.asList("account/owner"));
|
||||
when(accountDao.getMembers(ACCOUNT_ID)).thenReturn(Arrays.asList(accountOwner, accountOwner2));
|
||||
|
||||
ContainerResponse response = makeRequest(HttpMethod.DELETE, SERVICE_PATH + "/" + ACCOUNT_ID + "/members/" + USER_ID, null, null);
|
||||
|
||||
assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
|
||||
verify(accountDao).removeMember(accountOwner);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void workspaceShouldBeRegistered() throws Exception {
|
||||
WorkspaceImpl workspace = spy(createUsersWorkspace());
|
||||
Account account = new Account("account123");
|
||||
when(workspace.getId()).thenReturn("workspace123");
|
||||
when(workspaceManager.getWorkspace(any())).thenReturn(workspace);
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
when(accountDao.getByWorkspace(workspace.getId())).thenThrow(new NotFoundException(""));
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + '/' + account.getId() + '/' + workspace.getId(), null, null);
|
||||
|
||||
assertEquals(response.getStatus(), 200);
|
||||
AccountDescriptor descriptor = (AccountDescriptor)response.getEntity();
|
||||
assertEquals(descriptor.getWorkspaces().size(), 1);
|
||||
assertEquals(descriptor.getWorkspaces().get(0).getId(), workspace.getId());
|
||||
verify(accountDao).update(account);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFailWorkspaceRegistrationWhenWorkspaceIsAlreadyRegistered() throws Exception {
|
||||
WorkspaceImpl workspace = mock(WorkspaceImpl.class);
|
||||
Account account = new Account("account123");
|
||||
when(workspace.getId()).thenReturn("workspace123");
|
||||
when(workspaceManager.getWorkspace(any())).thenReturn(workspace);
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
when(accountDao.isWorkspaceRegistered(workspace.getId())).thenReturn(true);
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + '/' + account.getId() + '/' + workspace.getId(), null, null);
|
||||
|
||||
assertEquals(response.getEntity().toString(), "Workspace 'workspace123' already registered in another account");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFailWorkspaceRegistrationWhenAccountAlreadyContainsGivenWorkspace() throws Exception {
|
||||
WorkspaceImpl workspace = mock(WorkspaceImpl.class);
|
||||
Account account = new Account("account123");
|
||||
account.setWorkspaces(singletonList(workspace));
|
||||
when(workspace.getId()).thenReturn("workspace123");
|
||||
when(workspaceManager.getWorkspace(any())).thenReturn(workspace);
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
|
||||
ContainerResponse response = makeRequest(POST, SERVICE_PATH + '/' + account.getId() + '/' + workspace.getId(), null, null);
|
||||
|
||||
assertEquals(response.getEntity().toString(), "Workspace 'workspace123' is already registered in this account");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void workspaceShouldBeUnregistered() throws Exception {
|
||||
WorkspaceImpl workspace = mock(WorkspaceImpl.class);
|
||||
Account account = new Account("account123");
|
||||
account.setWorkspaces(new ArrayList<>(singletonList(workspace)));
|
||||
when(workspace.getId()).thenReturn("workspace123");
|
||||
when(workspaceManager.getWorkspace(any())).thenReturn(workspace);
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
|
||||
ContainerResponse response = makeRequest(DELETE, SERVICE_PATH + '/' + account.getId() + '/' + workspace.getId(), null, null);
|
||||
|
||||
assertEquals(response.getStatus(), 200);
|
||||
AccountDescriptor descriptor = (AccountDescriptor)response.getEntity();
|
||||
assertTrue(descriptor.getWorkspaces().isEmpty());
|
||||
verify(accountDao).update(account);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldFailWorkspaceUnRegistrationWhenWorkspaceIsNotRegistered() throws Exception {
|
||||
WorkspaceImpl workspace = mock(WorkspaceImpl.class);
|
||||
Account account = new Account("account123");
|
||||
when(workspace.getId()).thenReturn("workspace123");
|
||||
when(workspaceManager.getWorkspace(any())).thenReturn(workspace);
|
||||
when(accountDao.getById(account.getId())).thenReturn(account);
|
||||
|
||||
ContainerResponse response = makeRequest(DELETE, SERVICE_PATH + '/' + account.getId() + '/' + workspace.getId(), null, null);
|
||||
|
||||
assertEquals(response.getEntity().toString(), "Workspace 'workspace123' is not registered in account 'account123'");
|
||||
}
|
||||
|
||||
protected void verifyLinksRel(List<Link> links, List<String> rels) {
|
||||
assertEquals(links.size(), rels.size());
|
||||
for (String rel : rels) {
|
||||
boolean linkPresent = false;
|
||||
int i = 0;
|
||||
for (; i < links.size() && !linkPresent; i++) {
|
||||
linkPresent = links.get(i).getRel().equals(rel);
|
||||
}
|
||||
if (!linkPresent) {
|
||||
fail(String.format("Given links do not contain link with rel = %s", rel));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String[] getRoles(Class<? extends Service> clazz, String methodName) {
|
||||
for (Method one : clazz.getMethods()) {
|
||||
if (one.getName().equals(methodName)) {
|
||||
if (one.isAnnotationPresent(RolesAllowed.class)) {
|
||||
return one.getAnnotation(RolesAllowed.class).value();
|
||||
} else {
|
||||
return new String[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException(String.format("Class %s does not have method with name %s", clazz.getName(), methodName));
|
||||
}
|
||||
|
||||
private List<String> generateRels(String role) {
|
||||
final List<String> rels = new LinkedList<>();
|
||||
rels.add(Constants.LINK_REL_GET_MEMBERS);
|
||||
rels.add(Constants.LINK_REL_GET_ACCOUNTS);
|
||||
rels.add(Constants.LINK_REL_GET_ACCOUNT_BY_ID);
|
||||
switch (role) {
|
||||
case "system/admin":
|
||||
rels.add(Constants.LINK_REL_REMOVE_ACCOUNT);
|
||||
case "system/manager":
|
||||
rels.add(Constants.LINK_REL_GET_ACCOUNT_BY_NAME);
|
||||
break;
|
||||
}
|
||||
return rels;
|
||||
}
|
||||
|
||||
protected ContainerResponse makeRequest(String method, String path, String contentType, Object toSend) throws Exception {
|
||||
Map<String, List<String>> headers = null;
|
||||
if (contentType != null) {
|
||||
headers = new HashMap<>();
|
||||
headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(contentType));
|
||||
}
|
||||
byte[] data = null;
|
||||
if (toSend != null) {
|
||||
data = JsonHelper.toJson(toSend).getBytes();
|
||||
}
|
||||
return launcher.service(method, path, BASE_URI, headers, data, null, environmentContext);
|
||||
}
|
||||
|
||||
protected void prepareSecurityContext(String role) {
|
||||
when(securityContext.isUserInRole(anyString())).thenReturn(false);
|
||||
if (!role.equals("system/admin") && !role.equals("system/manager")) {
|
||||
when(securityContext.isUserInRole("user")).thenReturn(true);
|
||||
}
|
||||
when(securityContext.isUserInRole(role)).thenReturn(true);
|
||||
}
|
||||
|
||||
private WorkspaceImpl createUsersWorkspace() {
|
||||
final EnvironmentImpl environment = new EnvironmentImpl("name",
|
||||
new RecipeImpl(),
|
||||
singletonList(new MachineConfigImpl(true,
|
||||
"name",
|
||||
"type",
|
||||
new MachineSourceImpl("type",
|
||||
"location"),
|
||||
null,
|
||||
null,
|
||||
null)));
|
||||
return new WorkspaceImpl("id123", "owner1234", new WorkspaceConfigImpl("name",
|
||||
"desc",
|
||||
"defEnv",
|
||||
null,
|
||||
null,
|
||||
singletonList(environment)));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
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
|
||||
|
||||
-->
|
||||
<configuration>
|
||||
|
||||
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%-41(%date[%.15thread]) %-45([%-5level] [%.30logger{30} %L]) - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="file" class="ch.qos.logback.core.FileAppender">
|
||||
<File>target/log/codenvy-factory-commons.log</File>
|
||||
<encoder>
|
||||
<pattern>%-41(%date[%.15thread]) %-45([%-5level] [%.30logger{30} %L]) - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="stdout"/>
|
||||
<appender-ref ref="file"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
|
|
@ -23,7 +23,6 @@
|
|||
<packaging>pom</packaging>
|
||||
<name>Che Core :: API :: Parent</name>
|
||||
<modules>
|
||||
<module>che-core-api-account</module>
|
||||
<module>che-core-api-auth</module>
|
||||
</modules>
|
||||
<properties>
|
||||
|
|
|
|||
10
pom.xml
10
pom.xml
|
|
@ -75,11 +75,6 @@
|
|||
<version>${project.version}</version>
|
||||
<type>war</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-auth</artifactId>
|
||||
|
|
@ -196,11 +191,6 @@
|
|||
<artifactId>che-core-api-workspace-shared</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-account</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-client-gwt-auth</artifactId>
|
||||
|
|
|
|||
|
|
@ -42,17 +42,6 @@ public interface Author {
|
|||
|
||||
Author withEmail(String email);
|
||||
|
||||
/**
|
||||
* Identifier for the tracked factory features.
|
||||
* Replaces orgid.
|
||||
*/
|
||||
@FactoryParameter(obligation = OPTIONAL)
|
||||
String getAccountId();
|
||||
|
||||
void setAccountId(String accountId);
|
||||
|
||||
Author withAccountId(String accountId);
|
||||
|
||||
/**
|
||||
* Id of user that create factory, set by the server
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -53,10 +53,6 @@
|
|||
<groupId>javax.inject</groupId>
|
||||
<artifactId>javax.inject</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-account</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.che.core</groupId>
|
||||
<artifactId>che-core-api-core</artifactId>
|
||||
|
|
|
|||
|
|
@ -10,9 +10,7 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.core.BadRequestException;
|
||||
import org.eclipse.che.api.core.ConflictException;
|
||||
import org.eclipse.che.api.factory.server.FactoryAcceptValidator;
|
||||
import org.eclipse.che.api.factory.shared.dto.Factory;
|
||||
import org.eclipse.che.api.user.server.dao.PreferenceDao;
|
||||
|
|
@ -26,9 +24,8 @@ import javax.inject.Singleton;
|
|||
@Singleton
|
||||
public class FactoryAcceptValidatorImpl extends FactoryBaseValidator implements FactoryAcceptValidator {
|
||||
@Inject
|
||||
public FactoryAcceptValidatorImpl(AccountDao accountDao,
|
||||
PreferenceDao preferenceDao) {
|
||||
super(accountDao, preferenceDao);
|
||||
public FactoryAcceptValidatorImpl(PreferenceDao preferenceDao) {
|
||||
super(preferenceDao);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -10,8 +10,6 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.core.BadRequestException;
|
||||
import org.eclipse.che.api.core.ForbiddenException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
|
|
@ -47,12 +45,9 @@ import static java.lang.System.currentTimeMillis;
|
|||
public abstract class FactoryBaseValidator {
|
||||
private static final Pattern PROJECT_NAME_VALIDATOR = Pattern.compile("^[\\\\\\w\\\\\\d]+[\\\\\\w\\\\\\d_.-]*$");
|
||||
|
||||
private final AccountDao accountDao;
|
||||
private final PreferenceDao preferenceDao;
|
||||
|
||||
public FactoryBaseValidator(AccountDao accountDao,
|
||||
PreferenceDao preferenceDao) {
|
||||
this.accountDao = accountDao;
|
||||
public FactoryBaseValidator(PreferenceDao preferenceDao) {
|
||||
this.preferenceDao = preferenceDao;
|
||||
}
|
||||
|
||||
|
|
@ -107,10 +102,9 @@ public abstract class FactoryBaseValidator {
|
|||
*/
|
||||
protected void validateAccountId(Factory factory) throws ServerException, ForbiddenException {
|
||||
// TODO do we need check if user is temporary?
|
||||
final String accountId = factory.getCreator() != null ? emptyToNull(factory.getCreator().getAccountId()) : null;
|
||||
final String userId = factory.getCreator() != null ? factory.getCreator().getUserId() : null;
|
||||
|
||||
if (accountId == null || userId == null) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -119,16 +113,6 @@ public abstract class FactoryBaseValidator {
|
|||
throw new ForbiddenException("Current user is not allowed to use this method.");
|
||||
}
|
||||
|
||||
final List<Member> members = accountDao.getMembers(accountId);
|
||||
if (members.isEmpty()) {
|
||||
throw new ForbiddenException(format(FactoryConstants.PARAMETRIZED_ILLEGAL_ACCOUNTID_PARAMETER_MESSAGE, accountId));
|
||||
}
|
||||
|
||||
if (members.stream().noneMatch(member -> member.getUserId()
|
||||
.equals(userId) && member.getRoles()
|
||||
.contains("account/owner"))) {
|
||||
throw new ForbiddenException("You are not authorized to use this accountId.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.core.BadRequestException;
|
||||
import org.eclipse.che.api.core.ForbiddenException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
|
|
@ -30,10 +29,9 @@ public class FactoryCreateValidatorImpl extends FactoryBaseValidator implements
|
|||
private WorkspaceValidator workspaceConfigValidator;
|
||||
|
||||
@Inject
|
||||
public FactoryCreateValidatorImpl(AccountDao accountDao,
|
||||
PreferenceDao preferenceDao,
|
||||
public FactoryCreateValidatorImpl(PreferenceDao preferenceDao,
|
||||
WorkspaceValidator workspaceConfigValidator) {
|
||||
super(accountDao, preferenceDao);
|
||||
super(preferenceDao);
|
||||
this.workspaceConfigValidator = workspaceConfigValidator;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,8 +10,6 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.core.ForbiddenException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
import org.eclipse.che.api.factory.server.FactoryEditValidator;
|
||||
|
|
@ -19,9 +17,7 @@ import org.eclipse.che.api.factory.shared.dto.Author;
|
|||
import org.eclipse.che.api.factory.shared.dto.Factory;
|
||||
import org.eclipse.che.commons.env.EnvironmentContext;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
|
|
@ -33,12 +29,6 @@ import static java.lang.String.format;
|
|||
@Singleton
|
||||
public class FactoryEditValidatorImpl implements FactoryEditValidator {
|
||||
|
||||
/**
|
||||
* Account DAO.
|
||||
*/
|
||||
@Inject
|
||||
private AccountDao accountDao;
|
||||
|
||||
/**
|
||||
* Validates given factory by checking the current user is granted to edit the factory
|
||||
*
|
||||
|
|
@ -53,75 +43,11 @@ public class FactoryEditValidatorImpl implements FactoryEditValidator {
|
|||
public void validate(Factory factory) throws ForbiddenException, ServerException {
|
||||
// ensure user has the correct permissions
|
||||
final String userId = EnvironmentContext.getCurrent().getUser().getId();
|
||||
boolean granted = validateAuthor(factory, userId);
|
||||
|
||||
// check also for account owner
|
||||
if (!granted) {
|
||||
validateAccountOwner(factory, userId);
|
||||
}
|
||||
|
||||
// ok access is granted !
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the given user is the same author than the one that has created the factory
|
||||
*
|
||||
* @param factory
|
||||
* the factory to check
|
||||
* @param userId
|
||||
* the user id to check
|
||||
* @return true if this is matching, else false
|
||||
*/
|
||||
protected boolean validateAuthor(Factory factory, String userId) throws ServerException {
|
||||
// Checks if there is an author from the factory (It may be missing for some old factories)
|
||||
Author author = factory.getCreator();
|
||||
if (author == null || author.getUserId() == null) {
|
||||
throw new ServerException(format("Invalid factory without author stored. Please contact the support about the factory ID '%s'",
|
||||
factory.getId()));
|
||||
}
|
||||
|
||||
// Gets the userId of the factory
|
||||
String factoryUserId = factory.getCreator().getUserId();
|
||||
|
||||
// return true if it's the same user
|
||||
return factoryUserId.equals(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the given user may be an account owner
|
||||
*
|
||||
* @param factory
|
||||
* the factory to check
|
||||
* @param userId
|
||||
* the user id to check
|
||||
* @throws org.eclipse.che.api.core.ForbiddenException
|
||||
* occurs when cobra attack
|
||||
*/
|
||||
protected void validateAccountOwner(Factory factory, String userId) throws ForbiddenException, ServerException {
|
||||
// Checks if there is an author from the factory (It may be missing for some old factories)
|
||||
// And if there is an accountID
|
||||
Author author = factory.getCreator();
|
||||
if (author == null || author.getAccountId() == null) {
|
||||
throw new ForbiddenException(format("You are not authorized for the factory '%s'", factory.getId()));
|
||||
}
|
||||
|
||||
// Gets accountID
|
||||
String factoryAccountId = factory.getCreator().getAccountId();
|
||||
|
||||
List<Member> members = accountDao.getMembers(factoryAccountId);
|
||||
if (members.isEmpty()) {
|
||||
throw new ForbiddenException(format("You are not authorized for the factory '%s'", factory.getId()));
|
||||
}
|
||||
|
||||
boolean isOwner = false;
|
||||
for (Member accountMember : members) {
|
||||
if (accountMember.getUserId().equals(userId) && accountMember.getRoles().contains("account/owner")) {
|
||||
isOwner = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isOwner) {
|
||||
throw new ForbiddenException(format("You are not an account/owner for the factory '%s'", factory.getId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -934,9 +934,9 @@ public class FactoryServiceTest {
|
|||
// given
|
||||
Factory factory = prepareFactoryWithGivenStorage("git", "http://github.com/codenvy/platform-api.git")
|
||||
.withId(CORRECT_FACTORY_ID)
|
||||
.withCreator(dto.createDto(Author.class).withAccountId("testorg"));
|
||||
.withCreator(dto.createDto(Author.class).withUserId("uid-123"));
|
||||
|
||||
List<Pair<String, String>> expected = Collections.singletonList(Pair.of("creator.accountid", "testorg"));
|
||||
List<Pair<String, String>> expected = Collections.singletonList(Pair.of("creator.userid", "uid-123"));
|
||||
when(factoryStore.findByAttribute(anyInt(), anyInt(), eq(expected))).thenReturn(
|
||||
Arrays.asList(factory, factory));
|
||||
|
||||
|
|
@ -944,7 +944,7 @@ public class FactoryServiceTest {
|
|||
Response response = given().auth()
|
||||
.basic(JettyHttpServer.ADMIN_USER_NAME, JettyHttpServer.ADMIN_USER_PASSWORD)
|
||||
.when()
|
||||
.get("/private" + SERVICE_PATH + "/find?creator.accountid=testorg");
|
||||
.get("/private" + SERVICE_PATH + "/find?creator.userid=uid-123");
|
||||
|
||||
// then
|
||||
assertEquals(response.getStatusCode(), 200);
|
||||
|
|
|
|||
|
|
@ -211,7 +211,6 @@ public class FactoryBuilderTest {
|
|||
.withV("4.0")
|
||||
.withWorkspace(workspaceConfig)
|
||||
.withCreator(dto.createDto(Author.class)
|
||||
.withAccountId("accountId")
|
||||
.withEmail("email")
|
||||
.withName("name"))
|
||||
.withPolicies(dto.createDto(Policies.class)
|
||||
|
|
|
|||
|
|
@ -12,11 +12,8 @@ package org.eclipse.che.api.factory.server.impl;
|
|||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.core.ApiException;
|
||||
import org.eclipse.che.api.core.BadRequestException;
|
||||
import org.eclipse.che.api.core.ConflictException;
|
||||
import org.eclipse.che.api.core.NotFoundException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
import org.eclipse.che.api.factory.server.FactoryConstants;
|
||||
|
|
@ -57,7 +54,6 @@ import java.util.Map;
|
|||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.eclipse.che.dto.server.DtoFactory.newDto;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@Listeners(value = {MockitoTestNGListener.class})
|
||||
|
|
@ -66,8 +62,6 @@ public class FactoryBaseValidatorTest {
|
|||
private static final String VALID_PROJECT_PATH = "/cloudide";
|
||||
private static final String ID = "id";
|
||||
|
||||
@Mock
|
||||
private AccountDao accountDao;
|
||||
|
||||
@Mock
|
||||
private UserDao userDao;
|
||||
|
|
@ -79,29 +73,23 @@ public class FactoryBaseValidatorTest {
|
|||
private FactoryBuilder builder;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
private HttpServletRequest request;
|
||||
|
||||
private TesterFactoryBaseValidator validator;
|
||||
|
||||
private Member member;
|
||||
|
||||
private Factory factory;
|
||||
|
||||
@BeforeMethod
|
||||
public void setUp() throws ParseException, NotFoundException, ServerException {
|
||||
factory = newDto(Factory.class)
|
||||
.withV("4.0")
|
||||
.withCreator(newDto(Author.class)
|
||||
.withAccountId(ID)
|
||||
.withUserId("userid"));
|
||||
.withV("4.0")
|
||||
.withCreator(newDto(Author.class)
|
||||
.withUserId("userid"));
|
||||
|
||||
User user = new User().withId("userid");
|
||||
|
||||
member = new Member().withUserId("userid")
|
||||
.withRoles(Collections.singletonList("account/owner"));
|
||||
when(accountDao.getMembers(anyString())).thenReturn(Collections.singletonList(member));
|
||||
when(userDao.getById("userid")).thenReturn(user);
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
@ -137,7 +125,8 @@ public class FactoryBaseValidatorTest {
|
|||
@Test
|
||||
public void shouldValidateIfStorageLocationIsCorrectSsh() throws ApiException {
|
||||
// given
|
||||
factory = prepareFactoryWithGivenStorage("git", "ssh://codenvy@review.gerrithub.io:29418/codenvy/exampleProject", "example-project");
|
||||
factory =
|
||||
prepareFactoryWithGivenStorage("git", "ssh://codenvy@review.gerrithub.io:29418/codenvy/exampleProject", "example-project");
|
||||
|
||||
// when, then
|
||||
validator.validateProjects(factory);
|
||||
|
|
@ -146,7 +135,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test
|
||||
public void shouldValidateIfStorageLocationIsCorrectHttps() throws ApiException {
|
||||
// given
|
||||
factory = prepareFactoryWithGivenStorage("git","https://github.com/codenvy/example.git", "/example");
|
||||
factory = prepareFactoryWithGivenStorage("git", "https://github.com/codenvy/example.git", "/example");
|
||||
|
||||
// when, then
|
||||
validator.validateProjects(factory);
|
||||
|
|
@ -155,7 +144,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test
|
||||
public void shouldValidateSubProjectWithNoLocation() throws ApiException {
|
||||
// given
|
||||
factory = prepareFactoryWithGivenStorage("git","null", "/cloudide/core");
|
||||
factory = prepareFactoryWithGivenStorage("git", "null", "/cloudide/core");
|
||||
|
||||
// when, then
|
||||
validator.validateProjects(factory);
|
||||
|
|
@ -168,7 +157,7 @@ public class FactoryBaseValidatorTest {
|
|||
|
||||
@DataProvider(name = "badAdvancedFactoryUrlProvider")
|
||||
public Object[][] invalidParametersFactoryUrlProvider() throws UnsupportedEncodingException {
|
||||
Factory adv1 = prepareFactoryWithGivenStorage("notagit", VALID_REPOSITORY_URL, VALID_PROJECT_PATH );
|
||||
Factory adv1 = prepareFactoryWithGivenStorage("notagit", VALID_REPOSITORY_URL, VALID_PROJECT_PATH);
|
||||
Factory adv2 = prepareFactoryWithGivenStorage("git", null, VALID_PROJECT_PATH);
|
||||
Factory adv3 = prepareFactoryWithGivenStorage("git", "", VALID_PROJECT_PATH);
|
||||
return new Object[][]{
|
||||
|
|
@ -245,24 +234,6 @@ public class FactoryBaseValidatorTest {
|
|||
validator.validateAccountId(factory);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class)
|
||||
public void shouldNotValidateIfAccountDoesNotExist() throws ApiException {
|
||||
when(accountDao.getMembers(anyString())).thenReturn(Collections.<Member>emptyList());
|
||||
|
||||
validator.validateAccountId(factory);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class, expectedExceptionsMessageRegExp = "You are not authorized to use this accountId.")
|
||||
public void shouldNotValidateIfFactoryOwnerIsNotOrgidOwner()
|
||||
throws ApiException, ParseException {
|
||||
Member wrongMember = member;
|
||||
wrongMember.setUserId("anotheruserid");
|
||||
when(accountDao.getMembers(anyString())).thenReturn(Arrays.asList(wrongMember));
|
||||
|
||||
// when, then
|
||||
validator.validateAccountId(factory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldValidateIfCurrentTimeBeforeSinceUntil() throws Exception {
|
||||
Long currentTime = new Date().getTime();
|
||||
|
|
@ -274,7 +245,7 @@ public class FactoryBaseValidatorTest {
|
|||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class,
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCE_MESSAGE)
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCE_MESSAGE)
|
||||
public void shouldNotValidateIfSinceBeforeCurrent() throws ApiException {
|
||||
factory.withPolicies(newDto(Policies.class)
|
||||
.withSince(1L));
|
||||
|
|
@ -282,7 +253,7 @@ public class FactoryBaseValidatorTest {
|
|||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class,
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_UNTIL_MESSAGE)
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_UNTIL_MESSAGE)
|
||||
public void shouldNotValidateIfUntilBeforeCurrent() throws ApiException {
|
||||
factory.withPolicies(newDto(Policies.class)
|
||||
.withUntil(1L));
|
||||
|
|
@ -290,7 +261,7 @@ public class FactoryBaseValidatorTest {
|
|||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class,
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCEUNTIL_MESSAGE)
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.INVALID_SINCEUNTIL_MESSAGE)
|
||||
public void shouldNotValidateIfUntilBeforeSince() throws ApiException {
|
||||
factory.withPolicies(newDto(Policies.class)
|
||||
.withSince(2L)
|
||||
|
|
@ -300,7 +271,7 @@ public class FactoryBaseValidatorTest {
|
|||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class,
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.ILLEGAL_FACTORY_BY_UNTIL_MESSAGE)
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.ILLEGAL_FACTORY_BY_UNTIL_MESSAGE)
|
||||
public void shouldNotValidateIfUntilBeforeCurrentTime() throws ApiException {
|
||||
Long currentTime = new Date().getTime();
|
||||
factory.withPolicies(newDto(Policies.class)
|
||||
|
|
@ -321,7 +292,7 @@ public class FactoryBaseValidatorTest {
|
|||
}
|
||||
|
||||
@Test(expectedExceptions = ApiException.class,
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.ILLEGAL_FACTORY_BY_SINCE_MESSAGE)
|
||||
expectedExceptionsMessageRegExp = FactoryConstants.ILLEGAL_FACTORY_BY_SINCE_MESSAGE)
|
||||
public void shouldNotValidateIfUntilSinceAfterCurrentTime() throws ApiException {
|
||||
Long currentTime = new Date().getTime();
|
||||
factory.withPolicies(newDto(Policies.class)
|
||||
|
|
@ -340,7 +311,7 @@ public class FactoryBaseValidatorTest {
|
|||
.withSince(System.currentTimeMillis() + 1_000_000)
|
||||
.withUntil(System.currentTimeMillis() + 10_000_000)
|
||||
.withReferer("codenvy.com"));
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
|
||||
validator.validateAccountId(factory);
|
||||
}
|
||||
|
|
@ -349,7 +320,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateOpenfileActionIfInWrongSectionOnAppClosed() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
.withId("openFile"));
|
||||
Ide ide = newDto(Ide.class)
|
||||
|
|
@ -363,7 +334,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateFindReplaceActionIfInWrongSectionOnAppLoaded() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
.withId("findReplace"));
|
||||
Ide ide = newDto(Ide.class)
|
||||
|
|
@ -377,7 +348,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateIfOpenfileActionInsufficientParams() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
.withId("openFile"));
|
||||
Ide ide = newDto(Ide.class)
|
||||
|
|
@ -391,7 +362,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateIfrunCommandActionInsufficientParams() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
.withId("openFile"));
|
||||
Ide ide = newDto(Ide.class)
|
||||
|
|
@ -405,12 +376,12 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateIfOpenWelcomePageActionInsufficientParams() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
.withId("openWelcomePage"));
|
||||
.withId("openWelcomePage"));
|
||||
Ide ide = newDto(Ide.class)
|
||||
.withOnAppLoaded((newDto(OnAppLoaded.class)
|
||||
.withActions(actions)));
|
||||
.withOnAppLoaded((newDto(OnAppLoaded.class)
|
||||
.withActions(actions)));
|
||||
Factory factoryWithAccountId = DtoFactory.getInstance().clone(factory).withIde(ide);
|
||||
//when
|
||||
validator.validateProjectActions(factoryWithAccountId);
|
||||
|
|
@ -419,7 +390,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test(expectedExceptions = BadRequestException.class)
|
||||
public void shouldNotValidateIfFindReplaceActionInsufficientParams() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("in", "pom.xml");
|
||||
// find is missing!
|
||||
|
|
@ -438,7 +409,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test
|
||||
public void shouldValidateFindReplaceAction() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("in", "pom.xml");
|
||||
params.put("find", "123");
|
||||
|
|
@ -457,7 +428,7 @@ public class FactoryBaseValidatorTest {
|
|||
@Test
|
||||
public void shouldValidateOpenfileAction() throws Exception {
|
||||
//given
|
||||
validator = new TesterFactoryBaseValidator(accountDao, preferenceDao);
|
||||
validator = new TesterFactoryBaseValidator(preferenceDao);
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("file", "pom.xml");
|
||||
List<Action> actions = Arrays.asList(newDto(Action.class)
|
||||
|
|
@ -477,29 +448,29 @@ public class FactoryBaseValidatorTest {
|
|||
return new Object[][]{
|
||||
{
|
||||
newDto(Factory.class)
|
||||
.withV("4.0")
|
||||
.withIde(newDto(Ide.class)
|
||||
.withOnAppLoaded(newDto(OnAppLoaded.class)
|
||||
.withActions(singletonList(newDto(Action.class)
|
||||
.withId("openWelcomePage")
|
||||
.withProperties(
|
||||
ImmutableMap
|
||||
.<String,
|
||||
String>builder()
|
||||
.put("authenticatedTitle",
|
||||
"title")
|
||||
.put("authenticatedIconUrl",
|
||||
"url")
|
||||
.put("authenticatedContentUrl",
|
||||
"url")
|
||||
.put("nonAuthenticatedTitle",
|
||||
"title")
|
||||
.put("nonAuthenticatedIconUrl",
|
||||
"url")
|
||||
.put("nonAuthenticatedContentUrl",
|
||||
"url")
|
||||
.build()))
|
||||
)))},
|
||||
.withV("4.0")
|
||||
.withIde(newDto(Ide.class)
|
||||
.withOnAppLoaded(newDto(OnAppLoaded.class)
|
||||
.withActions(singletonList(newDto(Action.class)
|
||||
.withId("openWelcomePage")
|
||||
.withProperties(
|
||||
ImmutableMap
|
||||
.<String,
|
||||
String>builder()
|
||||
.put("authenticatedTitle",
|
||||
"title")
|
||||
.put("authenticatedIconUrl",
|
||||
"url")
|
||||
.put("authenticatedContentUrl",
|
||||
"url")
|
||||
.put("nonAuthenticatedTitle",
|
||||
"title")
|
||||
.put("nonAuthenticatedIconUrl",
|
||||
"url")
|
||||
.put("nonAuthenticatedContentUrl",
|
||||
"url")
|
||||
.build()))
|
||||
)))},
|
||||
|
||||
{newDto(Factory.class)
|
||||
.withV("4.0")
|
||||
|
|
|
|||
|
|
@ -10,20 +10,23 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.core.ApiException;
|
||||
import org.eclipse.che.api.core.model.workspace.WorkspaceConfig;
|
||||
import org.eclipse.che.api.factory.shared.dto.Factory;
|
||||
import org.eclipse.che.api.user.server.dao.PreferenceDao;
|
||||
import org.eclipse.che.api.user.server.dao.UserDao;
|
||||
|
||||
import org.eclipse.che.api.workspace.server.WorkspaceValidator;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.testng.MockitoTestNGListener;
|
||||
import org.testng.annotations.BeforeMethod;
|
||||
import org.testng.annotations.Listeners;
|
||||
import org.testng.annotations.Test;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import static org.mockito.Mockito.any;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
/**
|
||||
* Tests for {@link org.eclipse.che.api.factory.server.impl.FactoryAcceptValidatorImpl} and {@link FactoryCreateValidatorImpl}
|
||||
|
|
@ -31,9 +34,6 @@ import static org.mockito.Mockito.*;
|
|||
@Listeners(value = {MockitoTestNGListener.class})
|
||||
public class FactoryCreateAndAcceptValidatorsImplsTest {
|
||||
|
||||
@Mock
|
||||
private AccountDao accountDao;
|
||||
|
||||
@Mock
|
||||
private UserDao userDao;
|
||||
|
||||
|
|
@ -54,8 +54,8 @@ public class FactoryCreateAndAcceptValidatorsImplsTest {
|
|||
@BeforeMethod
|
||||
public void setUp() throws Exception {
|
||||
|
||||
acceptValidator = new FactoryAcceptValidatorImpl(accountDao, preferenceDao);
|
||||
createValidator = new FactoryCreateValidatorImpl(accountDao, preferenceDao, workspaceConfigValidator);
|
||||
acceptValidator = new FactoryAcceptValidatorImpl(preferenceDao);
|
||||
createValidator = new FactoryCreateValidatorImpl(preferenceDao, workspaceConfigValidator);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
|||
|
|
@ -10,15 +10,11 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.account.server.dao.Member;
|
||||
import org.eclipse.che.api.core.ApiException;
|
||||
import org.eclipse.che.api.core.ForbiddenException;
|
||||
import org.eclipse.che.api.core.ServerException;
|
||||
import org.eclipse.che.api.factory.server.FactoryEditValidator;
|
||||
import org.eclipse.che.api.factory.shared.dto.Author;
|
||||
import org.eclipse.che.api.factory.shared.dto.Factory;
|
||||
|
||||
import org.eclipse.che.commons.env.EnvironmentContext;
|
||||
import org.eclipse.che.commons.user.User;
|
||||
import org.mockito.InjectMocks;
|
||||
|
|
@ -27,11 +23,6 @@ import org.mockito.testng.MockitoTestNGListener;
|
|||
import org.testng.annotations.Listeners;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
|
@ -43,9 +34,6 @@ import static org.mockito.Mockito.when;
|
|||
@Listeners(value = {MockitoTestNGListener.class})
|
||||
public class FactoryEditValidatorImplTest {
|
||||
|
||||
@Mock
|
||||
private AccountDao accountDao;
|
||||
|
||||
@Mock
|
||||
private Factory factory;
|
||||
|
||||
|
|
@ -79,96 +67,6 @@ public class FactoryEditValidatorImplTest {
|
|||
factoryEditValidator.validate(factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check when factory has no account id and user is not the same
|
||||
* @throws ApiException
|
||||
*/
|
||||
@Test(expectedExceptions = ForbiddenException.class)
|
||||
public void testWithoutAccountID() throws ApiException {
|
||||
setCurrentUser("toto");
|
||||
String userIdFactory = "florent";
|
||||
Author author = mock(Author.class);
|
||||
doReturn(author).when(factory)
|
||||
.getCreator();
|
||||
doReturn(userIdFactory).when(author)
|
||||
.getUserId();
|
||||
|
||||
factoryEditValidator.validate(factory);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check when factory has account id without members
|
||||
* @throws ApiException
|
||||
*/
|
||||
@Test(expectedExceptions = ForbiddenException.class)
|
||||
public void testUserWithNoMembersInAccountID() throws ApiException {
|
||||
String userIdFactory = "florent";
|
||||
String accountId = "myAccount";
|
||||
setCurrentUser("toto");
|
||||
Author author = mock(Author.class);
|
||||
doReturn("123").when(factory).getId();
|
||||
doReturn(author).when(factory).getCreator();
|
||||
doReturn(userIdFactory).when(author).getUserId();
|
||||
doReturn(accountId).when(author).getAccountId();
|
||||
|
||||
factoryEditValidator.validate(factory);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check when user is not the same and is not account owner
|
||||
* @throws ApiException
|
||||
*/
|
||||
@Test(expectedExceptions = ForbiddenException.class)
|
||||
public void testUserNotInAccountOwner() throws ApiException {
|
||||
String currentUserId = "florent";
|
||||
setCurrentUser(currentUserId);
|
||||
String userIdFactory = "johndoe";
|
||||
String accountId = "myAccount";
|
||||
Author author = mock(Author.class);
|
||||
doReturn("123").when(factory).getId();
|
||||
doReturn(author).when(factory).getCreator();
|
||||
doReturn(userIdFactory).when(author).getUserId();
|
||||
doReturn(accountId).when(author).getAccountId();
|
||||
|
||||
Member member = mock(Member.class);
|
||||
doReturn(currentUserId).when(member).getUserId();
|
||||
List<Member> members = new ArrayList<>();
|
||||
members.add(member);
|
||||
doReturn(members).when(accountDao).getMembers(eq(accountId));
|
||||
|
||||
factoryEditValidator.validate(factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check when user is not the same but is an account owner
|
||||
* @throws ApiException
|
||||
*/
|
||||
@Test
|
||||
public void testUserIsAccountOwner() throws ApiException {
|
||||
String currentUserId = "florent";
|
||||
setCurrentUser(currentUserId);
|
||||
String userIdFactory = "johndoe";
|
||||
String accountId = "myAccount";
|
||||
Author author = mock(Author.class);
|
||||
doReturn("123").when(factory).getId();
|
||||
doReturn(author).when(factory).getCreator();
|
||||
doReturn(userIdFactory).when(author).getUserId();
|
||||
doReturn(accountId).when(author).getAccountId();
|
||||
|
||||
Member member = mock(Member.class);
|
||||
doReturn(currentUserId).when(member).getUserId();
|
||||
List<String> roles = Arrays.asList("account/owner");
|
||||
doReturn(roles).when(member).getRoles();
|
||||
List<Member> members = new ArrayList<>();
|
||||
members.add(member);
|
||||
doReturn(members).when(accountDao).getMembers(eq(accountId));
|
||||
|
||||
factoryEditValidator.validate(factory);
|
||||
}
|
||||
|
||||
|
||||
private void setCurrentUser(String userId) {
|
||||
User user = mock(User.class);
|
||||
when(user.getId()).thenReturn(userId);
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@
|
|||
*******************************************************************************/
|
||||
package org.eclipse.che.api.factory.server.impl;
|
||||
|
||||
import org.eclipse.che.api.account.server.dao.AccountDao;
|
||||
import org.eclipse.che.api.user.server.dao.PreferenceDao;
|
||||
|
||||
/**
|
||||
|
|
@ -18,8 +17,7 @@ import org.eclipse.che.api.user.server.dao.PreferenceDao;
|
|||
*/
|
||||
public class TesterFactoryBaseValidator extends FactoryBaseValidator {
|
||||
|
||||
public TesterFactoryBaseValidator(AccountDao accountDao,
|
||||
PreferenceDao preferenceDao) {
|
||||
super(accountDao, preferenceDao);
|
||||
public TesterFactoryBaseValidator(PreferenceDao preferenceDao) {
|
||||
super(preferenceDao);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue