Repairs broken categories.<p>

@param dbc the database context
@param projectId the project id
@param resource the resource to repair the categories for

@throws CmsException if something goes wrong
762409
public void repairCategories(CmsDbContext dbc, CmsUUID projectId, CmsResource resource) throws CmsException {

        CmsObject cms = OpenCms.initCmsObject(new CmsObject(getSecurityManager(), dbc.getRequestContext()));
        cms.getRequestContext().setSiteRoot("");
        cms.getRequestContext().setCurrentProject(readProject(dbc, projectId));
        CmsCategoryService.getInstance().repairRelations(cms, resource);
    }
248542
protected void deleteRelationsWithSiblings(CmsDbContext dbc, CmsResource resource) throws CmsException {

        // get all siblings
        List<CmsResource> siblings;
        if (resource.getSiblingCount() > 1) {
            siblings = readSiblings(dbc, resource, CmsResourceFilter.ALL);
        } else {
            siblings = new ArrayList<CmsResource>();
            siblings.add(resource);
        }
        // clean the relations in content for all siblings
        I_CmsVfsDriver vfsDriver = getVfsDriver(dbc);
        Iterator<CmsResource> it = siblings.iterator();
        while (it.hasNext()) {
            CmsResource sibling = it.next();
            // clean the relation information for this sibling
            vfsDriver.deleteRelations(
                dbc,
                dbc.currentProject().getUuid(),
                sibling,
                CmsRelationFilter.TARGETS.filterDefinedInContent());
        }
    }
209844
protected void add(CmsPublishJobInfoBean publishJob) throws CmsException {

        // set the queue status in the publish job
        publishJob.enqueue();

        // add job to database if necessary
        if (OpenCms.getMemoryMonitor().requiresPersistency()) {
            CmsDbContext dbc = m_publishEngine.getDbContext(null);
            try {
                // this operation may in rare circumstances fail with a DB exception
                // if this is the case the publish job must NOT be in the queue
                m_publishEngine.getDriverManager().createPublishJob(dbc, publishJob);
            } catch (CmsException e) {
                dbc.rollback();
                LOG.error(e.getLocalizedMessage(), e);
                throw e;
            } finally {
                dbc.clear();
            }
        }

        // add publish job to cache
        OpenCms.getMemoryMonitor().cachePublishJob(publishJob);
    }
767327
protected void add(CmsPublishJobInfoBean publishJob) throws CmsException {

        OpenCms.getMemoryMonitor().cachePublishJobInHistory(publishJob);
        // write job to db if necessary
        if (OpenCms.getMemoryMonitor().requiresPersistency()) {
            CmsDbContext dbc = m_publishEngine.getDbContext(null);
            try {
                m_publishEngine.getDriverManager().writePublishJob(dbc, publishJob);
                // additionally, write the publish report
                m_publishEngine.getDriverManager().writePublishReport(dbc, publishJob);
                // delete publish list of started job
                m_publishEngine.getDriverManager().deletePublishList(dbc, publishJob.getPublishHistoryId());
            } catch (CmsException e) {
                dbc.rollback();
                LOG.error(e.getLocalizedMessage(), e);
                throw e;
            } finally {
                dbc.clear();
            }
        }
    }
607698
protected void addVisit(CmsDbContext dbc, String poolName, CmsVisitEntry visit) throws CmsDbSqlException {

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            if (CmsStringUtil.isNotEmpty(poolName)) {
                conn = m_sqlManager.getConnection(poolName);
            } else {
                conn = m_sqlManager.getConnection(dbc);
            }

            stmt = m_sqlManager.getPreparedStatement(conn, "C_VISIT_CREATE_3");

            stmt.setString(1, visit.getUserId().toString());
            stmt.setLong(2, visit.getDate());
            stmt.setString(3, visit.getStructureId() == null ? null : visit.getStructureId().toString());
            try {
                stmt.executeUpdate();
            } catch (SQLException e) {
                // ignore, most likely a duplicate entry
                LOG.debug(
                    Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)).key(),
                    e);
            }

        } catch (SQLException e) {
            throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
                e);
        } finally {
            try {
                m_sqlManager.closeAll(dbc, conn, stmt, null);
            } catch (Throwable t) {
                // this could happen during shutdown
                LOG.debug(t.getLocalizedMessage(), t);
            }
        }
    }
