@Test
  public void testAddFileEntryType() throws Exception {
    ServiceContext serviceContext = new ServiceContext();

    byte[] testFileBytes = FileUtil.getBytes(getClass(), _TEST_DDM_STRUCTURE);

    serviceContext.setAttribute("xsd", new String(testFileBytes));

    User user = TestPropsValues.getUser();

    serviceContext.setLanguageId(LocaleUtil.toLanguageId(user.getLocale()));

    DLFileEntryType dlFileEntryType =
        DLFileEntryTypeLocalServiceUtil.addFileEntryType(
            TestPropsValues.getUserId(),
            _group.getGroupId(),
            "Test Structure",
            StringPool.BLANK,
            new long[0],
            serviceContext);

    List<DDMStructure> ddmStructures = dlFileEntryType.getDDMStructures();

    Assert.assertEquals(1, ddmStructures.size());

    DDMStructure ddmStructure = ddmStructures.get(0);

    Locale[] availableLocales = LocaleUtil.fromLanguageIds(ddmStructure.getAvailableLanguageIds());

    boolean hasDefaultLocale = ArrayUtil.contains(availableLocales, LocaleUtil.getSiteDefault());

    Assert.assertTrue(hasDefaultLocale);

    boolean hasHungarianLocale = ArrayUtil.contains(availableLocales, LocaleUtil.HUNGARY);

    Assert.assertTrue(hasHungarianLocale);

    boolean hasUserLocale = ArrayUtil.contains(availableLocales, user.getLocale());

    Assert.assertTrue(hasUserLocale);

    DLFileEntryTypeLocalServiceUtil.deleteDLFileEntryType(dlFileEntryType);
  }
  protected ThemeDisplay getThemeDisplay(SecurityToken securityToken) throws Exception {

    long userIdLong = GetterUtil.getLong(securityToken.getViewerId());

    User user = UserLocalServiceUtil.getUserById(userIdLong);

    Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId());

    ThemeDisplay themeDisplay = new ThemeDisplay();

    themeDisplay.setCompany(company);
    themeDisplay.setLocale(user.getLocale());
    themeDisplay.setUser(user);

    return themeDisplay;
  }
