Checks if the current user has management access to the given project.<p>

@param dbc the current database context
@param project the project to check

@throws CmsRoleViolationException if the user does not have the required role permissions
507570
public void checkManagerOfProjectRole(CmsDbContext dbc, CmsProject project) throws CmsRoleViolationException {

        boolean hasRole = false;
        try {
            if (hasRole(dbc, dbc.currentUser(), CmsRole.ROOT_ADMIN)) {
                return;
            }
            hasRole = m_driverManager.getAllManageableProjects(
                dbc,
                m_driverManager.readOrganizationalUnit(dbc, project.getOuFqn()),
                false).contains(project);
        } catch (CmsException e) {
            // should never happen
            if (LOG.isErrorEnabled()) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
        if (!hasRole) {
            throw new CmsRoleViolationException(
                org.opencms.security.Messages.get().container(
                    org.opencms.security.Messages.ERR_NOT_MANAGER_OF_PROJECT_2,
                    dbc.currentUser().getName(),
                    dbc.currentProject().getName()));
        }
    }
199960
public void readLocks(CmsDbContext dbc) throws CmsException {

        if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
            // read the locks only if the wizard is not enabled
            Map<String, CmsLock> lockCache = new HashMap<String, CmsLock>();
            List<CmsLock> locks = m_driverManager.getProjectDriver(dbc).readLocks(dbc);
            Iterator<CmsLock> itLocks = locks.iterator();
            while (itLocks.hasNext()) {
                CmsLock lock = itLocks.next();
                internalLockResource(lock, lockCache);
            }
            OpenCms.getMemoryMonitor().flushLocks(lockCache);
            m_runningInServlet = true;
        }
    }
1289201
protected Acl collectAcl(CmsObject cms, CmsResource resource, boolean onlyBasic) throws CmsException {

        AccessControlListImpl cmisAcl = new AccessControlListImpl();
        List<Ace> cmisAces = new ArrayList<Ace>();
        List<CmsAccessControlEntry> aces = cms.getAccessControlEntries(resource.getRootPath(), true);
        for (CmsAccessControlEntry ace : aces) {
            boolean isDirect = ace.getResource().equals(resource.getResourceId());
            CmsUUID principalId = ace.getPrincipal();
            String principalName = getAcePrincipalName(cms, principalId);
            AccessControlEntryImpl cmisAce = new AccessControlEntryImpl();
            AccessControlPrincipalDataImpl cmisPrincipal = new AccessControlPrincipalDataImpl();
            cmisPrincipal.setId(principalName);
            cmisAce.setPrincipal(cmisPrincipal);
            cmisAce.setPermissions(onlyBasic ? getCmisPermissions(ace) : getNativePermissions(ace));
            cmisAce.setDirect(isDirect);
            cmisAces.add(cmisAce);
        }
        cmisAcl.setAces(cmisAces);
        cmisAcl.setExact(Boolean.FALSE);
        return cmisAcl;
    }
84795
public CmsGroup readGroup(CmsDbContext dbc, CmsProject project) {

        try {
            return readGroup(dbc, project.getGroupId());
        } catch (CmsException exc) {
            return new CmsGroup(
                CmsUUID.getNullUUID(),
                CmsUUID.getNullUUID(),
                project.getGroupId() + "",
                "deleted group",
                0);
        }
    }
