private static void _populateThreadLocalsFromContext(Map<String, Serializable> context) {

    long companyId = GetterUtil.getLong(context.get("companyId"));

    if (companyId > 0) {
      CompanyThreadLocal.setCompanyId(companyId);
    }

    Locale defaultLocale = (Locale) context.get("defaultLocale");

    if (defaultLocale != null) {
      LocaleThreadLocal.setDefaultLocale(defaultLocale);
    }

    long groupId = GetterUtil.getLong(context.get("groupId"));

    if (groupId > 0) {
      GroupThreadLocal.setGroupId(groupId);
    }

    String principalName = GetterUtil.getString(context.get("principalName"));

    if (Validator.isNotNull(principalName)) {
      PrincipalThreadLocal.setName(principalName);
    }

    PermissionChecker permissionChecker = null;

    if (Validator.isNotNull(principalName)) {
      try {
        User user = UserLocalServiceUtil.fetchUser(PrincipalThreadLocal.getUserId());

        permissionChecker = PermissionCheckerFactoryUtil.create(user);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    if (permissionChecker != null) {
      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    String principalPassword = GetterUtil.getString(context.get("principalPassword"));

    if (Validator.isNotNull(principalPassword)) {
      PrincipalThreadLocal.setPassword(principalPassword);
    }

    Locale siteDefaultLocale = (Locale) context.get("siteDefaultLocale");

    if (siteDefaultLocale != null) {
      LocaleThreadLocal.setSiteDefaultLocale(siteDefaultLocale);
    }

    Locale themeDisplayLocale = (Locale) context.get("themeDisplayLocale");

    if (themeDisplayLocale != null) {
      LocaleThreadLocal.setThemeDisplayLocale(themeDisplayLocale);
    }
  }
  public static void setThreadValues(User user) {
    if (user == null) {
      PrincipalThreadLocal.setName(null);
      PermissionThreadLocal.setPermissionChecker(null);

      return;
    }

    long userId = user.getUserId();

    String name = String.valueOf(userId);

    PrincipalThreadLocal.setName(name);

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (permissionChecker == null) {
        permissionChecker =
            (PermissionChecker) Class.forName(PropsValues.PERMISSIONS_CHECKER).newInstance();
      }

      permissionChecker.init(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
  private static void _populateContextFromThreadLocals(Map<String, Serializable> context) {

    if (!context.containsKey("companyId")) {
      context.put("companyId", CompanyThreadLocal.getCompanyId());
    }

    if (!context.containsKey("defaultLocale")) {
      context.put("defaultLocale", LocaleThreadLocal.getDefaultLocale());
    }

    if (!context.containsKey("groupId")) {
      context.put("groupId", GroupThreadLocal.getGroupId());
    }

    if (!context.containsKey("principalName")) {
      context.put("principalName", PrincipalThreadLocal.getName());
    }

    if (!context.containsKey("principalPassword")) {
      context.put("principalPassword", PrincipalThreadLocal.getPassword());
    }

    if (!context.containsKey("siteDefaultLocale")) {
      context.put("siteDefaultLocale", LocaleThreadLocal.getSiteDefaultLocale());
    }

    if (!context.containsKey("themeDisplayLocale")) {
      context.put("themeDisplayLocale", LocaleThreadLocal.getThemeDisplayLocale());
    }
  }
示例#4
0
  protected void setPrincipal(long companyId, long userId, String remoteUser, String password) {

    if ((userId == 0) && (remoteUser == null)) {
      return;
    }

    String name = String.valueOf(userId);

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      long remoteUserId = 0;

      try {
        remoteUserId = JAASHelper.getJaasUserId(companyId, remoteUser);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(e);
        }
      }

      if (remoteUserId > 0) {
        name = String.valueOf(remoteUserId);
      }
    } else if (remoteUser != null) {
      name = remoteUser;
    }

    PrincipalThreadLocal.setName(name);

    PrincipalThreadLocal.setPassword(password);
  }
  private String _getPassword() {
    String login = PrincipalThreadLocal.getName();

    if (Validator.isNull(login) || _isDefaultUser(login)) {
      return PropsUtil.get(PropsKeys.DL_REPOSITORY_GUEST_PASSWORD);
    }

    return PrincipalThreadLocal.getPassword();
  }
  protected void searchRecentEntries() throws Exception {
    long initialSearchGroupEntriesCount = searchGroupEntriesCount(group.getGroupId(), 0);

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    BaseModel<?> parentBaseModel1 = getParentBaseModel(group, serviceContext);
    BaseModel<?> parentBaseModel2 = getParentBaseModel(group, serviceContext);

    String name = PrincipalThreadLocal.getName();

    try {
      User user1 = UserTestUtil.addUser(null, 0);

      PrincipalThreadLocal.setName(user1.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);

      User user2 = UserTestUtil.addUser(null, 0);

      PrincipalThreadLocal.setName(user2.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);
    } finally {
      PrincipalThreadLocal.setName(name);
    }

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 5, searchGroupEntriesCount(group.getGroupId(), 0));

    moveParentBaseModelToTrash((Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 3, searchGroupEntriesCount(group.getGroupId(), 0));

    TrashHandler parentTrashHandler =
        TrashHandlerRegistryUtil.getTrashHandler(getParentBaseModelClassName());

    parentTrashHandler.restoreTrashEntry(
        TestPropsValues.getUserId(), (Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialSearchGroupEntriesCount + 5, searchGroupEntriesCount(group.getGroupId(), 0));
  }
  private String _getLogin() {
    String login = PrincipalThreadLocal.getName();

    if (Validator.isNull(login) || _isDefaultUser(login)) {
      return PropsUtil.get(PropsKeys.DL_REPOSITORY_GUEST_USERNAME);
    }

    try {
      String authType = getAuthType();

      if (!authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
        User user = userLocalService.getUser(GetterUtil.getLong(login));

        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
          login = user.getEmailAddress();
        } else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
          login = user.getScreenName();
        }
      }
    } catch (PortalException | SystemException e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Unable to get login to connect to external repository " + _extRepository, e);
      }

      login = null;
    }

    return login;
  }
  public InputStream getContentStream(String version) throws PortalException {

    if (Validator.isNull(version)) {
      return getContentStream();
    }

    for (Document document : getAllVersions()) {
      if (version.equals(document.getVersionLabel())) {
        ContentStream contentStream = document.getContentStream();

        try {
          DLAppHelperLocalServiceUtil.getFileAsStream(PrincipalThreadLocal.getUserId(), this, true);
        } catch (Exception e) {
          _log.error(e, e);
        }

        return contentStream.getStream();
      }
    }

    throw new NoSuchFileVersionException(
        "No CMIS file version with {fileEntryId="
            + getFileEntryId()
            + ", version="
            + version
            + "}");
  }
  @Override
  protected void doUpgrade() throws Exception {
    String name = PrincipalThreadLocal.getName();

    try {
      long companyId = PortalUtil.getDefaultCompanyId();

      long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

      PrincipalThreadLocal.setName(defaultUserId);

      clearData(companyId);
      setupPermissionsDefined(defaultUserId);
    } finally {
      PrincipalThreadLocal.setName(name);
    }
  }
  private void _checkAssetEntry(ExtRepositoryFileEntryAdapter extRepositoryFileEntryAdapter)
      throws PortalException {

    dlAppHelperLocalService.checkAssetEntry(
        PrincipalThreadLocal.getUserId(),
        extRepositoryFileEntryAdapter,
        extRepositoryFileEntryAdapter.getFileVersion());
  }
  /** @deprecated As of 7.0.0, replaced by {@link #getRepositoryEntry(String)} */
  @Deprecated
  public Object[] getRepositoryEntryIds(String objectId) throws PortalException {

    RepositoryEntry repositoryEntry =
        repositoryEntryLocalService.getRepositoryEntry(
            PrincipalThreadLocal.getUserId(), getGroupId(), getRepositoryId(), objectId);

    return new Object[] {repositoryEntry.getRepositoryEntryId(), repositoryEntry.getUuid(), false};
  }
示例#12
0
  protected void initThreadLocals(HttpServletRequest request) throws Exception {

    HttpSession session = request.getSession();

    User user = (User) session.getAttribute(WebKeys.USER);

    initThreadLocals(user);

    PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));
  }
