gt:         final Workspace workspace = workspaceDao.getByName(name);
context: /*******************************************************************************
   * Copyright (c) 2012-2015 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.workspace.server;
  
  
  import com.wordnik.swagger.annotations.Api;
  import com.wordnik.swagger.annotations.ApiOperation;
  import com.wordnik.swagger.annotations.ApiParam;
  import com.wordnik.swagger.annotations.ApiResponse;
  import com.wordnik.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.core.BadRequestException;
  import org.eclipse.che.api.core.ConflictException;
  import org.eclipse.che.api.core.ForbiddenException;
  import org.eclipse.che.api.core.NotFoundException;
  import org.eclipse.che.api.core.ServerException;
  import org.eclipse.che.api.core.rest.Service;
  import org.eclipse.che.api.core.rest.annotations.Description;
  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.UserService;
  import org.eclipse.che.api.user.server.dao.PreferenceDao;
  import org.eclipse.che.api.user.server.dao.Profile;
  import org.eclipse.che.api.user.server.dao.User;
  import org.eclipse.che.api.user.server.dao.UserDao;
  import org.eclipse.che.api.user.server.dao.UserProfileDao;
  import org.eclipse.che.api.workspace.server.dao.Member;
  import org.eclipse.che.api.workspace.server.dao.MemberDao;
  import org.eclipse.che.api.workspace.server.dao.Workspace;
  import org.eclipse.che.api.workspace.server.dao.WorkspaceDao;
  import org.eclipse.che.api.workspace.shared.dto.MemberDescriptor;
  import org.eclipse.che.api.workspace.shared.dto.NewMembership;
  import org.eclipse.che.api.workspace.shared.dto.NewWorkspace;
  import org.eclipse.che.api.workspace.shared.dto.WorkspaceDescriptor;
  import org.eclipse.che.api.workspace.shared.dto.WorkspaceReference;
  import org.eclipse.che.api.workspace.shared.dto.WorkspaceUpdate;
  import org.eclipse.che.commons.env.EnvironmentContext;
  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.util.ArrayList;
  import java.util.HashMap;
  import java.util.LinkedList;
  import java.util.List;
  import java.util.Map;
  
  import static java.lang.Boolean.parseBoolean;
  import static java.util.Arrays.asList;
  import static java.util.Collections.singletonMap;
  import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
  import static javax.ws.rs.core.Response.Status.CREATED;
  import static javax.ws.rs.core.Response.status;
  import static org.eclipse.che.api.user.server.Constants.LINK_REL_GET_USER_BY_ID;
  import static org.eclipse.che.commons.lang.NameGenerator.generate;
  
  /**
   * Workspace API
   *
   * @author Eugene Voevodin
   * @author Max Shaposhnik
   */
  @Api(value = "/workspace",
       description = "Workspace manager")
  @Path("/workspace")
  public class WorkspaceService extends Service {
      private static final Logger LOG = LoggerFactory.getLogger(WorkspaceService.class);
  
      private final WorkspaceDao   workspaceDao;
      private final UserDao        userDao;
      private final MemberDao      memberDao;
      private final UserProfileDao profileDao;
      private final PreferenceDao  preferenceDao;
      private final AccountDao     accountDao;
  
      @Inject
      public WorkspaceService(WorkspaceDao workspaceDao,
                              UserDao userDao,
                              MemberDao memberDao,
                              AccountDao accountDao,
                              UserProfileDao profileDao,
                              PreferenceDao preferenceDao
                             ) {
  
          this.workspaceDao = workspaceDao;
          this.userDao = userDao;
          this.memberDao = memberDao;
          this.accountDao = accountDao;
          this.profileDao = profileDao;
          this.preferenceDao = preferenceDao;
      }
  
      /**
       * Creates new workspace and adds current user as member to created workspace
       * with roles <i>"workspace/admin"</i> and <i>"workspace/developer"</i>. Returns status code <strong>201 CREATED</strong>
       * and {@link WorkspaceDescriptor} if workspace has been created successfully.
       * Each new workspace should contain at least name and account identifier.
       *
       * @param newWorkspace
       *         new workspace
       * @return descriptor of created workspace
       * @throws ConflictException
       *         when current user account identifier and given account identifier are different
       * @throws NotFoundException
       *         when account with given identifier does not exist
       * @throws ServerException
       *         when some error occurred while retrieving/persisting account, workspace or member
       * @throws BadRequestException
       *         when either new workspace or workspace name or account id is {@code null}
       * @see NewWorkspace
       * @see WorkspaceDescriptor
       * @see #getById(String, SecurityContext)
       * @see #getByName(String, SecurityContext)
       */
      @ApiOperation(value = "Create a new workspace",
                    notes = "User and system/admin can create a new persistent workspace. To create a new workspace, a user needs " +
                            "a valid account. Workspace attributes are optional and used as a storage for any workspace specific information",
                    response = WorkspaceDescriptor.class)
      @ApiResponses(value = {
              @ApiResponse(code = 201, message = "CREATED"),
              @ApiResponse(code = 403, message = "You have no access to create more workspaces"),
              @ApiResponse(code = 404, message = "NOT FOUND"),
              @ApiResponse(code = 409, message = "You can create workspace associated only with your own account"),
              @ApiResponse(code = 500, message = "INTERNAL SERVER ERROR")})
      @POST
      @GenerateLink(rel = Constants.LINK_REL_CREATE_WORKSPACE)
      @RolesAllowed({"user", "system/admin"})
      @Consumes(APPLICATION_JSON)
      @Produces(APPLICATION_JSON)
      public Response create(@ApiParam(value = "new workspace", required = true)
                             @Required
                             @Description("new workspace")
                             NewWorkspace newWorkspace,
                             @Context SecurityContext context) throws ConflictException,
                                                                      NotFoundException,
                                                                      ServerException,
                                                                      BadRequestException {
          requiredNotNull(newWorkspace, "New workspace");
          requiredNotNull(newWorkspace.getAccountId(), "Account ID");
          if (newWorkspace.getAttributes() != null) {
              validateAttributes(newWorkspace.getAttributes());
          }
          if (newWorkspace.getName() == null || newWorkspace.getName().isEmpty()) {
              newWorkspace.setName(generateWorkspaceName());
          }
          final Account account = accountDao.getById(newWorkspace.getAccountId());
  
          //check user has access to add new workspace
          if (!context.isUserInRole("system/admin")) {
              ensureCurrentUserOwnerOf(account);
          }
  
          if (account.getAttributes().containsKey(org.eclipse.che.api.account.server.Constants.RESOURCES_LOCKED_PROPERTY)) {
              newWorkspace.getAttributes().put(org.eclipse.che.api.account.server.Constants.RESOURCES_LOCKED_PROPERTY, "true");
          }
  
          final Workspace workspace = new Workspace().withId(generate(Workspace.class.getSimpleName().toLowerCase(), Constants.ID_LENGTH))
                                                     .withName(newWorkspace.getName())
                                                     .withTemporary(false)
                                                     .withAccountId(newWorkspace.getAccountId())
                                                     .withAttributes(newWorkspace.getAttributes());
          workspaceDao.create(workspace);
          LOG.info("EVENT#workspace-created# WS#{}# WS-ID#{}# USER#{}#", newWorkspace.getName(), workspace.getId(), currentUser().getId());
          return status(CREATED).entity(toDescriptor(workspace, context)).build();
      }
  
      /**
       * Creates new temporary workspace and adds current user
       * as member to created workspace with roles <i>"workspace/admin"</i> and <i>"workspace/developer"</i>.
       * If user does not exist, it will be created with role <i>"tmp_user"</i>.
       * Returns status code <strong>201 CREATED</strong> and {@link WorkspaceDescriptor} if workspace
       * has been created successfully. Each new workspace should contain
       * at least workspace name and account identifier.
       *
       * @param newWorkspace
       *         new workspace
       * @return descriptor of created workspace
       * @throws ConflictException
       *         when current user account identifier and given account identifier are different
       * @throws BadRequestException
       *         when either new workspace or workspace name or account identifier is {@code null}
       * @throws NotFoundException
       *         when account with given identifier does not exist
       * @throws ServerException
       *         when some error occurred while retrieving/persisting account, workspace, member or profile
       * @see WorkspaceDescriptor
       * @see #getById(String, SecurityContext)
       * @see #getByName(String, SecurityContext)
       */
      @ApiOperation(value = "Create a temporary workspace",
                    notes = "A temporary workspace is destroyed after certain time of inactivity. It has the same functionality as" +
                            "a persistent workspace. Temporary workspace name is automatically generated when it is system created," +
                            "otherwise a name can be passed in JSON params",
                    response = WorkspaceDescriptor.class
      )
      @ApiResponses(value = {
              @ApiResponse(code = 201, message = "CREATED"),
              @ApiResponse(code = 403, message = "You have no access to create more workspaces"),
              @ApiResponse(code = 404, message = "NOT FOUND"),
              @ApiResponse(code = 409, message = "You can create workspace associated only to your own account"),
              @ApiResponse(code = 500, message = "INTERNAL SERVER ERROR")
      })
      @POST
      @Path("/temp")
      @GenerateLink(rel = Constants.LINK_REL_CREATE_TEMP_WORKSPACE)
      @Consumes(APPLICATION_JSON)
      @Produces(APPLICATION_JSON)
      public Response createTemporary(@ApiParam(value = "New Temporary workspace", required = true)
                                      @Required
                                      @Description("New temporary workspace")
                                      NewWorkspace newWorkspace,
                                      @Context SecurityContext context) throws ConflictException,
                                                                               NotFoundException,
                                                                               BadRequestException,
                                                                               ServerException {
          requiredNotNull(newWorkspace, "New workspace");
          if (newWorkspace.getAttributes() != null) {
              validateAttributes(newWorkspace.getAttributes());
          }
          final Workspace workspace = new Workspace().withId(generate(Workspace.class.getSimpleName().toLowerCase(), Constants.ID_LENGTH))
                                                     .withName(newWorkspace.getName())
                                                     .withTemporary(true)
                                                     .withAccountId(newWorkspace.getAccountId())
                                                     .withAttributes(newWorkspace.getAttributes());
  
          //temporary user should be created if real user does not exist
          final User user;
          boolean isTemporary = false;
          if (context.getUserPrincipal() == null) {
              user = createTemporaryUser();
              isTemporary = true;
          } else {
              user = userDao.getById(currentUser().getId());
          }
  
          if (!isTemporary && !context.isUserInRole("system/admin")) {
              final Account account = accountDao.getById(newWorkspace.getAccountId());
              ensureCurrentUserOwnerOf(account);
          }
  
          createTemporaryWorkspace(workspace);
          final Member newMember = new Member().withUserId(user.getId())
                                               .withWorkspaceId(workspace.getId())
                                               .withRoles(asList("workspace/developer", "workspace/admin"));
          memberDao.create(newMember);
  
          LOG.info("EVENT#workspace-created# WS#{}# WS-ID#{}# USER#{}#", workspace.getName(), workspace.getId(), user.getId());
          return status(CREATED).entity(toDescriptor(workspace, context)).build();
      }
  
      /**
       * Searches for workspace with given identifier and returns {@link WorkspaceDescriptor} if found.
       * If user that has called this method is not <i>"workspace/admin"</i> or <i>"workspace/developer"</i>
       * workspace attributes will not be added to response.
       *
       * @param id
       *         workspace identifier
       * @return descriptor of found workspace
       * @throws NotFoundException
       *         when workspace with given identifier doesn't exist
       * @throws ServerException
       *         when some error occurred while retrieving workspace
       * @see WorkspaceDescriptor
       * @see #getByName(String, SecurityContext)
       */
      @ApiOperation(value = "Get workspace by ID",
                    response = WorkspaceDescriptor.class)
      @ApiResponses(value = {
              @ApiResponse(code = 200, message = "OK"),
              @ApiResponse(code = 404, message = "Workspace with specified ID does not exist"),
              @ApiResponse(code = 403, message = "Access to requested workspace is forbidden"),
              @ApiResponse(code = 500, message = "Server error")})
      @GET
      @Path("/{id}")
      @Produces(APPLICATION_JSON)
      public WorkspaceDescriptor getById(@ApiParam(value = "Workspace ID")
                                         @Description("Workspace ID")
                                         @PathParam("id")
                                         String id,
                                         @Context SecurityContext context) throws NotFoundException,
                                                                                  ServerException,
                                                                                  ForbiddenException {
          final Workspace workspace = workspaceDao.getById(id);
          if (!context.isUserInRole("account/owner") &&
              !context.isUserInRole("workspace/developer") &&
              !context.isUserInRole("workspace/admin")) {
              // tmp_workspace_cloned_from_private_repo - gives information
              // whether workspace was clone from private repository or not. It can be use
              // by temporary workspace sharing filter for user that are not workspace/admin
              // so we need that property here.
              // PLZ DO NOT REMOVE!!!!
              final Map<String, String> attributes = workspace.getAttributes();
              if (attributes.containsKey("allowAnyoneAddMember")) {
                  workspace.setAttributes(singletonMap("allowAnyoneAddMember", attributes.get("allowAnyoneAddMember")));
              } else {
                  attributes.clear();
              }
          }
          return toDescriptor(workspace, context);
      }
  
      /**
       * Searches for workspace with given name and return {@link WorkspaceDescriptor} for it.
       * If user that has called this method is not <i>"workspace/admin"</i> or <i>"workspace/developer"</i>
       * workspace attributes will not be added to response.
       *
       * @param name
       *         workspace name
       * @return descriptor of found workspace
       * @throws NotFoundException
       *         when workspace with given identifier doesn't exist
       * @throws ServerException
       *         when some error occurred while retrieving workspace
       * @see WorkspaceDescriptor
       * @see #getById(String, SecurityContext)
       */
      @ApiOperation(value = "Gets workspace by name",
                    response = WorkspaceDescriptor.class)
      @ApiResponses(value = {
              @ApiResponse(code = 200, message = "OK"),
              @ApiResponse(code = 404, message = "Workspace with specified name doesn't exist"),
              @ApiResponse(code = 403, message = "Access to requested workspace is forbidden"),
              @ApiResponse(code = 500, message = "Server error")})
      @GET
      @GenerateLink(rel = Constants.LINK_REL_GET_WORKSPACE_BY_NAME)
      @Produces(APPLICATION_JSON)
      public WorkspaceDescriptor getByName(@ApiParam(value = "Name of workspace", required = true)
                                           @Required
                                           @Description("Name of workspace")
                                           @QueryParam("name")
                                           String name,
                                           @Context SecurityContext context) throws NotFoundException,
                                                                                    ServerException,
                                                                                    BadRequestException {
          requiredNotNull(name, "Workspace name");
  