367459
public void parse(CmsResource resource) throws CmsException {

        CmsFile file = m_cms.readFile(resource);
        parse(file);
    }
179145
public void deleteAliases(CmsDbContext dbc, CmsProject project, CmsAliasFilter filter) throws CmsException {

        I_CmsVfsDriver vfsDriver = getVfsDriver(dbc);
        vfsDriver.deleteAliases(dbc, project, filter);
    }
248193
public void finish() throws CmsException {

        m_finished = true;
        m_requiresCleanup = false;
        CmsProject project = getProject();
        CmsObject projectCms = OpenCms.initCmsObject(m_adminCms);
        projectCms.getRequestContext().setCurrentProject(project);
        if (m_configuration.isAutoPublish()) {
            // we don't necessarily publish with the user who has the locks on the resources, so we need to steal the locks
            List<CmsResource> projectResources = projectCms.readProjectView(project.getUuid(), CmsResource.STATE_KEEP);
            for (CmsResource projectResource : projectResources) {
                CmsLock lock = projectCms.getLock(projectResource);
                if (!lock.isUnlocked() && !lock.isLockableBy(projectCms.getRequestContext().getCurrentUser())) {
                    projectCms.changeLock(projectResource);
                }
            }
            OpenCms.getPublishManager().publishProject(
                projectCms,
                new CmsLogReport(Locale.ENGLISH, CmsUgcSession.class));
        } else {
            // try to unlock everything - we don't need this in case of auto-publish, since publishing already unlocks the resources
            projectCms.unlockProject(project.getUuid());
        }

    }
1108643
public void publishJob(CmsObject cms, CmsDbContext dbc, CmsPublishList publishList, I_CmsReport report)
    throws CmsException {

        try {
            // check state and lock
            List<CmsResource> allResources = new ArrayList<CmsResource>(publishList.getFolderList());
            allResources.addAll(publishList.getDeletedFolderList());
            allResources.addAll(publishList.getFileList());
            Iterator<CmsResource> itResources = allResources.iterator();
            while (itResources.hasNext()) {
                CmsResource resource = itResources.next();
                try {
                    resource = readResource(dbc, resource.getStructureId(), CmsResourceFilter.ALL);
                } catch (CmsVfsResourceNotFoundException e) {
                    continue;
                }
                if (resource.getState().isUnchanged()) {
                    // remove files that were published by a concurrent job
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                            Messages.get().getBundle().key(
                                Messages.RPT_PUBLISH_REMOVED_RESOURCE_1,
                                dbc.removeSiteRoot(resource.getRootPath())));
                    }
                    publishList.remove(resource);
                    unlockResource(dbc, resource, true, true);
                    continue;
                }
                CmsLock lock = m_lockManager.getLock(dbc, resource, false);
                if (!lock.getSystemLock().isPublish()) {
                    // remove files that are not locked for publishing
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                            Messages.get().getBundle().key(
                                Messages.RPT_PUBLISH_REMOVED_RESOURCE_1,
                                dbc.removeSiteRoot(resource.getRootPath())));
                    }
                    publishList.remove(resource);
                    continue;
                }
            }

            CmsProject onlineProject = readProject(dbc, CmsProject.ONLINE_PROJECT_ID);

            // clear the cache
            m_monitor.clearCache();

            int publishTag = getNextPublishTag(dbc);
            getProjectDriver(dbc).publishProject(dbc, report, onlineProject, publishList, publishTag);

            // iterate the initialized module action instances
            Iterator<String> i = OpenCms.getModuleManager().getModuleNames().iterator();
            while (i.hasNext()) {
                CmsModule module = OpenCms.getModuleManager().getModule(i.next());
                if ((module != null) && (module.getActionInstance() != null)) {
                    module.getActionInstance().publishProject(cms, publishList, publishTag, report);
                }
            }

            boolean temporaryProject = (cms.getRequestContext().getCurrentProject().getType() == CmsProject.PROJECT_TYPE_TEMPORARY);
            // the project was stored in the history tables for history
            // it will be deleted if the project_flag is PROJECT_TYPE_TEMPORARY
            if ((temporaryProject) && (!publishList.isDirectPublish())) {
                try {
                    getProjectDriver(dbc).deleteProject(dbc, dbc.currentProject());
                } catch (CmsException e) {
                    LOG.error(
                        Messages.get().getBundle().key(
                            Messages.LOG_DELETE_TEMP_PROJECT_FAILED_1,
                            cms.getRequestContext().getCurrentProject().getName()));
                }
                // if project was temporary set context to online project
                cms.getRequestContext().setCurrentProject(onlineProject);
            }
        } finally {
            // clear the cache again
            m_monitor.clearCache();
        }
    }