示例#13
0
  public InputStream getContentStream() {
    ContentStream contentStream = _document.getContentStream();

    try {
      DLAppHelperLocalServiceUtil.getFileAsStream(PrincipalThreadLocal.getUserId(), this, true);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return contentStream.getStream();
  }
  public InputStream getContentStream(boolean incrementCounter) {
    ContentStream contentStream = _document.getContentStream();

    try {
      DLAppHelperLocalServiceUtil.getFileAsStream(
          PrincipalThreadLocal.getUserId(), getFileEntry(), incrementCounter);
    } catch (Exception e) {
      _log.error(e);
    }

    return contentStream.getStream();
  }
  protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
      throw new PrincipalException("User is not authenticated");
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret =
        PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
  }
  @Override
  public Session getSession() throws PortalException, RepositoryException {
    Map<String, String> parameters = new HashMap<String, String>();

    parameters.put(SessionParameter.BINDING_TYPE, BindingType.WEBSERVICES.value());
    parameters.put(SessionParameter.COMPRESSION, Boolean.TRUE.toString());

    Locale locale = LocaleUtil.getDefault();

    parameters.put(SessionParameter.LOCALE_ISO3166_COUNTRY, locale.getCountry());
    parameters.put(SessionParameter.LOCALE_ISO639_LANGUAGE, locale.getLanguage());

    String password = PrincipalThreadLocal.getPassword();

    parameters.put(SessionParameter.PASSWORD, password);

    String login = getLogin();

    parameters.put(SessionParameter.USER, login);

    parameters.put(
        SessionParameter.WEBSERVICES_ACL_SERVICE, getTypeSettingsValue(_WEBSERVICES_ACL_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_DISCOVERY_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_DISCOVERY_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_MULTIFILING_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_MULTIFILING_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_NAVIGATION_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_NAVIGATION_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_OBJECT_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_OBJECT_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_POLICY_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_POLICY_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_RELATIONSHIP_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_RELATIONSHIP_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_REPOSITORY_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_REPOSITORY_SERVICE));
    parameters.put(
        SessionParameter.WEBSERVICES_VERSIONING_SERVICE,
        getTypeSettingsValue(_WEBSERVICES_VERSIONING_SERVICE));

    CMISRepositoryUtil.checkRepository(
        getRepositoryId(), parameters, getTypeSettingsProperties(), _REPOSITORY_ID);

    return CMISRepositoryUtil.createSession(parameters);
  }
