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());
    }
  }
  @Test
  public void testLocalizedSiteAddFileEntryType() throws Exception {
    Group group = GroupTestUtil.addGroup();

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

    Locale locale = LocaleThreadLocal.getSiteDefaultLocale();

    try {
      LocaleThreadLocal.setSiteDefaultLocale(LocaleUtil.SPAIN);

      String name = RandomTestUtil.randomString();
      String description = RandomTestUtil.randomString();
      DDMStructure ddmStructure =
          DDMStructureTestUtil.addStructure(
              DLFileEntry.class.getName(), new Locale[] {LocaleUtil.SPAIN}, LocaleUtil.SPAIN);

      DLFileEntryType dlFileEntryType =
          DLFileEntryTypeLocalServiceUtil.addFileEntryType(
              TestPropsValues.getUserId(),
              group.getGroupId(),
              name,
              description,
              new long[] {ddmStructure.getStructureId()},
              serviceContext);

      Assert.assertEquals(name, dlFileEntryType.getName(LocaleUtil.US, true));
      Assert.assertEquals(description, dlFileEntryType.getDescription(LocaleUtil.US, true));
    } finally {
      LocaleThreadLocal.setSiteDefaultLocale(locale);
    }
  }
  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);
    }
  }
  protected void updateArticleType() throws Exception {
    if (!hasSelectedArticleTypes()) {
      return;
    }

    List<String> types = getArticleTypes();

    if (types.size() <= 0) {
      return;
    }

    Locale localeThreadLocalDefaultLocale = LocaleThreadLocal.getDefaultLocale();

    try {
      List<Company> companies = _companyLocalService.getCompanies();

      for (Company company : companies) {
        LocaleThreadLocal.setDefaultLocale(company.getLocale());

        Set<Locale> locales = LanguageUtil.getAvailableLocales(company.getGroupId());

        Locale defaultLocale =
            LocaleUtil.fromLanguageId(
                UpgradeProcessUtil.getDefaultLanguageId(company.getCompanyId()));

        Map<Locale, String> nameMap =
            LocalizationUtil.getLocalizationMap(locales, defaultLocale, "type");

        AssetVocabulary assetVocabulary =
            addAssetVocabulary(
                company.getGroupId(),
                company.getCompanyId(),
                "type",
                nameMap,
                new HashMap<Locale, String>());

        Map<String, Long> journalArticleTypesToAssetCategoryIds = new HashMap<>();

        for (String type : types) {
          AssetCategory assetCategory =
              addAssetCategory(
                  company.getGroupId(),
                  company.getCompanyId(),
                  type,
                  assetVocabulary.getVocabularyId());

          journalArticleTypesToAssetCategoryIds.put(type, assetCategory.getCategoryId());
        }

        updateArticles(company.getCompanyId(), journalArticleTypesToAssetCategoryIds);
      }
    } finally {
      LocaleThreadLocal.setDefaultLocale(localeThreadLocalDefaultLocale);
    }
  }
  public static void setCompanyId(long companyId) {
    if (_log.isDebugEnabled()) {
      _log.debug("setCompanyId " + companyId);
    }

    if (companyId > 0) {
      try {
        Company company = CompanyLocalServiceUtil.getCompany(companyId);

        LocaleThreadLocal.setLocale(company.getLocale());
        TimeZoneThreadLocal.setTimeZone(company.getTimeZone());
      } catch (Exception e) {
        _log.error(e, e);
      }

      _companyId.set(companyId);
    } else {
      LocaleThreadLocal.setLocale(null);
      TimeZoneThreadLocal.setTimeZone(null);

      _companyId.set(CompanyConstants.SYSTEM);
    }
  }
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (PortalUtil.isMultipartRequest(request)) {
      UploadServletRequest uploadServletRequest = new UploadServletRequestImpl(request);

      request = uploadServletRequest;
    }

    String path = GetterUtil.getString(request.getPathInfo());

    if ((!path.equals(StringPool.BLANK) && !path.equals(StringPool.SLASH))
        || (request.getParameter("discover") != null)) {

      Locale locale = PortalUtil.getLocale(request, response, true);

      LocaleThreadLocal.setThemeDisplayLocale(locale);

      super.service(request, response);

      return;
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Servlet context " + request.getContextPath());
    }

    String apiPath = PortalUtil.getPathMain() + "/portal/api/jsonws";

    HttpSession session = request.getSession();

    ServletContext servletContext = session.getServletContext();

    boolean remoteAccess = AccessControlThreadLocal.isRemoteAccess();

    try {
      AccessControlThreadLocal.setRemoteAccess(true);

      String contextPath = PortalContextLoaderListener.getPortalServletContextPath();

      if (servletContext.getContext(contextPath) != null) {
        if (!contextPath.equals(StringPool.SLASH) && apiPath.startsWith(contextPath)) {

          apiPath = apiPath.substring(contextPath.length());
        }

        RequestDispatcher requestDispatcher = request.getRequestDispatcher(apiPath);

        requestDispatcher.forward(request, response);
      } else {
        String servletContextPath = ContextPathUtil.getContextPath(servletContext);

        String redirectPath = "/api/jsonws?contextPath=" + HttpUtil.encodeURL(servletContextPath);

        response.sendRedirect(redirectPath);
      }
    } finally {
      AccessControlThreadLocal.setRemoteAccess(remoteAccess);
    }
  }
  public void setSiteDefaultLocale(Locale siteDefaultLocale) {
    _siteDefaultLocale = siteDefaultLocale;

    LocaleThreadLocal.setSiteDefaultLocale(siteDefaultLocale);
  }
  public void setLocale(Locale locale) {
    _locale = locale;

    LocaleThreadLocal.setThemeDisplayLocale(locale);
  }