1119082
private boolean lockResource(CmsObject cms, CmsResource cmsResource) throws CmsException {

        CmsLock lock = cms.getLock(cms.getSitePath(cmsResource));
        // check the lock
        if ((lock != null)
            && lock.isOwnedBy(cms.getRequestContext().getCurrentUser())
            && lock.isOwnedInProjectBy(
                cms.getRequestContext().getCurrentUser(),
                cms.getRequestContext().getCurrentProject())) {
            // prove is current lock from current user in current project
            return true;
        } else if ((lock != null) && !lock.isUnlocked() && !lock.isOwnedBy(cms.getRequestContext().getCurrentUser())) {
            // the resource is not locked by the current user, so can not lock it
            return false;
        } else if ((lock != null)
            && !lock.isUnlocked()
            && lock.isOwnedBy(cms.getRequestContext().getCurrentUser())
            && !lock.isOwnedInProjectBy(
                cms.getRequestContext().getCurrentUser(),
                cms.getRequestContext().getCurrentProject())) {
            // prove is current lock from current user but not in current project
            // file is locked by current user but not in current project

            cms.changeLock(cms.getSitePath(cmsResource));
        } else if ((lock != null) && lock.isUnlocked()) {
            // lock resource from current user in current project
            cms.lockResource(cms.getSitePath(cmsResource));
        }
        lock = cms.getLock(cms.getSitePath(cmsResource));
        if ((lock != null)
            && lock.isOwnedBy(cms.getRequestContext().getCurrentUser())
            && !lock.isOwnedInProjectBy(
                cms.getRequestContext().getCurrentUser(),
                cms.getRequestContext().getCurrentProject())) {
            // resource could not be locked
            return false;
        }
        // resource is locked successfully
        return true;
    }
943153
public void updateLastLoginDate(CmsDbContext dbc, CmsUser user) throws CmsException {

        m_monitor.clearUserCache(user);
        // set the last login time to the current time
        user.setLastlogin(System.currentTimeMillis());
        dbc.setAttribute(ATTRIBUTE_LOGIN, user.getName());
        getUserDriver(dbc).writeUser(dbc, user);
        // update cache
        m_monitor.cacheUser(user);

        // invalidate all user dependent caches
        m_monitor.flushCache(
            CmsMemoryMonitor.CacheType.ACL,
            CmsMemoryMonitor.CacheType.GROUP,
            CmsMemoryMonitor.CacheType.ORG_UNIT,
            CmsMemoryMonitor.CacheType.USERGROUPS,
            CmsMemoryMonitor.CacheType.USER_LIST,
            CmsMemoryMonitor.CacheType.PERMISSION,
            CmsMemoryMonitor.CacheType.RESOURCE_LIST);

        // fire user modified event
        Map<String, Object> eventData = new HashMap<String, Object>();
        eventData.put(I_CmsEventListener.KEY_USER_ID, user.getId().toString());
        eventData.put(I_CmsEventListener.KEY_USER_NAME, user.getName());
        eventData.put(I_CmsEventListener.KEY_USER_ACTION, I_CmsEventListener.VALUE_USER_MODIFIED_ACTION_WRITE_USER);
        eventData.put(I_CmsEventListener.KEY_USER_CHANGES, Integer.valueOf(CmsUser.FLAG_LAST_LOGIN));
        OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_USER_MODIFIED, eventData));
    }
579923
@CheckForNull
  private PermissionTemplateDto findTemplate(DbSession dbSession, ComponentDto component) {
    String organizationUuid = component.getOrganizationUuid();
    List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession, organizationUuid, null);
    List<PermissionTemplateDto> matchingTemplates = new ArrayList<>();
    for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) {
      String keyPattern = permissionTemplateDto.getKeyPattern();
      if (StringUtils.isNotBlank(keyPattern) && component.getDbKey().matches(keyPattern)) {
        matchingTemplates.add(permissionTemplateDto);
      }
    }
    checkAtMostOneMatchForComponentKey(component.getDbKey(), matchingTemplates);
    if (matchingTemplates.size() == 1) {
      return matchingTemplates.get(0);
    }

    DefaultTemplates defaultTemplates = dbClient.organizationDao().getDefaultTemplates(dbSession, organizationUuid)
      .orElseThrow(() -> new IllegalStateException(
        format("No Default templates defined for organization with uuid '%s'", organizationUuid)));

    String qualifier = component.qualifier();
    DefaultTemplatesResolverImpl.ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver.resolve(defaultTemplates);
    switch (qualifier) {
      case Qualifiers.PROJECT:
        return dbClient.permissionTemplateDao().selectByUuid(dbSession, resolvedDefaultTemplates.getProject());
      case Qualifiers.VIEW:
        String portDefaultTemplateUuid = resolvedDefaultTemplates.getPortfolio().orElseThrow(
          () -> new IllegalStateException("Attempt to create a view when Governance plugin is not installed"));
        return dbClient.permissionTemplateDao().selectByUuid(dbSession, portDefaultTemplateUuid);
      case Qualifiers.APP:
        String appDefaultTemplateUuid = resolvedDefaultTemplates.getApplication().orElseThrow(
          () -> new IllegalStateException("Attempt to create a view when Governance plugin is not installed"));
        return dbClient.permissionTemplateDao().selectByUuid(dbSession, appDefaultTemplateUuid);
      default:
        throw new IllegalArgumentException(format("Qualifier '%s' is not supported", qualifier));
    }
  }