Exemplo n.º 3
0
  protected long loginUser(
      HttpServletRequest request,
      HttpServletResponse response,
      long companyId,
      long userId,
      String remoteUser)
      throws PortalException, SystemException {

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

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      userId = JAASHelper.getJaasUserId(companyId, remoteUser);
    } else {
      userId = GetterUtil.getLong(remoteUser);
    }

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE, request, response);

    User user = UserLocalServiceUtil.getUserById(userId);

    if (PropsValues.USERS_UPDATE_LAST_LOGIN) {
      UserLocalServiceUtil.updateLastLogin(userId, request.getRemoteAddr());
    }

    HttpSession session = request.getSession();

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(WebKeys.USER_ID, new Long(userId));
    session.setAttribute(Globals.LOCALE_KEY, user.getLocale());

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, request, response);

    return userId;
  }
  protected void sendEmail(long mbMessageId, ThemeDisplay themeDisplay) throws Exception {

    MBMessage mbMessage = MBMessageLocalServiceUtil.getMBMessage(mbMessageId);

    User sender = UserLocalServiceUtil.getUser(mbMessage.getUserId());

    Company company = CompanyLocalServiceUtil.getCompany(sender.getCompanyId());

    InternetAddress from = new InternetAddress(company.getEmailAddress());

    String subject =
        StringUtil.read(
            PrivateMessagingPortlet.class.getResourceAsStream(
                "dependencies/notification_message_subject.tmpl"));

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$COMPANY_NAME$]", "[$FROM_NAME$]"},
            new String[] {company.getName(), sender.getFullName()});

    String body =
        StringUtil.read(
            PrivateMessagingPortlet.class.getResourceAsStream(
                "dependencies/notification_message_body.tmpl"));

    long portraitId = sender.getPortraitId();
    String tokenId = WebServerServletTokenUtil.getToken(sender.getPortraitId());
    String portraitURL =
        themeDisplay.getPortalURL()
            + themeDisplay.getPathImage()
            + "/user_"
            + (sender.isFemale() ? "female" : "male")
            + "_portrait?img_id="
            + portraitId
            + "&t="
            + tokenId;

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$BODY$]", "[$COMPANY_NAME$]", "[$FROM_AVATAR$]",
              "[$FROM_NAME$]", "[$FROM_PROFILE_URL$]", "[$SUBJECT$]"
            },
            new String[] {
              mbMessage.getBody(),
              company.getName(),
              portraitURL,
              sender.getFullName(),
              sender.getDisplayURL(themeDisplay),
              mbMessage.getSubject()
            });

    List<UserThread> userThreads =
        UserThreadLocalServiceUtil.getMBThreadUserThreads(mbMessage.getThreadId());

    for (UserThread userThread : userThreads) {
      if ((userThread.getUserId() == mbMessage.getUserId())
          && UserNotificationManagerUtil.isDeliver(
              userThread.getUserId(),
              PortletKeys.PRIVATE_MESSAGING,
              PrivateMessagingConstants.NEW_MESSAGE,
              0,
              UserNotificationDeliveryConstants.TYPE_EMAIL)) {

        continue;
      }

      User recipient = UserLocalServiceUtil.getUser(userThread.getUserId());

      String threadURL = getThreadURL(recipient, mbMessage.getThreadId(), themeDisplay);

      if (Validator.isNull(threadURL)) {
        continue;
      }

      InternetAddress to = new InternetAddress(recipient.getEmailAddress());

      Format dateFormatDateTime =
          FastDateFormatFactoryUtil.getDateTime(
              FastDateFormatConstants.LONG,
              FastDateFormatConstants.SHORT,
              recipient.getLocale(),
              recipient.getTimeZone());

      String userThreadBody =
          StringUtil.replace(
              body,
              new String[] {"[$SENT_DATE$]", "[$THREAD_URL$]"},
              new String[] {dateFormatDateTime.format(mbMessage.getCreateDate()), threadURL});

      MailMessage mailMessage = new MailMessage(from, to, subject, userThreadBody, true);

      MailServiceUtil.sendEmail(mailMessage);
    }
  }