1091872
void loadCategories(CmsObject cms, String contextPath) {

        m_checkboxes.clear();
        m_container.removeAllItems();

        List<CmsCategory> categories;
        Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
        CmsCategoryService catService = CmsCategoryService.getInstance();
        // get the categories
        try {
            categories = catService.readCategories(cms, "", true, contextPath);

            categories = catService.localizeCategories(cms, categories, wpLocale);
            setCategories(categories);
        } catch (CmsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
924010
public List<CmsOrganizationalUnit> getResourceOrgUnits(CmsDbContext dbc, CmsResource resource) throws CmsException {

        List<CmsOrganizationalUnit> result = getVfsDriver(dbc).getResourceOus(
            dbc,
            dbc.currentProject().getUuid(),
            resource);

        return result;
    }
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()));
        }
    }
844855
protected void checkWritePermissionsInFolder(CmsDbContext dbc, CmsResource folder) throws CmsDataAccessException {

        ResultSet res = null;
        PreparedStatement stmt = null;
        Connection conn = null;

        CmsUUID projectId = dbc.getRequestContext().getCurrentProject().getUuid();

        // first read all subresources with ACEs
        List<CmsResource> resources = new ArrayList<CmsResource>();
        try {
            conn = m_sqlManager.getConnection(dbc);
            stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ_WITH_ACE_1");
            stmt.setString(1, folder.getRootPath() + "%");
            res = stmt.executeQuery();

            while (res.next()) {
                resources.add(createResource(res, projectId));
            }
        } catch (SQLException e) {
            throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
                e);
        } finally {
            m_sqlManager.closeAll(dbc, conn, stmt, res);
        }

        // check current user write permission for each of these resources
        Iterator<CmsResource> itResources = resources.iterator();
        while (itResources.hasNext()) {
            CmsResource resource = itResources.next();
            try {
                m_driverManager.getSecurityManager().checkPermissions(
                    dbc.getRequestContext(),
                    resource,
                    CmsPermissionSet.ACCESS_WRITE,
                    false,
                    CmsResourceFilter.ALL);
            } catch (CmsException e) {
                throw new CmsDataAccessException(e.getMessageContainer(), e);
            }
        }

        // then check for possible jsp pages without permissions
        CmsResourceFilter filter = CmsResourceFilter.ALL;
        itResources = readTypesInResourceTree(
            dbc,
            projectId,
            folder.getRootPath(),
            CmsResourceTypeJsp.getJspResourceTypeIds(),
            filter.getState(),
            filter.getModifiedAfter(),
            filter.getModifiedBefore(),
            filter.getReleaseAfter(),
            filter.getReleaseBefore(),
            filter.getExpireAfter(),
            filter.getExpireBefore(),
            CmsDriverManager.READMODE_INCLUDE_TREE).iterator();
        while (itResources.hasNext()) {
            CmsResource resource = itResources.next();
            try {
                m_driverManager.getSecurityManager().checkPermissions(
                    dbc.getRequestContext(),
                    resource,
                    CmsPermissionSet.ACCESS_WRITE,
                    false,
                    CmsResourceFilter.ALL);
            } catch (CmsException e) {
                throw new CmsDataAccessException(e.getMessageContainer(), e);
            }
        }
    }
