@Test
  public void testFetchByPrimaryKeysWithOnePrimaryKey() throws Exception {
    Layout newLayout = addLayout();

    Set<Serializable> primaryKeys = new HashSet<Serializable>();

    primaryKeys.add(newLayout.getPrimaryKey());

    Map<Serializable, Layout> layouts = _persistence.fetchByPrimaryKeys(primaryKeys);

    Assert.assertEquals(1, layouts.size());
    Assert.assertEquals(newLayout, layouts.get(newLayout.getPrimaryKey()));
  }
  public static void updatePermissions(Layout layout, boolean addDefaultActionIds)
      throws Exception {

    long companyId = layout.getCompanyId();

    Role role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST);

    String[] actionIds = new String[0];

    String name = Layout.class.getName();
    int scope = ResourceConstants.SCOPE_INDIVIDUAL;
    String primKey = String.valueOf(layout.getPrimaryKey());

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.POWER_USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);

    if (addDefaultActionIds) {
      actionIds = new String[] {ActionKeys.VIEW};
    }

    role = RoleLocalServiceUtil.getRole(companyId, RoleConstants.USER);

    ResourcePermissionLocalServiceUtil.setResourcePermissions(
        companyId, name, scope, primKey, role.getRoleId(), actionIds);
  }
  @Test
  public void testFetchByPrimaryKeysWithMultiplePrimaryKeysWhereAllPrimaryKeysExist()
      throws Exception {
    Layout newLayout1 = addLayout();
    Layout newLayout2 = addLayout();

    Set<Serializable> primaryKeys = new HashSet<Serializable>();

    primaryKeys.add(newLayout1.getPrimaryKey());
    primaryKeys.add(newLayout2.getPrimaryKey());

    Map<Serializable, Layout> layouts = _persistence.fetchByPrimaryKeys(primaryKeys);

    Assert.assertEquals(2, layouts.size());
    Assert.assertEquals(newLayout1, layouts.get(newLayout1.getPrimaryKey()));
    Assert.assertEquals(newLayout2, layouts.get(newLayout2.getPrimaryKey()));
  }
  @Test
  public void testFetchByPrimaryKeysWithMultiplePrimaryKeysWhereSomePrimaryKeysExist()
      throws Exception {
    Layout newLayout = addLayout();

    long pk = RandomTestUtil.nextLong();

    Set<Serializable> primaryKeys = new HashSet<Serializable>();

    primaryKeys.add(newLayout.getPrimaryKey());
    primaryKeys.add(pk);

    Map<Serializable, Layout> layouts = _persistence.fetchByPrimaryKeys(primaryKeys);

    Assert.assertEquals(1, layouts.size());
    Assert.assertEquals(newLayout, layouts.get(newLayout.getPrimaryKey()));
  }
  @Test
  public void testFetchByPrimaryKeyExisting() throws Exception {
    Layout newLayout = addLayout();

    Layout existingLayout = _persistence.fetchByPrimaryKey(newLayout.getPrimaryKey());

    Assert.assertEquals(existingLayout, newLayout);
  }
  @Test
  public void testRemove() throws Exception {
    Layout newLayout = addLayout();

    _persistence.remove(newLayout);

    Layout existingLayout = _persistence.fetchByPrimaryKey(newLayout.getPrimaryKey());

    Assert.assertNull(existingLayout);
  }
  @Test
  public void testCreate() throws Exception {
    long pk = RandomTestUtil.nextLong();

    Layout layout = _persistence.create(pk);

    Assert.assertNotNull(layout);

    Assert.assertEquals(layout.getPrimaryKey(), pk);
  }
  private void _doPreparePortlet(HttpServletRequest request, Portlet portlet) throws Exception {

    User user = PortalUtil.getUser(request);
    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    long scopeGroupId = PortalUtil.getScopeGroupId(request, portlet.getPortletId());

    themeDisplay.setScopeGroupId(scopeGroupId);

    long siteGroupId = 0;

    if (layout.isTypeControlPanel()) {
      siteGroupId = PortalUtil.getSiteGroupId(scopeGroupId);
    } else {
      siteGroupId = PortalUtil.getSiteGroupId(layout.getGroupId());
    }

    themeDisplay.setSiteGroupId(siteGroupId);

    if (user != null) {
      HttpSession session = request.getSession();

      InvokerPortletImpl.clearResponse(
          session,
          layout.getPrimaryKey(),
          portlet.getPortletId(),
          LanguageUtil.getLanguageId(request));
    }

    processPublicRenderParameters(request, layout, portlet);

    if (themeDisplay.isLifecycleRender() || themeDisplay.isLifecycleResource()) {

      WindowState windowState =
          WindowStateFactory.getWindowState(ParamUtil.getString(request, "p_p_state"));

      if (layout.isTypeControlPanel()
          && ((windowState == null)
              || windowState.equals(WindowState.NORMAL)
              || Validator.isNull(windowState.toString()))) {

        windowState = WindowState.MAXIMIZED;
      }

      PortletMode portletMode =
          PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

      PortalUtil.updateWindowState(portlet.getPortletId(), user, layout, windowState, request);

      PortalUtil.updatePortletMode(portlet.getPortletId(), user, layout, portletMode, request);
    }
  }
  @Test
  public void testResetOriginalValues() throws Exception {
    if (!PropsValues.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
      return;
    }

    Layout newLayout = addLayout();

    _persistence.clearCache();

    LayoutModelImpl existingLayoutModelImpl =
        (LayoutModelImpl) _persistence.findByPrimaryKey(newLayout.getPrimaryKey());

    Assert.assertTrue(
        Validator.equals(
            existingLayoutModelImpl.getUuid(), existingLayoutModelImpl.getOriginalUuid()));
    Assert.assertEquals(
        existingLayoutModelImpl.getGroupId(), existingLayoutModelImpl.getOriginalGroupId());
    Assert.assertEquals(
        existingLayoutModelImpl.getPrivateLayout(),
        existingLayoutModelImpl.getOriginalPrivateLayout());

    Assert.assertEquals(
        existingLayoutModelImpl.getIconImageId(), existingLayoutModelImpl.getOriginalIconImageId());

    Assert.assertEquals(
        existingLayoutModelImpl.getGroupId(), existingLayoutModelImpl.getOriginalGroupId());
    Assert.assertEquals(
        existingLayoutModelImpl.getPrivateLayout(),
        existingLayoutModelImpl.getOriginalPrivateLayout());
    Assert.assertEquals(
        existingLayoutModelImpl.getLayoutId(), existingLayoutModelImpl.getOriginalLayoutId());

    Assert.assertEquals(
        existingLayoutModelImpl.getGroupId(), existingLayoutModelImpl.getOriginalGroupId());
    Assert.assertEquals(
        existingLayoutModelImpl.getPrivateLayout(),
        existingLayoutModelImpl.getOriginalPrivateLayout());
    Assert.assertTrue(
        Validator.equals(
            existingLayoutModelImpl.getFriendlyURL(),
            existingLayoutModelImpl.getOriginalFriendlyURL()));

    Assert.assertEquals(
        existingLayoutModelImpl.getGroupId(), existingLayoutModelImpl.getOriginalGroupId());
    Assert.assertEquals(
        existingLayoutModelImpl.getPrivateLayout(),
        existingLayoutModelImpl.getOriginalPrivateLayout());
    Assert.assertTrue(
        Validator.equals(
            existingLayoutModelImpl.getSourcePrototypeLayoutUuid(),
            existingLayoutModelImpl.getOriginalSourcePrototypeLayoutUuid()));
  }
  public String getJSON(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession();

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    Layout layout = themeDisplay.getLayout();

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    String portletId = ParamUtil.getString(request, "portletId");

    if (!PortletPermissionUtil.contains(
        permissionChecker, themeDisplay.getPlid(), portletId, ActionKeys.CONFIGURATION)) {

      return null;
    }

    String languageId = LanguageUtil.getLanguageId(request);
    String title = ParamUtil.getString(request, "title");

    PortletPreferences portletSetup =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

    portletSetup.setValue("portlet-setup-title-" + languageId, title);
    portletSetup.setValue("portlet-setup-use-custom-title", "true");

    portletSetup.store();

    InvokerPortletImpl.clearResponse(
        session, layout.getPrimaryKey(), portletId, LanguageUtil.getLanguageId(request));

    return null;
  }
  @Test
  public void testUpdateExisting() throws Exception {
    long pk = RandomTestUtil.nextLong();

    Layout newLayout = _persistence.create(pk);

    newLayout.setMvccVersion(RandomTestUtil.nextLong());

    newLayout.setUuid(RandomTestUtil.randomString());

    newLayout.setGroupId(RandomTestUtil.nextLong());

    newLayout.setCompanyId(RandomTestUtil.nextLong());

    newLayout.setUserId(RandomTestUtil.nextLong());

    newLayout.setUserName(RandomTestUtil.randomString());

    newLayout.setCreateDate(RandomTestUtil.nextDate());

    newLayout.setModifiedDate(RandomTestUtil.nextDate());

    newLayout.setPrivateLayout(RandomTestUtil.randomBoolean());

    newLayout.setLayoutId(RandomTestUtil.nextLong());

    newLayout.setParentLayoutId(RandomTestUtil.nextLong());

    newLayout.setName(RandomTestUtil.randomString());

    newLayout.setTitle(RandomTestUtil.randomString());

    newLayout.setDescription(RandomTestUtil.randomString());

    newLayout.setKeywords(RandomTestUtil.randomString());

    newLayout.setRobots(RandomTestUtil.randomString());

    newLayout.setType(RandomTestUtil.randomString());

    newLayout.setTypeSettings(RandomTestUtil.randomString());

    newLayout.setHidden(RandomTestUtil.randomBoolean());

    newLayout.setFriendlyURL(RandomTestUtil.randomString());

    newLayout.setIconImageId(RandomTestUtil.nextLong());

    newLayout.setThemeId(RandomTestUtil.randomString());

    newLayout.setColorSchemeId(RandomTestUtil.randomString());

    newLayout.setWapThemeId(RandomTestUtil.randomString());

    newLayout.setWapColorSchemeId(RandomTestUtil.randomString());

    newLayout.setCss(RandomTestUtil.randomString());

    newLayout.setPriority(RandomTestUtil.nextInt());

    newLayout.setLayoutPrototypeUuid(RandomTestUtil.randomString());

    newLayout.setLayoutPrototypeLinkEnabled(RandomTestUtil.randomBoolean());

    newLayout.setSourcePrototypeLayoutUuid(RandomTestUtil.randomString());

    _layouts.add(_persistence.update(newLayout));

    Layout existingLayout = _persistence.findByPrimaryKey(newLayout.getPrimaryKey());

    Assert.assertEquals(existingLayout.getMvccVersion(), newLayout.getMvccVersion());
    Assert.assertEquals(existingLayout.getUuid(), newLayout.getUuid());
    Assert.assertEquals(existingLayout.getPlid(), newLayout.getPlid());
    Assert.assertEquals(existingLayout.getGroupId(), newLayout.getGroupId());
    Assert.assertEquals(existingLayout.getCompanyId(), newLayout.getCompanyId());
    Assert.assertEquals(existingLayout.getUserId(), newLayout.getUserId());
    Assert.assertEquals(existingLayout.getUserName(), newLayout.getUserName());
    Assert.assertEquals(
        Time.getShortTimestamp(existingLayout.getCreateDate()),
        Time.getShortTimestamp(newLayout.getCreateDate()));
    Assert.assertEquals(
        Time.getShortTimestamp(existingLayout.getModifiedDate()),
        Time.getShortTimestamp(newLayout.getModifiedDate()));
    Assert.assertEquals(existingLayout.getPrivateLayout(), newLayout.getPrivateLayout());
    Assert.assertEquals(existingLayout.getLayoutId(), newLayout.getLayoutId());
    Assert.assertEquals(existingLayout.getParentLayoutId(), newLayout.getParentLayoutId());
    Assert.assertEquals(existingLayout.getName(), newLayout.getName());
    Assert.assertEquals(existingLayout.getTitle(), newLayout.getTitle());
    Assert.assertEquals(existingLayout.getDescription(), newLayout.getDescription());
    Assert.assertEquals(existingLayout.getKeywords(), newLayout.getKeywords());
    Assert.assertEquals(existingLayout.getRobots(), newLayout.getRobots());
    Assert.assertEquals(existingLayout.getType(), newLayout.getType());
    Assert.assertEquals(existingLayout.getTypeSettings(), newLayout.getTypeSettings());
    Assert.assertEquals(existingLayout.getHidden(), newLayout.getHidden());
    Assert.assertEquals(existingLayout.getFriendlyURL(), newLayout.getFriendlyURL());
    Assert.assertEquals(existingLayout.getIconImageId(), newLayout.getIconImageId());
    Assert.assertEquals(existingLayout.getThemeId(), newLayout.getThemeId());
    Assert.assertEquals(existingLayout.getColorSchemeId(), newLayout.getColorSchemeId());
    Assert.assertEquals(existingLayout.getWapThemeId(), newLayout.getWapThemeId());
    Assert.assertEquals(existingLayout.getWapColorSchemeId(), newLayout.getWapColorSchemeId());
    Assert.assertEquals(existingLayout.getCss(), newLayout.getCss());
    Assert.assertEquals(existingLayout.getPriority(), newLayout.getPriority());
    Assert.assertEquals(
        existingLayout.getLayoutPrototypeUuid(), newLayout.getLayoutPrototypeUuid());
    Assert.assertEquals(
        existingLayout.getLayoutPrototypeLinkEnabled(), newLayout.getLayoutPrototypeLinkEnabled());
    Assert.assertEquals(
        existingLayout.getSourcePrototypeLayoutUuid(), newLayout.getSourcePrototypeLayoutUuid());
  }
  protected Portlet processPortletRequest(
      HttpServletRequest request, HttpServletResponse response, String lifecycle) throws Exception {

    HttpSession session = request.getSession();

    long companyId = PortalUtil.getCompanyId(request);
    User user = PortalUtil.getUser(request);
    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    String portletId = ParamUtil.getString(request, "p_p_id");

    if (Validator.isNull(portletId)) {
      return null;
    }

    Portlet portlet = PortletLocalServiceUtil.getPortletById(companyId, portletId);

    if (portlet == null) {
      return null;
    }

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    themeDisplay.setScopeGroupId(PortalUtil.getScopeGroupId(request, portletId));

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    if (user != null) {
      InvokerPortletImpl.clearResponse(
          session, layout.getPrimaryKey(), portletId, LanguageUtil.getLanguageId(request));
    }

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    WindowState windowState =
        WindowStateFactory.getWindowState(ParamUtil.getString(request, "p_p_state"));

    if (layout.isTypeControlPanel()
        && ((windowState == null)
            || windowState.equals(WindowState.NORMAL)
            || (Validator.isNull(windowState.toString())))) {

      windowState = WindowState.MAXIMIZED;
    }

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portletId);

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

    processPublicRenderParameters(request, layout, portlet);

    if (lifecycle.equals(PortletRequest.ACTION_PHASE)) {
      String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);

      if (_log.isDebugEnabled()) {
        _log.debug("Content type " + contentType);
      }

      UploadServletRequest uploadRequest = null;

      try {
        if ((contentType != null) && (contentType.startsWith(ContentTypes.MULTIPART_FORM_DATA))) {

          PortletConfigImpl invokerPortletConfigImpl =
              (PortletConfigImpl) invokerPortlet.getPortletConfig();

          if (invokerPortlet.isStrutsPortlet()
              || ((invokerPortletConfigImpl != null) && (!invokerPortletConfigImpl.isWARFile()))) {

            uploadRequest = new UploadServletRequestImpl(request);

            request = uploadRequest;
          }
        }

        if (PropsValues.AUTH_TOKEN_CHECK_ENABLED && invokerPortlet.isCheckAuthToken()) {

          AuthTokenUtil.check(request);
        }

        ActionRequestImpl actionRequestImpl =
            ActionRequestFactory.create(
                request,
                portlet,
                invokerPortlet,
                portletContext,
                windowState,
                portletMode,
                portletPreferences,
                layout.getPlid());

        ActionResponseImpl actionResponseImpl =
            ActionResponseFactory.create(
                actionRequestImpl, response, portletId, user, layout, windowState, portletMode);

        actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);

        ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequestImpl);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);

        invokerPortlet.processAction(actionRequestImpl, actionResponseImpl);

        actionResponseImpl.transferHeaders(response);

        RenderParametersPool.put(
            request, layout.getPlid(), portletId, actionResponseImpl.getRenderParameterMap());

        List<LayoutTypePortlet> layoutTypePortlets = null;

        if (!actionResponseImpl.getEvents().isEmpty()) {
          if (PropsValues.PORTLET_EVENT_DISTRIBUTION_LAYOUT_SET) {
            layoutTypePortlets =
                getLayoutTypePortlets(layout.getGroupId(), layout.isPrivateLayout());
          } else {
            if (layout.isTypePortlet()) {
              LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

              layoutTypePortlets = new ArrayList<LayoutTypePortlet>();

              layoutTypePortlets.add(layoutTypePortlet);
            }
          }

          processEvents(actionRequestImpl, actionResponseImpl, layoutTypePortlets);

          actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);
        }
      } finally {
        if (uploadRequest != null) {
          uploadRequest.cleanUp();
        }

        ServiceContextThreadLocal.popServiceContext();
      }
    } else if (lifecycle.equals(PortletRequest.RENDER_PHASE)
        || lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {

      PortalUtil.updateWindowState(portletId, user, layout, windowState, request);

      PortalUtil.updatePortletMode(portletId, user, layout, portletMode, request);
    }

    if (lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {
      PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

      String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portletId);

      portletDisplay.setId(portletId);
      portletDisplay.setRootPortletId(portlet.getRootPortletId());
      portletDisplay.setInstanceId(portlet.getInstanceId());
      portletDisplay.setResourcePK(portletPrimaryKey);
      portletDisplay.setPortletName(portletConfig.getPortletName());
      portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portletId));

      ResourceRequestImpl resourceRequestImpl =
          ResourceRequestFactory.create(
              request,
              portlet,
              invokerPortlet,
              portletContext,
              windowState,
              portletMode,
              portletPreferences,
              layout.getPlid());

      ResourceResponseImpl resourceResponseImpl =
          ResourceResponseFactory.create(resourceRequestImpl, response, portletId, companyId);

      resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

      try {
        ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequestImpl);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);

        invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);
      } finally {
        ServiceContextThreadLocal.popServiceContext();
      }
    }

    return portlet;
  }
  protected void processEvent(
      PortletRequestImpl portletRequestImpl,
      StateAwareResponseImpl stateAwareResponseImpl,
      List<LayoutTypePortlet> layoutTypePortlets,
      LayoutTypePortlet layoutTypePortlet,
      Portlet portlet,
      Event event)
      throws Exception {

    HttpServletRequest request = portletRequestImpl.getHttpServletRequest();
    HttpServletResponse response = stateAwareResponseImpl.getHttpServletResponse();
    HttpSession session = request.getSession();

    String portletId = portlet.getPortletId();

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    WindowState windowState = null;

    if (layoutTypePortlet.hasStateMaxPortletId(portletId)) {
      windowState = WindowState.MAXIMIZED;
    } else if (layoutTypePortlet.hasStateMinPortletId(portletId)) {
      windowState = WindowState.MINIMIZED;
    } else {
      windowState = WindowState.NORMAL;
    }

    PortletMode portletMode = null;

    if (layoutTypePortlet.hasModeAboutPortletId(portletId)) {
      portletMode = LiferayPortletMode.ABOUT;
    } else if (layoutTypePortlet.hasModeConfigPortletId(portletId)) {
      portletMode = LiferayPortletMode.CONFIG;
    } else if (layoutTypePortlet.hasModeEditPortletId(portletId)) {
      portletMode = PortletMode.EDIT;
    } else if (layoutTypePortlet.hasModeEditDefaultsPortletId(portletId)) {
      portletMode = LiferayPortletMode.EDIT_DEFAULTS;
    } else if (layoutTypePortlet.hasModeEditGuestPortletId(portletId)) {
      portletMode = LiferayPortletMode.EDIT_GUEST;
    } else if (layoutTypePortlet.hasModeHelpPortletId(portletId)) {
      portletMode = PortletMode.HELP;
    } else if (layoutTypePortlet.hasModePreviewPortletId(portletId)) {
      portletMode = LiferayPortletMode.PREVIEW;
    } else if (layoutTypePortlet.hasModePrintPortletId(portletId)) {
      portletMode = LiferayPortletMode.PRINT;
    } else {
      portletMode = PortletMode.VIEW;
    }

    User user = stateAwareResponseImpl.getUser();
    Layout layout = stateAwareResponseImpl.getLayout();

    PortletPreferences portletPreferences = portletRequestImpl.getPreferencesImpl();

    EventRequestImpl eventRequestImpl =
        EventRequestFactory.create(
            request,
            portlet,
            invokerPortlet,
            portletContext,
            windowState,
            portletMode,
            portletPreferences,
            layoutTypePortlet.getLayout().getPlid());

    eventRequestImpl.setEvent(serializeEvent(event, invokerPortlet.getPortletClassLoader()));

    EventResponseImpl eventResponseImpl =
        EventResponseFactory.create(eventRequestImpl, response, portletId, user, layout);

    eventRequestImpl.defineObjects(portletConfig, eventResponseImpl);

    try {
      try {
        InvokerPortletImpl.clearResponse(
            session,
            layout.getPrimaryKey(),
            portletId,
            LanguageUtil.getLanguageId(eventRequestImpl));

        invokerPortlet.processEvent(eventRequestImpl, eventResponseImpl);

        if (eventResponseImpl.isCalledSetRenderParameter()) {
          Map<String, String[]> renderParameterMap = new HashMap<String, String[]>();

          MapUtil.copy(eventResponseImpl.getRenderParameterMap(), renderParameterMap);

          RenderParametersPool.put(request, layout.getPlid(), portletId, renderParameterMap);
        }
      } catch (UnavailableException ue) {
        throw ue;
      }

      processEvents(eventRequestImpl, eventResponseImpl, layoutTypePortlets);
    } finally {
      eventRequestImpl.cleanUp();
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext,
      Element ruleGroupInstanceElement,
      String path,
      MDRRuleGroupInstance ruleGroupInstance)
      throws Exception {

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

    String ruleGroupPath =
        StagedModelPathUtil.getPath(
            portletDataContext, MDRRuleGroup.class.getName(), ruleGroupInstance.getRuleGroupId());

    MDRRuleGroup ruleGroup = (MDRRuleGroup) portletDataContext.getZipEntryAsObject(ruleGroupPath);

    StagedModelDataHandlerUtil.importStagedModel(
        portletDataContext, ruleGroupInstanceElement, ruleGroupPath, ruleGroup);

    Map<Long, Long> ruleGroupIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MDRRuleGroup.class);

    Long ruleGroupId =
        MapUtil.getLong(
            ruleGroupIds, ruleGroupInstance.getRuleGroupId(), ruleGroupInstance.getRuleGroupId());

    long classPK = 0;

    String layoutUuid = ruleGroupInstanceElement.attributeValue("layout-uuid");

    try {
      if (Validator.isNotNull(layoutUuid)) {
        Layout layout =
            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
                layoutUuid,
                portletDataContext.getScopeGroupId(),
                portletDataContext.isPrivateLayout());

        classPK = layout.getPrimaryKey();
      } else {
        LayoutSet layoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                portletDataContext.getScopeGroupId(), portletDataContext.isPrivateLayout());

        classPK = layoutSet.getLayoutSetId();
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        StringBundler sb = new StringBundler(5);

        sb.append("Layout ");
        sb.append(layoutUuid);
        sb.append(" is missing for rule group instance ");
        sb.append(ruleGroupInstance.getRuleGroupInstanceId());
        sb.append(", skipping this rule group instance.");

        _log.warn(sb.toString());
      }

      return;
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(
            ruleGroupInstanceElement, ruleGroupInstance, MDRPortletDataHandler.NAMESPACE);

    serviceContext.setUserId(userId);

    MDRRuleGroupInstance importedRuleGroupInstance = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRRuleGroupInstance existingMDRRuleGroupInstance =
          MDRRuleGroupInstanceUtil.fetchByUUID_G(
              ruleGroupInstance.getUuid(), portletDataContext.getScopeGroupId());

      if (existingMDRRuleGroupInstance == null) {
        serviceContext.setUuid(ruleGroupInstance.getUuid());

        importedRuleGroupInstance =
            MDRRuleGroupInstanceLocalServiceUtil.addRuleGroupInstance(
                portletDataContext.getScopeGroupId(),
                ruleGroupInstance.getClassName(),
                classPK,
                ruleGroupId,
                ruleGroupInstance.getPriority(),
                serviceContext);
      } else {
        importedRuleGroupInstance =
            MDRRuleGroupInstanceLocalServiceUtil.updateRuleGroupInstance(
                existingMDRRuleGroupInstance.getRuleGroupInstanceId(),
                ruleGroupInstance.getPriority());
      }
    } else {
      importedRuleGroupInstance =
          MDRRuleGroupInstanceLocalServiceUtil.addRuleGroupInstance(
              portletDataContext.getScopeGroupId(),
              ruleGroupInstance.getClassName(),
              classPK,
              ruleGroupId,
              ruleGroupInstance.getPriority(),
              serviceContext);
    }

    portletDataContext.importClassedModel(
        ruleGroupInstance, importedRuleGroupInstance, MDRPortletDataHandler.NAMESPACE);
  }