示例#17
0
  protected HttpServletRequest setCredentials(
      HttpServletRequest request, HttpSession session, long userId) throws Exception {

    User user = UserLocalServiceUtil.getUser(userId);

    String userIdString = String.valueOf(userId);

    request = new ProtectedServletRequest(request, userIdString);

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(_AUTHENTICATED_USER, userIdString);

    if (_usePermissionChecker) {
      PrincipalThreadLocal.setName(userId);
      PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, false);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    return request;
  }
  protected File[] exportLayouts(long userGroupId, Map<String, String[]> parameterMap)
      throws PortalException {

    File[] files = new File[2];

    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(userGroupId);

    User user = userLocalService.getUser(GetterUtil.getLong(PrincipalThreadLocal.getName()));

    Group group = userGroup.getGroup();

    if (userGroup.hasPrivateLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              true,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), true),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[0] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    if (userGroup.hasPublicLayouts()) {
      Map<String, Serializable> exportLayoutSettingsMap =
          ExportImportConfigurationSettingsMapFactory.buildExportLayoutSettingsMap(
              user,
              group.getGroupId(),
              false,
              ExportImportHelperUtil.getAllLayoutIds(group.getGroupId(), false),
              parameterMap);

      ExportImportConfiguration exportImportConfiguration =
          exportImportConfigurationLocalService.addDraftExportImportConfiguration(
              user.getUserId(),
              ExportImportConfigurationConstants.TYPE_EXPORT_LAYOUT,
              exportLayoutSettingsMap);

      files[1] = exportImportLocalService.exportLayoutsAsFile(exportImportConfiguration);
    }

    return files;
  }
  /**
   * See {@link com.liferay.portal.service.BaseServiceImpl#getUserId()}
   *
   * @deprecated As of 7.0.0, with no direct replacement
   */
  @Deprecated
  public static long getUserId() throws PrincipalException {
    String name = PrincipalThreadLocal.getName();

    if (Validator.isNull(name)) {
      throw new PrincipalException("Principal is null");
    } else {
      for (int i = 0; i < BaseServiceImpl.ANONYMOUS_NAMES.length; i++) {
        if (StringUtil.equalsIgnoreCase(name, BaseServiceImpl.ANONYMOUS_NAMES[i])) {

          throw new PrincipalException("Principal cannot be " + BaseServiceImpl.ANONYMOUS_NAMES[i]);
        }
      }
    }

    return GetterUtil.getLong(name);
  }
  @Override
  public void initContextUser(long userId) throws AuthException {
    try {
      User user = UserLocalServiceUtil.getUser(userId);

      CompanyThreadLocal.setCompanyId(user.getCompanyId());

      PrincipalThreadLocal.setName(userId);

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      AccessControlThreadLocal.setRemoteAccess(false);
    } catch (Exception e) {
      throw new AuthException(e.getMessage(), e);
    }
  }