387830
public void writeAccessControlEntry(CmsDbContext dbc, CmsResource resource, CmsAccessControlEntry ace)
    throws CmsException {

        // write the new ace
        getUserDriver(dbc).writeAccessControlEntry(dbc, dbc.currentProject(), ace);

        // log it
        log(
            dbc,
            new CmsLogEntry(
                dbc,
                resource.getStructureId(),
                CmsLogEntryType.RESOURCE_PERMISSIONS,
                new String[] {resource.getRootPath()}),
            false);

        // update the "last modified" information
        setDateLastModified(dbc, resource, resource.getDateLastModified());

        // clear the cache
        m_monitor.clearAccessControlListCache();

        // fire a resource modification event
        Map<String, Object> data = new HashMap<String, Object>(2);
        data.put(I_CmsEventListener.KEY_RESOURCE, resource);
        data.put(I_CmsEventListener.KEY_CHANGE, new Integer(CHANGED_ACCESSCONTROL));
        OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, data));
    }
599180
public static boolean isAzkabanJobPresent(String sessionId, AzkabanProjectConfig azkabanProjectConfig)
      throws IOException {
    log.info("Checking if Azkaban project: " + azkabanProjectConfig.getAzkabanProjectName() + " exists");
    try {
      // NOTE: hacky way to determine if project already exists because Azkaban does not provides a way to
      // .. check if the project already exists or not
      boolean isPresent = StringUtils.isNotBlank(AzkabanAjaxAPIClient.getProjectId(sessionId, azkabanProjectConfig));
      log.info("Project exists: " + isPresent);

      return isPresent;
    } catch (IOException e) {
      // Project doesn't exists
      if (String.format("Project %s doesn't exist.", azkabanProjectConfig.getAzkabanProjectName())
          .equalsIgnoreCase(e.getMessage())) {
        log.info("Project does not exists.");
        return false;
      }
      // Project exists but with no read access to current user
      if ("Permission denied. Need READ access.".equalsIgnoreCase(e.getMessage())) {
        log.info("Project exists, but current user does not has READ access.");
        return true;
      }
      // Some other error
      log.error("Issue in checking if project is present", e);
      throw e;
    }
  }
1228613
protected void setupCms(CmsObject cms) {

        cms.getRequestContext().setUri("/");
        cms.getRequestContext().setSiteRoot((String)m_site.getValue());
        try {
            cms.getRequestContext().setCurrentProject(cms.readProject((CmsUUID)m_project.getValue()));
        } catch (CmsException e) {
            LOG.error("Unable to read Project", e);
        }
    }