Exemplo n.º 5
0
  protected void importEvent(
      PortletDataContext portletDataContext, Element eventElement, CalEvent event)
      throws Exception {

    long userId = portletDataContext.getUserId(event.getUserUuid());

    Date startDate = event.getStartDate();

    int startDateMonth = 0;
    int startDateDay = 0;
    int startDateYear = 0;
    int startDateHour = 0;
    int startDateMinute = 0;

    if (startDate != null) {
      Locale locale = null;
      TimeZone timeZone = null;

      if (event.getTimeZoneSensitive()) {
        User user = UserLocalServiceUtil.getUser(userId);

        locale = user.getLocale();
        timeZone = user.getTimeZone();
      } else {
        locale = LocaleUtil.getDefault();
        timeZone = TimeZoneUtil.getTimeZone(StringPool.UTC);
      }

      Calendar startCal = CalendarFactoryUtil.getCalendar(timeZone, locale);

      startCal.setTime(startDate);

      startDateMonth = startCal.get(Calendar.MONTH);
      startDateDay = startCal.get(Calendar.DATE);
      startDateYear = startCal.get(Calendar.YEAR);
      startDateHour = startCal.get(Calendar.HOUR);
      startDateMinute = startCal.get(Calendar.MINUTE);

      if (startCal.get(Calendar.AM_PM) == Calendar.PM) {
        startDateHour += 12;
      }
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(eventElement, event, NAMESPACE);

    CalEvent importedEvent = null;

    if (portletDataContext.isDataStrategyMirror()) {
      CalEvent existingEvent =
          CalEventUtil.fetchByUUID_G(event.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEvent == null) {
        serviceContext.setUuid(event.getUuid());

        importedEvent =
            CalEventLocalServiceUtil.addEvent(
                userId,
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      } else {
        importedEvent =
            CalEventLocalServiceUtil.updateEvent(
                userId,
                existingEvent.getEventId(),
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      }
    } else {
      importedEvent =
          CalEventLocalServiceUtil.addEvent(
              userId,
              event.getTitle(),
              event.getDescription(),
              event.getLocation(),
              startDateMonth,
              startDateDay,
              startDateYear,
              startDateHour,
              startDateMinute,
              event.getDurationHour(),
              event.getDurationMinute(),
              event.isAllDay(),
              event.isTimeZoneSensitive(),
              event.getType(),
              event.getRepeating(),
              event.getRecurrenceObj(),
              event.getRemindBy(),
              event.getFirstReminder(),
              event.getSecondReminder(),
              serviceContext);
    }

    portletDataContext.importClassedModel(event, importedEvent, NAMESPACE);
  }
Exemplo n.º 6
0
  @SuppressWarnings("unchecked")
  protected void doEditMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = request.getRequestURI();
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User backendUser = null;
    try {
      backendUser = com.liferay.portal.util.PortalUtil.getUser(request);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", String.valueOf(id.getInode()));
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasAddChildrenPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, backendUser);
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, backendUser);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser);
    context.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", new Boolean(hasAddChildrenPermOverHTMLPage));
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));
    context.put("canAddForm", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));
    context.put("canViewDiff", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
                htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser)
            && portletAPI.hasTemplateManagerRights(backendUser);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    if (cmsTemplate == null) { // DOTCMS-4051
      cmsTemplate = new com.dotmarketing.portlets.templates.model.Template();
      Logger.debug(VelocityServlet.class, "HTMLPAGE TEMPLATE NOT FOUND");
    }

    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, true, false, host);
    // added to show tabs
    context.put("previewPage", "1");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      boolean hasWritePermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, backendUser, false)
              && portletAPI.hasContainerManagerRights(backendUser);
      boolean hasReadPermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_READ, backendUser, false);
      context.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer);
      if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true);
      else
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer);

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);
      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, backendUser);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      List<Contentlet> contentlets = null;

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(),
                  idenContainer.getInode(),
                  sort,
                  true,
                  -1,
                  backendUser,
                  true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());

        } else {
          String luceneQuery = c.getLuceneQuery();
          int limit = c.getMaxContentlets();
          String sortBy = c.getSortContentletsBy();
          int offset = 0;
          contentlets = conAPI.search(luceneQuery, limit, offset, sortBy, backendUser, true);
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, backendUser);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }
        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
        // ### Add the structure fake contentlet ###
        if (contentletList.size() == 0) {
          Structure structure = ContainerFactory.getContainerStructure(c);
          contentletList.add(structure.getInode() + "");
          // sets contentletlist with all the files to load per
          // container
          context.remove("contentletList" + c.getIdentifier());
          context.remove("totalSize" + c.getIdentifier());
          // http://jira.dotmarketing.net/browse/DOTCMS-2876
          context.put("contentletList" + c.getIdentifier(), new long[0]);
          context.put("totalSize" + c.getIdentifier(), 0);
        }
        // ### END Add the structure fake contentlet ###

      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), backendUser.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      // Return a resource not found right away if the page is not found,
      // not try to load the frames
      if (!InodeUtils.isSet(templateIdentifier.getInode())) throw new ResourceNotFoundException("");
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {
      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
Exemplo n.º 7
0
  @SuppressWarnings("unchecked")
  public void doPreviewMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration());
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User user = null;
    HttpSession session = request.getSession(false);
    try {
      if (session != null)
        user =
            (com.liferay.portal.model.User)
                session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", id.getInode());
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage) APILocator.getVersionableAPI().findWorkingVersion(id, user, true);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user);
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
            htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, user, true);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, false, true, host);
    context.put("previewPage", "2");
    context.put("livePage", "0");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      context.put(
          "EDIT_CONTAINER_PERMISSION" + c.getIdentifier(),
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, true));

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);

      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, user, true);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      List<Contentlet> contentlets = null;

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, user, true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null && contentlets.size() > 0) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user, true);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }

        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), user.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {

      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
  protected void notify(
      long userId, MembershipRequest membershipRequest, String subjectProperty, String bodyProperty)
      throws IOException, PortalException, SystemException {

    Company company = companyPersistence.findByPrimaryKey(membershipRequest.getCompanyId());

    Group group = groupPersistence.findByPrimaryKey(membershipRequest.getGroupId());

    User user = userPersistence.findByPrimaryKey(userId);
    User requestUser = userPersistence.findByPrimaryKey(membershipRequest.getUserId());

    String fromName =
        PrefsPropsUtil.getString(
            membershipRequest.getCompanyId(), PropsKeys.COMMUNITIES_EMAIL_FROM_NAME);

    String fromAddress =
        PrefsPropsUtil.getString(
            membershipRequest.getCompanyId(), PropsKeys.COMMUNITIES_EMAIL_FROM_ADDRESS);

    String toName = user.getFullName();
    String toAddress = user.getEmailAddress();

    String subject = PrefsPropsUtil.getContent(membershipRequest.getCompanyId(), subjectProperty);

    String body = PrefsPropsUtil.getContent(membershipRequest.getCompanyId(), bodyProperty);

    String statusKey = null;

    if (membershipRequest.getStatusId() == MembershipRequestConstants.STATUS_APPROVED) {

      statusKey = "approved";
    } else if (membershipRequest.getStatusId() == MembershipRequestConstants.STATUS_DENIED) {

      statusKey = "denied";
    } else {
      statusKey = "pending";
    }

    subject =
        StringUtil.replace(
            subject,
            new String[] {
              "[$COMMUNITY_NAME$]",
              "[$COMPANY_ID$]",
              "[$COMPANY_MX$]",
              "[$COMPANY_NAME$]",
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$PORTAL_URL$]",
              "[$REQUEST_USER_ADDRESS$]",
              "[$REQUEST_USER_NAME$]",
              "[$STATUS$]",
              "[$TO_NAME$]",
              "[$USER_ADDRESS$]",
              "[$USER_NAME$]",
            },
            new String[] {
              group.getName(),
              String.valueOf(company.getCompanyId()),
              company.getMx(),
              company.getName(),
              fromAddress,
              fromName,
              company.getVirtualHost(),
              requestUser.getEmailAddress(),
              requestUser.getFullName(),
              LanguageUtil.get(user.getLocale(), statusKey),
              toName,
              user.getEmailAddress(),
              user.getFullName()
            });

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$COMMENTS$]",
              "[$COMMUNITY_NAME$]",
              "[$COMPANY_ID$]",
              "[$COMPANY_MX$]",
              "[$COMPANY_NAME$]",
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$PORTAL_URL$]",
              "[$REPLY_COMMENTS$]",
              "[$REQUEST_USER_NAME$]",
              "[$REQUEST_USER_ADDRESS$]",
              "[$STATUS$]",
              "[$TO_NAME$]",
              "[$USER_ADDRESS$]",
              "[$USER_NAME$]",
            },
            new String[] {
              membershipRequest.getComments(),
              group.getName(),
              String.valueOf(company.getCompanyId()),
              company.getMx(),
              company.getName(),
              fromAddress,
              fromName,
              company.getVirtualHost(),
              membershipRequest.getReplyComments(),
              requestUser.getFullName(),
              requestUser.getEmailAddress(),
              LanguageUtil.get(user.getLocale(), statusKey),
              toName,
              user.getEmailAddress(),
              user.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage message = new MailMessage(from, to, subject, body, true);

    mailService.sendEmail(message);
  }