示例#21
0
  protected void initThreadLocals(User user) throws Exception {
    CompanyThreadLocal.setCompanyId(user.getCompanyId());

    PrincipalThreadLocal.setName(user.getUserId());

    if (!_usePermissionChecker) {
      return;
    }

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (permissionChecker != null) {
      return;
    }

    permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
  }
  @Override
  public ArchivedSettings getPortletInstanceArchivedSettings(
      long groupId, String portletId, String name) throws PortalException {

    PortletItem portletItem = null;

    try {
      portletItem =
          PortletItemLocalServiceUtil.getPortletItem(
              groupId, name, portletId, PortletPreferences.class.getName());
    } catch (NoSuchPortletItemException nspie) {
      long userId = PrincipalThreadLocal.getUserId();

      portletItem =
          PortletItemLocalServiceUtil.updatePortletItem(
              userId, groupId, name, portletId, PortletPreferences.class.getName());
    }

    return new ArchivedSettingsImpl(portletItem);
  }
  protected RepositoryEntry getRepositoryEntry(String objectId) throws PortalException {

    return repositoryEntryLocalService.getRepositoryEntry(
        PrincipalThreadLocal.getUserId(), getGroupId(), getRepositoryId(), objectId);
  }
  @Override
  public long getGroupIdFromScopeId(String scopeId, long siteGroupId, boolean privateLayout)
      throws PortalException, SystemException {

    if (scopeId.startsWith(SCOPE_ID_CHILD_GROUP_PREFIX)) {
      String scopeIdSuffix = scopeId.substring(SCOPE_ID_CHILD_GROUP_PREFIX.length());

      return GetterUtil.getLong(scopeIdSuffix);
    } else if (scopeId.startsWith(SCOPE_ID_GROUP_PREFIX)) {
      String scopeIdSuffix = scopeId.substring(SCOPE_ID_GROUP_PREFIX.length());

      if (scopeIdSuffix.equals(GroupConstants.DEFAULT)) {
        return siteGroupId;
      }

      return GetterUtil.getLong(scopeIdSuffix);
    } else if (scopeId.startsWith(SCOPE_ID_LAYOUT_UUID_PREFIX)) {
      String layoutUuid = scopeId.substring(SCOPE_ID_LAYOUT_UUID_PREFIX.length());

      Layout scopeIdLayout =
          LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(layoutUuid, siteGroupId, privateLayout);

      Group scopeIdGroup = null;

      if (scopeIdLayout.hasScopeGroup()) {
        scopeIdGroup = scopeIdLayout.getScopeGroup();
      } else {
        scopeIdGroup =
            GroupLocalServiceUtil.addGroup(
                PrincipalThreadLocal.getUserId(),
                GroupConstants.DEFAULT_PARENT_GROUP_ID,
                Layout.class.getName(),
                scopeIdLayout.getPlid(),
                GroupConstants.DEFAULT_LIVE_GROUP_ID,
                String.valueOf(scopeIdLayout.getPlid()),
                null,
                0,
                null,
                false,
                true,
                null);
      }

      return scopeIdGroup.getGroupId();
    } else if (scopeId.startsWith(SCOPE_ID_LAYOUT_PREFIX)) {

      // Legacy preferences

      String scopeIdSuffix = scopeId.substring(SCOPE_ID_LAYOUT_PREFIX.length());

      long scopeIdLayoutId = GetterUtil.getLong(scopeIdSuffix);

      Layout scopeIdLayout =
          LayoutLocalServiceUtil.getLayout(siteGroupId, privateLayout, scopeIdLayoutId);

      Group scopeIdGroup = scopeIdLayout.getScopeGroup();

      return scopeIdGroup.getGroupId();
    } else if (scopeId.startsWith(SCOPE_ID_PARENT_GROUP_PREFIX)) {
      String scopeIdSuffix = scopeId.substring(SCOPE_ID_PARENT_GROUP_PREFIX.length());

      return GetterUtil.getLong(scopeIdSuffix);
    } else {
      throw new IllegalArgumentException("Invalid scope ID " + scopeId);
    }
  }