125276
protected CmsBrokenLinkBean createSitemapBrokenLinkBean(CmsResource resource) throws CmsException {

        CmsProperty titleProp = m_cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, true);
        String typeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName();
        String defaultTitle = CmsResource.getName(resource.getRootPath());
        String title = titleProp.getValue(defaultTitle);
        String path = m_cms.getSitePath(resource);
        String subtitle = path;
        return new CmsBrokenLinkBean(resource.getStructureId(), title, subtitle, typeName);
    }
306695
public void initialize(CmsObject cms) throws CmsException {

        CmsUUID id = m_entry.getId();
        CmsResource resource = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION);
        m_resource = resource;
        CmsResource defaultFile = resource;
        if (resource.isFolder()) {
            defaultFile = cms.readDefaultFile(resource, CmsResourceFilter.IGNORE_EXPIRATION);
        }
        CmsLocaleGroup localeGroup = cms.getLocaleGroupService().readLocaleGroup(defaultFile);
        CmsResource primary = localeGroup.getPrimaryResource();
        CmsProperty noTranslationProp = cms.readPropertyObject(
            primary,
            CmsPropertyDefinition.PROPERTY_LOCALE_NOTRANSLATION,
            false);
        m_noTranslation = noTranslationProp.getValue();
        CmsUUID defaultFileId = (defaultFile != null) ? defaultFile.getStructureId() : null;
        m_isCopyable = (defaultFile != null) && CmsResourceTypeXmlContainerPage.isContainerPage(defaultFile);
        Collection<CmsResource> resourcesForTargetLocale = localeGroup.getResourcesForLocale(m_otherLocale);
        if (!resourcesForTargetLocale.isEmpty()) {
            m_linkedResource = resourcesForTargetLocale.iterator().next();
            if (primary.getStructureId().equals(m_resource.getStructureId())
                || primary.getStructureId().equals(defaultFileId)
                || primary.getStructureId().equals(m_linkedResource.getStructureId())) {
                m_isDirectLink = true;
            }
        }
    }
940894
protected CmsBrokenLinkBean createSitemapBrokenLinkBean(CmsResource resource) throws CmsException {

        CmsObject cms = getCmsObject();
        CmsProperty titleProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, true);
        String defaultTitle = "";
        String title = titleProp.getValue(defaultTitle);
        String path = cms.getSitePath(resource);
        String subtitle = path;
        return new CmsBrokenLinkBean(resource.getStructureId(), title, subtitle);

    }
718050
private void initWorkplaceCmsContext(CmsWorkplaceSettings settings, CmsObject cms) {

        CmsRequestContext reqCont = cms.getRequestContext();

        // check project setting
        if (!settings.getProject().equals(reqCont.getCurrentProject().getUuid())) {
            try {
                reqCont.setCurrentProject(cms.readProject(settings.getProject()));
            } catch (CmsDbEntryNotFoundException e) {
                try {
                    // project not found, set current project and settings to online project
                    reqCont.setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID));
                    settings.setProject(CmsProject.ONLINE_PROJECT_ID);
                } catch (CmsException ex) {
                    // log error
                    if (LOG.isInfoEnabled()) {
                        LOG.info(ex.getLocalizedMessage());
                    }
                }
            } catch (CmsException e1) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(e1.getLocalizedMessage());
                }
            }
        }

        // check site setting
        if (!(settings.getSite().equals(reqCont.getSiteRoot()))) {
            // site was switched, set new site root
            reqCont.setSiteRoot(settings.getSite());
            // removed setting explorer resource to "/" to get the stored folder
        }
    }