253467
protected CmsHistoryProject internalCreateProject(ResultSet res, List<String> resources) throws SQLException {

        String ou = CmsOrganizationalUnit.removeLeadingSeparator(
            res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_OU_0")));
        CmsUUID publishedById = new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECT_PUBLISHED_BY_0")));
        CmsUUID userId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_USER_ID_0")));
        return new CmsHistoryProject(
            res.getInt(m_sqlManager.readQuery("C_PROJECTS_PUBLISH_TAG_0")),
            new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_ID_0"))),
            ou + res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_NAME_0")),
            res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_DESCRIPTION_0")),
            userId,
            new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_GROUP_ID_0"))),
            new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_MANAGERGROUP_ID_0"))),
            res.getLong(m_sqlManager.readQuery("C_PROJECTS_DATE_CREATED_0")),
            CmsProject.CmsProjectType.valueOf(res.getInt(m_sqlManager.readQuery("C_PROJECTS_PROJECT_TYPE_0"))),
            res.getLong(m_sqlManager.readQuery("C_PROJECT_PUBLISHDATE_0")),
            publishedById,
            resources);
    }
1341466
public CmsProject createTempfileProject(CmsDbContext dbc) throws CmsException {

        // read the needed groups from the cms
        CmsGroup projectUserGroup = readGroup(dbc, dbc.currentProject().getGroupId());
        CmsGroup projectManagerGroup = readGroup(dbc, dbc.currentProject().getManagerGroupId());

        CmsProject tempProject = getProjectDriver(dbc).createProject(
            dbc,
            new CmsUUID(),
            dbc.currentUser(),
            projectUserGroup,
            projectManagerGroup,
            I_CmsProjectDriver.TEMP_FILE_PROJECT_NAME,
            Messages.get().getBundle(dbc.getRequestContext().getLocale()).key(
                Messages.GUI_WORKPLACE_TEMPFILE_PROJECT_DESC_0),
            CmsProject.PROJECT_FLAG_HIDDEN,
            CmsProject.PROJECT_TYPE_NORMAL);
        getProjectDriver(dbc).createProjectResource(dbc, tempProject.getUuid(), "/");

        OpenCms.fireCmsEvent(
            new CmsEvent(
                I_CmsEventListener.EVENT_PROJECT_MODIFIED,
                Collections.<String, Object> singletonMap("project", tempProject)));

        return tempProject;
    }
139745
protected boolean checkUserDataTable(CmsSetupDb dbCon) {

        System.out.println(new Exception().getStackTrace()[0].toString());
        return dbCon.hasTableOrColumn(CHECK_CMS_USERDATA, null);
    }
883921
@Override
    protected void createHistProjectsTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        if (!dbCon.hasTableOrColumn(HISTORY_PROJECTS_TABLE, null)) {
            String createStatement = readQuery(QUERY_CREATE_HISTORY_PROJECTS_TABLE_MYSQL);
            Map<String, String> replacer = Collections.singletonMap("${tableEngine}", m_poolData.get("engine"));
            dbCon.updateSqlStatement(createStatement, replacer, null);
            transferDataToHistoryTable(dbCon);
        } else {
            System.out.println("table " + HISTORY_PROJECTS_TABLE + " already exists");
        }
    }
121369
protected void createHistProjectsTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        if (!dbCon.hasTableOrColumn(HISTORY_PROJECTS_TABLE, null)) {
            String createStatement = readQuery(QUERY_CREATE_HISTORY_PROJECTS_TABLE);
            dbCon.updateSqlStatement(createStatement, null, null);
            transferDataToHistoryTable(dbCon);
        } else {
            System.out.println("table " + HISTORY_PROJECTS_TABLE + " already exists");
        }
    }
744008
private static void ensureProjectMember(ProjectMetadata project, User user) {
        requireNonNull(project, "project");
        requireNonNull(user, "user");

        checkArgument(project.members().values().stream().anyMatch(member -> member.login().equals(user.id())),
                      user.id() + " is not a member of the project " + project.name());
    }
175719
public I_CmsUserDriver getUserDriver(CmsDbContext dbc) {

        if ((dbc == null) || (dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) {
            return m_userDriver;
        }
        I_CmsUserDriver driver = dbc.getUserDriver(dbc.getProjectId());
        return driver != null ? driver : m_userDriver;

    }