示例#25
0
  private long _initCompany(ServletContext servletContext, String webId) {

    // Begin initializing company

    if (_log.isDebugEnabled()) {
      _log.debug("Begin initializing company with web id " + webId);
    }

    long companyId = 0;

    try {
      Company company = CompanyLocalServiceUtil.checkCompany(webId);

      companyId = company.getCompanyId();
    } catch (Exception e) {
      _log.error(e, e);
    }

    Long currentThreadCompanyId = CompanyThreadLocal.getCompanyId();

    String currentThreadPrincipalName = PrincipalThreadLocal.getName();

    try {
      CompanyThreadLocal.setCompanyId(companyId);

      String principalName = null;

      try {
        User user = UserLocalServiceUtil.getUser(PrincipalThreadLocal.getUserId());

        if (user.getCompanyId() == companyId) {
          principalName = currentThreadPrincipalName;
        }
      } catch (Exception e) {
      }

      PrincipalThreadLocal.setName(principalName);

      // Initialize display

      if (_log.isDebugEnabled()) {
        _log.debug("Initialize display");
      }

      try {
        String xml =
            HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-display.xml"));

        PortletCategory portletCategory =
            (PortletCategory) WebAppPool.get(companyId, WebKeys.PORTLET_CATEGORY);

        if (portletCategory == null) {
          portletCategory = new PortletCategory();
        }

        PortletCategory newPortletCategory = PortletLocalServiceUtil.getEARDisplay(xml);

        portletCategory.merge(newPortletCategory);

        for (int i = 0; i < _companyIds.length; i++) {
          long currentCompanyId = _companyIds[i];

          PortletCategory currentPortletCategory =
              (PortletCategory) WebAppPool.get(currentCompanyId, WebKeys.PORTLET_CATEGORY);

          if (currentPortletCategory != null) {
            portletCategory.merge(currentPortletCategory);
          }
        }

        WebAppPool.put(companyId, WebKeys.PORTLET_CATEGORY, portletCategory);
      } catch (Exception e) {
        _log.error(e, e);
      }

      // LDAP import

      try {
        if (LDAPSettingsUtil.isImportOnStartup(companyId)) {
          UserImporterUtil.importUsers(companyId);
        }
      } catch (Exception e) {
        _log.error(e, e);
      }

      // Process application startup events

      if (_log.isDebugEnabled()) {
        _log.debug("Process application startup events");
      }

      try {
        EventsProcessorUtil.process(
            PropsKeys.APPLICATION_STARTUP_EVENTS,
            PropsValues.APPLICATION_STARTUP_EVENTS,
            new String[] {String.valueOf(companyId)});
      } catch (Exception e) {
        _log.error(e, e);
      }

      // End initializing company

      if (_log.isDebugEnabled()) {
        _log.debug(
            "End initializing company with web id " + webId + " and company id " + companyId);
      }

      addCompanyId(companyId);
    } finally {
      CompanyThreadLocal.setCompanyId(currentThreadCompanyId);

      PrincipalThreadLocal.setName(currentThreadPrincipalName);
    }

    return companyId;
  }
  @Override
  protected void dispatch(Set<MessageListener> messageListeners, final Message message) {

    if (!message.contains("companyId")) {
      message.put("companyId", CompanyThreadLocal.getCompanyId());
    }

    if (!message.contains("principalName")) {
      message.put("principalName", PrincipalThreadLocal.getName());
    }

    if (!message.contains("principalPassword")) {
      message.put("principalPassword", PrincipalThreadLocal.getPassword());
    }

    ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

    for (final MessageListener messageListener : messageListeners) {
      Runnable runnable =
          new MessageRunnable(message) {

            public void run() {
              long companyId = CompanyThreadLocal.getCompanyId();
              String principalName = PrincipalThreadLocal.getName();
              String principalPassword = PrincipalThreadLocal.getPassword();

              try {
                long messageCompanyId = message.getLong("companyId");

                if (messageCompanyId > 0) {
                  CompanyThreadLocal.setCompanyId(messageCompanyId);
                }

                String messagePrincipalName = message.getString("principalName");

                if (Validator.isNotNull(messagePrincipalName)) {
                  PrincipalThreadLocal.setName(messagePrincipalName);
                }

                String messagePrincipalPassword = message.getString("principalPassword");

                if (Validator.isNotNull(messagePrincipalPassword)) {
                  PrincipalThreadLocal.setPassword(messagePrincipalPassword);
                }

                messageListener.receive(message);
              } catch (MessageListenerException mle) {
                _log.error("Unable to process message " + message, mle);
              } finally {
                CompanyThreadLocal.setCompanyId(companyId);
                PrincipalThreadLocal.setName(principalName);
                PrincipalThreadLocal.setPassword(principalPassword);

                CentralizedThreadLocal.clearShortLivedThreadLocals();
              }
            }
          };

      threadPoolExecutor.execute(runnable);
    }
  }
  @Override
  public List<SyncDLObject> filterFindByC_M_R_P(
      long companyId, long modifiedTime, long repositoryId, long parentFolderId) {

    Session session = null;

    try {
      session = openSession();

      StringBundler sb = new StringBundler(5);

      String sql = StringPool.BLANK;

      if (modifiedTime != -1) {
        sql = CustomSQLUtil.get(FIND_BY_DELETE_EVENT);

        sb.append(sql);
        sb.append(" UNION ALL ");
      }

      sql = CustomSQLUtil.get(FIND_BY_FOLDER_TYPE);

      if (modifiedTime == -1) {
        sql = sql + " AND (SyncDLObject.event != 'trash') ";
      }

      sql =
          InlineSQLHelperUtil.replacePermissionCheck(
              sql,
              DLFolder.class.getName(),
              "SyncDLObject.typePK",
              null,
              "SyncDLObject.repositoryId",
              new long[] {repositoryId},
              null);

      sb.append(sql);
      sb.append(" UNION ALL ");

      sql = CustomSQLUtil.get(FIND_BY_FILE_OR_PWC_TYPE);

      if (modifiedTime == -1) {
        sql = sql + " AND (SyncDLObject.event != 'trash') ";
      }

      sql =
          InlineSQLHelperUtil.replacePermissionCheck(
              sql,
              DLFileEntry.class.getName(),
              "SyncDLObject.typePK",
              null,
              "SyncDLObject.repositoryId",
              new long[] {repositoryId},
              null);

      sb.append(sql);

      sql = sb.toString();

      if (parentFolderId == -1) {
        sql = StringUtil.replace(sql, _PARENT_FOLDER_ID_SQL, StringPool.BLANK);
      }

      SQLQuery q = session.createSynchronizedSQLQuery(sql);

      q.addEntity("SyncDLObject", SyncDLObjectImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      if (modifiedTime != -1) {
        qPos.add(companyId);
        qPos.add(modifiedTime);
        qPos.add(repositoryId);

        if (parentFolderId != -1) {
          qPos.add(parentFolderId);
        }
      }

      qPos.add(companyId);
      qPos.add(modifiedTime);
      qPos.add(repositoryId);

      if (parentFolderId != -1) {
        qPos.add(parentFolderId);
      }

      qPos.add(companyId);
      qPos.add(modifiedTime);
      qPos.add(repositoryId);

      if (parentFolderId != -1) {
        qPos.add(parentFolderId);
      }

      qPos.add(PrincipalThreadLocal.getUserId());

      return q.list();
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  @Override
  protected void dispatch(final Set<MessageListener> messageListeners, final Message message) {

    if (!message.contains("companyId")) {
      message.put("companyId", CompanyThreadLocal.getCompanyId());
    }

    if (!message.contains("permissionChecker")) {
      message.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
    }

    if (!message.contains("principalName")) {
      message.put("principalName", PrincipalThreadLocal.getName());
    }

    if (!message.contains("principalPassword")) {
      message.put("principalPassword", PrincipalThreadLocal.getPassword());
    }

    ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

    Runnable runnable =
        new MessageRunnable(message) {

          public void run() {
            try {
              long messageCompanyId = message.getLong("companyId");

              if (messageCompanyId > 0) {
                CompanyThreadLocal.setCompanyId(messageCompanyId);
              }

              PermissionChecker permissionChecker =
                  (PermissionChecker) message.get("permissionChecker");

              if (permissionChecker != null) {
                PermissionThreadLocal.setPermissionChecker(permissionChecker);
              }

              String messagePrincipalName = message.getString("principalName");

              if (Validator.isNotNull(messagePrincipalName)) {
                PrincipalThreadLocal.setName(messagePrincipalName);
              }

              String messagePrincipalPassword = message.getString("principalPassword");

              if (Validator.isNotNull(messagePrincipalPassword)) {
                PrincipalThreadLocal.setPassword(messagePrincipalPassword);
              }

              Boolean clusterForwardMessage =
                  (Boolean) message.get(ClusterLinkUtil.CLUSTER_FORWARD_MESSAGE);

              if (clusterForwardMessage != null) {
                MessageValuesThreadLocal.setValue(
                    ClusterLinkUtil.CLUSTER_FORWARD_MESSAGE, clusterForwardMessage);
              }

              for (MessageListener messageListener : messageListeners) {
                try {
                  messageListener.receive(message);
                } catch (MessageListenerException mle) {
                  _log.error("Unable to process message " + message, mle);
                }
              }
            } finally {
              ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);

              CentralizedThreadLocal.clearShortLivedThreadLocals();
            }
          }
        };

    threadPoolExecutor.execute(runnable);
  }
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    User user = null;

    try {
      user = _getUser(request);

      PrincipalThreadLocal.setName(user.getUserId());
      PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      if (_lastModified) {
        long lastModified = getLastModified(request);

        if (lastModified > 0) {
          long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);

          if ((ifModifiedSince > 0) && (ifModifiedSince == lastModified)) {

            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
          }
        }

        if (lastModified > 0) {
          response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
        }
      }

      String path = HttpUtil.fixPath(request.getPathInfo());
      String[] pathArray = StringUtil.split(path, CharPool.SLASH);

      if (pathArray.length == 0) {
        sendGroups(response, user, request.getServletPath() + StringPool.SLASH + path);
      } else {
        if (_PATH_DDM.equals(pathArray[0])) {
          sendDDMRecordFile(request, response, pathArray);
        } else if (Validator.isNumber(pathArray[0])) {
          sendFile(request, response, user, pathArray);
        } else {
          if (isLegacyImageGalleryImageId(request, response)) {
            return;
          }

          Image image = getImage(request, true);

          if (image != null) {
            writeImage(image, request, response);
          } else {
            sendDocumentLibrary(
                request,
                response,
                user,
                request.getServletPath() + StringPool.SLASH + path,
                pathArray);
          }
        }
      }
    } catch (NoSuchFileEntryException nsfee) {
      PortalUtil.sendError(HttpServletResponse.SC_NOT_FOUND, nsfee, request, response);
    } catch (PrincipalException pe) {
      processPrincipalException(pe, user, request, response);
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);
    }
  }