protected void copyPreferences(String sourcePortletId, String targetPortletId) {

    Layout layout = getLayout();

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), permissionChecker.getUserId(), layout, sourcePortletId, false);

      javax.portlet.PortletPreferences sourcePortletPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

      portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), permissionChecker.getUserId(), layout, targetPortletId, false);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePortletPreferences);
    } catch (Exception e) {
    }
  }
  protected PortletPreferences getPortletPreferences(
      long companyId, long ownerId, int ownerType, long plid, String serviceName)
      throws PortalException {

    PortletPreferences portletPreferences = null;

    try {
      if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED)
          || (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY)
          || (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP)) {

        portletPreferences =
            PortletPreferencesLocalServiceUtil.getPortletPreferences(
                ownerId, ownerType, LayoutConstants.DEFAULT_PLID, serviceName);
      } else {
        portletPreferences =
            PortletPreferencesLocalServiceUtil.getPortletPreferences(
                ownerId, ownerType, plid, serviceName);
      }
    } catch (NoSuchPortletPreferencesException nsppe) {
      portletPreferences =
          PortletPreferencesLocalServiceUtil.addPortletPreferences(
              companyId, ownerId, ownerType, plid, serviceName, null, null);
    }

    return portletPreferences;
  }
  @Override
  public Map<Long, PortletPreferences> getPortletSetupMap(
      long companyId,
      long groupId,
      long ownerId,
      int ownerType,
      String portletId,
      boolean privateLayout) {

    Map<Long, PortletPreferences> portletSetupMap = new HashMap<Long, PortletPreferences>();

    List<com.liferay.portal.model.PortletPreferences> portletPreferencesList =
        PortletPreferencesLocalServiceUtil.getPortletPreferences(
            companyId, groupId, ownerId, ownerType, portletId, privateLayout);

    for (com.liferay.portal.model.PortletPreferences portletPreferences : portletPreferencesList) {

      PortletPreferences portletSetup =
          PortletPreferencesLocalServiceUtil.getPreferences(
              companyId, ownerId, ownerType, portletPreferences.getPlid(), portletId);

      portletSetupMap.put(portletPreferences.getPlid(), portletSetup);
    }

    return portletSetupMap;
  }
  protected void copyPreferences(long userId, String sourcePortletId, String targetPortletId) {

    Layout layout = getLayout();

    try {
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), 0, layout, sourcePortletId, false);

      javax.portlet.PortletPreferences sourcePortletPreferences =
          PortletPreferencesLocalServiceUtil.getStrictPreferences(portletPreferencesIds);

      portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), userId, layout, targetPortletId, false);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePortletPreferences);
    } catch (Exception e) {
    }
  }
  protected void deletePortletSetup(String portletId) {
    try {
      List<PortletPreferences> portletPreferencesList =
          PortletPreferencesLocalServiceUtil.getPortletPreferences(getPlid(), portletId);

      for (PortletPreferences portletPreferences : portletPreferencesList) {

        PortletPreferencesLocalServiceUtil.deletePortletPreferences(
            portletPreferences.getPortletPreferencesId());
      }
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
  private ModifiableSettings _getModifiableSettings() {
    if (_portletPreferencesSettings != null) {
      return _portletPreferencesSettings;
    }

    PortletPreferences portletPreferences = null;

    try {
      long ownerId = _portletItem.getPortletItemId();
      int ownerType = PortletKeys.PREFS_OWNER_TYPE_ARCHIVED;
      long plid = 0;
      String portletId = _portletItem.getPortletId();

      portletPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(
              _portletItem.getCompanyId(),
              ownerId,
              ownerType,
              plid,
              PortletConstants.getRootPortletId(portletId));
    } catch (SystemException se) {
      throw new RuntimeException("Unable to load settings", se);
    }

    _portletPreferencesSettings = new PortletPreferencesSettings(portletPreferences);

    return _portletPreferencesSettings;
  }
Exemple #7
0
  public static String getUserPreference(
      long userId, long plid, String portletId, String preferenceName) {
    String _preference = StringPool.BLANK;

    PortletPreferences preferences = null;
    try {
      preferences =
          PortletPreferencesLocalServiceUtil.getPortletPreferences(
              userId, PortletKeys.PREFS_OWNER_TYPE_USER, plid, portletId);
    } catch (PortalException e) {
      // ignore
    } catch (SystemException e) {
      // ignore
    }

    if (Validator.isNull(preferences)) return _preference;

    Document document = null;
    try {
      document = SAXReaderUtil.read(preferences.getPreferences());
    } catch (DocumentException e) {
      e.printStackTrace();
    }

    for (Iterator<Element> itr = document.getRootElement().elementIterator("preference");
        itr.hasNext(); ) {
      Element preference = (Element) itr.next();

      if (preference.element("name").getText().equalsIgnoreCase(preferenceName)) {
        _preference = preference.element("value").getText();
      }
    }

    return _preference;
  }
  protected void importServicePortletPreferences(
      PortletDataContext portletDataContext, Element serviceElement) throws PortalException {

    long ownerId = GetterUtil.getLong(serviceElement.attributeValue("owner-id"));
    int ownerType = GetterUtil.getInteger(serviceElement.attributeValue("owner-type"));
    String serviceName = serviceElement.attributeValue("service-name");

    PortletPreferences portletPreferences =
        getPortletPreferences(
            portletDataContext.getCompanyId(),
            ownerId,
            ownerType,
            LayoutConstants.DEFAULT_PLID,
            serviceName);

    for (Attribute attribute : serviceElement.attributes()) {
      serviceElement.remove(attribute);
    }

    String xml = serviceElement.asXML();

    portletPreferences.setPreferences(xml);

    PortletPreferencesLocalServiceUtil.updatePortletPreferences(portletPreferences);
  }
  protected void importPortletData(
      PortletDataContext portletDataContext,
      String portletId,
      long plid,
      Element portletDataElement)
      throws Exception {

    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;

    PortletPreferences portletPreferences =
        PortletPreferencesUtil.fetchByO_O_P_P(ownerId, ownerType, plid, portletId);

    if (portletPreferences == null) {
      portletPreferences = new com.liferay.portal.model.impl.PortletPreferencesImpl();
    }

    String xml =
        importPortletData(portletDataContext, portletId, portletPreferences, portletDataElement);

    if (xml != null) {
      PortletPreferencesLocalServiceUtil.updatePreferences(
          ownerId, ownerType, plid, portletId, xml);
    }
  }
  @Override
  public PortletPreferences getPortletPreferences(HttpServletRequest request, String portletId)
      throws PortalException {

    PortletPreferencesIds portletPreferencesIds = getPortletPreferencesIds(request, portletId);

    return PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);
  }
  @Override
  public void checkControlPanelPortletPreferences(ThemeDisplay themeDisplay, Portlet portlet)
      throws PortalException {

    Layout layout = themeDisplay.getLayout();

    Group group = layout.getGroup();

    if (!group.isControlPanel()) {
      return;
    }

    String portletId = portlet.getPortletId();

    boolean hasControlPanelAccessPermission =
        PortletPermissionUtil.hasControlPanelAccessPermission(
            themeDisplay.getPermissionChecker(), themeDisplay.getScopeGroupId(), portletId);

    if (!hasControlPanelAccessPermission) {
      return;
    }

    PortletPreferences portletSetup = getStrictLayoutPortletSetup(layout, portletId);

    if (portletSetup instanceof StrictPortletPreferencesImpl) {
      getLayoutPortletSetup(layout, portletId);
    }

    if (portlet.isInstanceable()) {
      return;
    }

    PortletPreferencesIds portletPreferencesIds =
        getPortletPreferencesIds(
            themeDisplay.getScopeGroupId(), themeDisplay.getUserId(), layout, portletId, false);

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.fetchPreferences(portletPreferencesIds);

    if (portletPreferences != null) {
      return;
    }

    PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);
  }
  protected javax.portlet.PortletPreferences getPortletPreferences(
      long companyId, long plid, String portletId) throws Exception {

    return PortletPreferencesLocalServiceUtil.getPreferences(
        companyId,
        PortletKeys.PREFS_OWNER_ID_DEFAULT,
        PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
        plid,
        portletId);
  }
  @Override
  public boolean hasPortletId(String portletId, boolean strict) throws PortalException {

    List<String> columns = getColumns();

    for (String columnId : columns) {
      if (hasNonstaticPortletId(columnId, portletId)) {
        return true;
      }

      if (hasStaticPortletId(columnId, portletId)) {
        return true;
      }
    }

    Layout layout = getLayout();

    if (layout.isTypeControlPanel()) {
      return false;
    }

    if (isCustomizable() && isCustomizedView()) {
      LayoutTypePortletImpl defaultLayoutTypePortletImpl = getDefaultLayoutTypePortletImpl();

      if (defaultLayoutTypePortletImpl.hasNonstaticPortletId(portletId)) {
        return false;
      }
    }

    if (!strict
        && ((PortletPreferencesLocalServiceUtil.getPortletPreferencesCount(
                    PortletKeys.PREFS_OWNER_TYPE_LAYOUT, layout.getPlid(), portletId)
                > 0)
            || (PortletPreferencesLocalServiceUtil.getPortletPreferencesCount(
                    PortletKeys.PREFS_OWNER_TYPE_USER, layout.getPlid(), portletId)
                > 0))) {

      return true;
    }

    return false;
  }
  private long _getPortletPreferencesId(long plid, String portletId)
      throws PortalException, SystemException {

    com.liferay.portal.model.PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPortletPreferences(
            PortletKeys.PREFS_OWNER_ID_DEFAULT,
            PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
            plid,
            portletId);

    return portletPreferences.getPortletPreferencesId();
  }
  protected PortletPreferences updatePortletPreferences(
      long plid, String portletId, javax.portlet.PortletPreferences jxPreferences)
      throws Exception {

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.updatePreferences(
            PortletKeys.PREFS_OWNER_ID_DEFAULT,
            PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
            plid,
            portletId,
            jxPreferences);

    return portletPreferences;
  }
  protected PortletPreferences getPortletInstancePortletPreferences(
      Layout layout, String portletId) {

    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;

    if (PortletConstants.hasUserId(portletId)) {
      ownerId = PortletConstants.getUserId(portletId);
      ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
    }

    return PortletPreferencesLocalServiceUtil.getStrictPreferences(
        layout.getCompanyId(), ownerId, ownerType, layout.getPlid(), portletId);
  }
  @Test
  public void testCleanUpLayoutRevisionPortletPreferences() throws Exception {
    LayoutRevision layoutRevision = getLayoutRevision();

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.addPortletPreferences(
            TestPropsValues.getCompanyId(),
            TestPropsValues.getUserId(),
            0,
            layoutRevision.getLayoutRevisionId(),
            RandomTestUtil.randomString(),
            new PortletImpl(),
            StringPool.BLANK);

    Assert.assertNotNull(portletPreferences);

    doVerify();

    portletPreferences =
        PortletPreferencesLocalServiceUtil.fetchPortletPreferences(
            portletPreferences.getPortletPreferencesId());

    Assert.assertNull(portletPreferences);
  }
  protected void exportPortletPreferences(
      PortletDataContext portletDataContext,
      long ownerId,
      int ownerType,
      boolean defaultUser,
      Layout layout,
      long plid,
      String portletId,
      Element parentElement)
      throws Exception {

    PortletPreferences portletPreferences = null;

    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY)
        || (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP)
        || (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED)) {

      plid = PortletKeys.PREFS_OWNER_ID_DEFAULT;
    }

    try {
      portletPreferences =
          PortletPreferencesLocalServiceUtil.getPortletPreferences(
              ownerId, ownerType, plid, portletId);
    } catch (NoSuchPortletPreferencesException nsppe) {
      return;
    }

    LayoutTypePortlet layoutTypePortlet = null;

    if (layout != null) {
      layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();
    }

    if ((layoutTypePortlet == null) || (layoutTypePortlet.hasPortletId(portletId))) {

      exportPortletPreference(
          portletDataContext,
          ownerId,
          ownerType,
          defaultUser,
          portletPreferences,
          portletId,
          plid,
          parentElement);
    }
  }
  protected List<Portlet> getEmbeddedPortlets(
      List<Portlet> columnPortlets, List<Portlet> staticPortlets) {

    if (_embeddedPortlets != null) {
      return _embeddedPortlets;
    }

    List<Portlet> portlets = new ArrayList<>();

    Layout layout = getLayout();

    List<PortletPreferences> portletPreferences =
        PortletPreferencesLocalServiceUtil.getPortletPreferences(
            PortletKeys.PREFS_OWNER_ID_DEFAULT,
            PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
            layout.getPlid());

    if (isCustomizable() && hasUserPreferences()) {
      portletPreferences = ListUtil.copy(portletPreferences);

      portletPreferences.addAll(
          PortletPreferencesLocalServiceUtil.getPortletPreferences(
              _portalPreferences.getUserId(), PortletKeys.PREFS_OWNER_TYPE_USER, layout.getPlid()));
    }

    for (PortletPreferences portletPreference : portletPreferences) {
      String portletId = portletPreference.getPortletId();

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

      if (Validator.isNull(portletId)
          || columnPortlets.contains(portlet)
          || staticPortlets.contains(portlet)
          || !portlet.isReady()
          || portlet.isUndeployedPortlet()
          || !portlet.isActive()) {

        continue;
      }

      if (portlet != null) {
        Portlet embeddedPortlet = portlet;

        if (portlet.isInstanceable()) {

          // Instanceable portlets do not need to be cloned because
          // they are already cloned. See the method getPortletById in
          // the class PortletLocalServiceImpl and how it references
          // the method getClonedInstance in the class PortletImpl.

        } else {
          embeddedPortlet = (Portlet) embeddedPortlet.clone();
        }

        // We set embedded portlets as static on order to avoid adding
        // the close and/or move icons.

        embeddedPortlet.setStatic(true);

        portlets.add(embeddedPortlet);
      }
    }

    _embeddedPortlets = portlets;

    return _embeddedPortlets;
  }
  protected void updatePortletPreferences(
      PortletDataContext portletDataContext,
      long ownerId,
      int ownerType,
      long plid,
      String portletId,
      String xml,
      boolean importData)
      throws Exception {

    Portlet portlet =
        PortletLocalServiceUtil.getPortletById(portletDataContext.getCompanyId(), portletId);

    if (portlet == null) {
      if (_log.isDebugEnabled()) {
        _log.debug(
            "Do not update portlet preferences for "
                + portletId
                + " because the portlet does not exist");
      }

      return;
    }

    PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

    if (importData || !MergeLayoutPrototypesThreadLocal.isInProgress()) {
      PortletPreferencesLocalServiceUtil.updatePreferences(
          ownerId, ownerType, plid, portletId, xml);

      return;
    }

    // Portlet preferences to be updated only when importing data

    String[] dataPortletPreferences = portletDataHandler.getDataPortletPreferences();

    // Current portlet preferences

    javax.portlet.PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(
            portletDataContext.getCompanyId(), ownerId, ownerType, plid, portletId);

    // New portlet preferences

    javax.portlet.PortletPreferences jxPortletPreferences =
        PortletPreferencesFactoryUtil.fromXML(
            portletDataContext.getCompanyId(), ownerId, ownerType, plid, portletId, xml);

    Enumeration<String> enu = jxPortletPreferences.getNames();

    while (enu.hasMoreElements()) {
      String name = enu.nextElement();

      String scopeLayoutUuid = portletDataContext.getScopeLayoutUuid();
      String scopeType = portletDataContext.getScopeType();

      if (!ArrayUtil.contains(dataPortletPreferences, name)
          || (Validator.isNull(scopeLayoutUuid) && scopeType.equals("company"))) {

        String[] values = jxPortletPreferences.getValues(name, null);

        portletPreferences.setValues(name, values);
      }
    }

    PortletPreferencesLocalServiceUtil.updatePreferences(
        ownerId, ownerType, plid, portletId, portletPreferences);
  }
  public static void copyPreferences(
      HttpServletRequest request, Layout targetLayout, Layout sourceLayout) throws Exception {

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

    LayoutTypePortlet sourceLayoutTypePortlet = (LayoutTypePortlet) sourceLayout.getLayoutType();

    List<String> sourcePortletIds = sourceLayoutTypePortlet.getPortletIds();

    for (String sourcePortletId : sourcePortletIds) {

      // Copy preference

      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              request, targetLayout, sourcePortletId);

      PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

      PortletPreferencesIds sourcePortletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              request, sourceLayout, sourcePortletId);

      PortletPreferences sourcePreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(sourcePortletPreferencesIds);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePreferences);

      // Copy portlet setup

      PortletPreferences targetPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(
              themeDisplay.getCompanyId(),
              PortletKeys.PREFS_OWNER_ID_DEFAULT,
              PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
              targetLayout.getPlid(),
              sourcePortletId);

      sourcePreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(
              themeDisplay.getCompanyId(),
              PortletKeys.PREFS_OWNER_ID_DEFAULT,
              PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
              sourceLayout.getPlid(),
              sourcePortletId);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          PortletKeys.PREFS_OWNER_ID_DEFAULT,
          PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
          targetLayout.getPlid(),
          sourcePortletId,
          sourcePreferences);

      SitesUtil.updateLayoutScopes(
          themeDisplay.getUserId(),
          sourceLayout,
          targetLayout,
          sourcePreferences,
          targetPreferences,
          sourcePortletId,
          themeDisplay.getLanguageId());

      Portlet sourcePortlet =
          PortletLocalServiceUtil.getPortletById(sourceLayout.getCompanyId(), sourcePortletId);

      PortletLayoutListener sourcePortletLayoutListener =
          sourcePortlet.getPortletLayoutListenerInstance();

      if (sourcePortletLayoutListener != null) {
        sourcePortletLayoutListener.onAddToLayout(sourcePortletId, targetLayout.getPlid());
      }
    }
  }
  public MarkupResponse invokeGetMarkup(GetMarkup getMarkup) throws WSRPException {
    String portletHandle = getMarkup.getPortletContext().getPortletHandle();

    MarkupResponse markupResponse = new MarkupResponse();
    MarkupContext markupContext = new MarkupContext();
    markupResponse.setMarkupContext(markupContext);

    try {
      MarkupParams markupParams = getMarkup.getMarkupParams();

      // window state
      String wsrpWindowState = markupParams.getWindowState();
      WindowState windowState = WSRPUtil.fromWsrpWindowState(wsrpWindowState);

      // portlet mode
      String wsrpMode = markupParams.getMode();
      PortletMode mode = WSRPUtil.fromWsrpMode(wsrpMode);

      ServletContext ctx = WSRPUtil.getServletContext();
      long companyId = WSRPUtil.getCompanyId();

      Portlet portlet = PortletLocalServiceUtil.getPortletById(companyId, portletHandle);
      CachePortlet cachePortlet = PortletInstanceFactory.create(portlet, ctx);
      PortletConfig portletConfig = PortletConfigFactory.create(portlet, ctx);
      PortletContext portletCtx = portletConfig.getPortletContext();

      Locale reqLocale = LocaleHelper.getLocale(markupParams.getLocales()[0]);
      String reqMimeType = markupParams.getMimeTypes()[0];
      Map renderParameters = _getRenderParameters(markupParams);
      HttpServletRequest httpReq =
          new WSRPServletRequest(
              WSRPUtil.getHttpServletRequest(), reqLocale, reqMimeType, renderParameters);
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(httpReq, portlet.getPortletId());
      PortletPreferences portletPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

      // this gets the default layout of the general guest
      User user = UserLocalServiceUtil.getDefaultUser(companyId);
      Layout layout = _getDefaultUserLayout(user.getCompanyId());

      RenderRequestImpl renderRequest =
          RenderRequestFactory.create(
              httpReq,
              portlet,
              cachePortlet,
              portletCtx,
              windowState,
              mode,
              portletPreferences,
              layout.getPlid());
      WSRPServletResponse res = new WSRPServletResponse();

      RenderResponseImpl renderResponse =
          new WSRPRenderResponseImpl(
              getMarkup,
              _provider,
              (RenderRequestImpl) renderRequest,
              res,
              portlet.getPortletId(),
              companyId,
              layout.getPlid());
      renderResponse.setContentType("text/html");
      renderRequest.defineObjects(portletConfig, renderResponse);
      cachePortlet.render(renderRequest, renderResponse);
      markupContext.setMarkupString(res.getString());
      String contentType = renderResponse.getContentType();
      if (contentType == null) {
        contentType = ContentTypes.TEXT_HTML_UTF8;
      }
      markupContext.setMimeType(contentType);
      markupContext.setLocale(renderResponse.getLocale().getLanguage());
      markupContext.setPreferredTitle(renderResponse.getTitle());

      RenderRequestFactory.recycle(renderRequest);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return markupResponse;
  }
  private ActionResult _doProcessAction(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    HttpServletRequest ownerLayoutRequest = getOwnerLayoutRequestWrapper(request, portlet);

    Layout ownerLayout = (Layout) ownerLayoutRequest.getAttribute(WebKeys.LAYOUT);

    boolean allowAddPortletDefaultResource =
        PortalUtil.isAllowAddPortletDefaultResource(ownerLayoutRequest, portlet);

    if (!allowAddPortletDefaultResource) {
      String url = null;

      LastPath lastPath = (LastPath) request.getAttribute(WebKeys.LAST_PATH);

      if (lastPath != null) {
        StringBundler sb = new StringBundler(3);

        sb.append(PortalUtil.getPortalURL(request));
        sb.append(lastPath.getContextPath());
        sb.append(lastPath.getPath());

        url = sb.toString();
      } else {
        url = String.valueOf(request.getRequestURI());
      }

      _log.error("Reject processAction for " + url + " on " + portlet.getPortletId());

      return ActionResult.EMPTY_ACTION_RESULT;
    }

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    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, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

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

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

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

    String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);

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

    UploadServletRequest uploadServletRequest = null;

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

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

        if (invokerPortlet.isStrutsPortlet()
            || invokerPortletConfigImpl.isCopyRequestParameters()
            || !invokerPortletConfigImpl.isWARFile()) {

          uploadServletRequest = new UploadServletRequestImpl(request);

          request = uploadServletRequest;
        }
      }

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

        AuthTokenUtil.check(request);
      }

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

      User user = PortalUtil.getUser(request);

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

      actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);

      ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

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

      long scopeGroupId = themeDisplay.getScopeGroupId();

      boolean access =
          PortletPermissionUtil.hasAccessPermission(
              permissionChecker, scopeGroupId, ownerLayout, portlet, portletMode);

      if (access) {
        invokerPortlet.processAction(actionRequestImpl, actionResponseImpl);

        actionResponseImpl.transferHeaders(response);
      }

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

      List<Event> events = actionResponseImpl.getEvents();

      String redirectLocation = actionResponseImpl.getRedirectLocation();

      if (Validator.isNull(redirectLocation) && portlet.isActionURLRedirect()) {

        PortletURL portletURL =
            new PortletURLImpl(
                actionRequestImpl,
                actionRequestImpl.getPortletName(),
                layout.getPlid(),
                PortletRequest.RENDER_PHASE);

        Map<String, String[]> renderParameters = actionResponseImpl.getRenderParameterMap();

        for (Map.Entry<String, String[]> entry : renderParameters.entrySet()) {

          String key = entry.getKey();
          String[] value = entry.getValue();

          portletURL.setParameter(key, value);
        }

        redirectLocation = portletURL.toString();
      }

      return new ActionResult(events, redirectLocation);
    } finally {
      if (uploadServletRequest != null) {
        uploadServletRequest.cleanUp();
      }

      ServiceContextThreadLocal.popServiceContext();
    }
  }
  public BlockingInteractionResponse invokePerformBlockingInteraction(
      PerformBlockingInteraction pbo) throws WSRPException {
    String portletHandle = pbo.getPortletContext().getPortletHandle();

    BlockingInteractionResponse bir = new BlockingInteractionResponse();
    UpdateResponse updateRes = new UpdateResponse();
    bir.setUpdateResponse(updateRes);

    try {
      MarkupParams markupParams = pbo.getMarkupParams();

      // window state
      String wsrpWindowState = markupParams.getWindowState();
      WindowState windowState = WSRPUtil.fromWsrpWindowState(wsrpWindowState);

      // portlet mode
      String wsrpMode = markupParams.getMode();
      PortletMode mode = WSRPUtil.fromWsrpMode(wsrpMode);

      ServletContext ctx = WSRPUtil.getServletContext();
      long companyId = WSRPUtil.getCompanyId();

      Portlet portlet = PortletLocalServiceUtil.getPortletById(companyId, portletHandle);
      CachePortlet cachePortlet = PortletInstanceFactory.create(portlet, ctx);
      PortletConfig portletConfig = PortletConfigFactory.create(portlet, ctx);
      PortletContext portletCtx = portletConfig.getPortletContext();

      Locale reqLocale = LocaleHelper.getLocale(markupParams.getLocales()[0]);
      String reqMimeType = markupParams.getMimeTypes()[0];
      InteractionParams interactionParams = pbo.getInteractionParams();
      Map actionParameters = _getActionParameters(interactionParams);
      HttpServletRequest httpReq =
          new WSRPServletRequest(
              WSRPUtil.getHttpServletRequest(), reqLocale, reqMimeType, actionParameters);
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(httpReq, portlet.getPortletId());
      PortletPreferences portletPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

      // this gets the default layout of the general guest
      User user = UserLocalServiceUtil.getDefaultUser(companyId);
      Layout layout = _getDefaultUserLayout(user.getCompanyId());

      ActionRequestImpl actionRequest =
          ActionRequestFactory.create(
              httpReq,
              portlet,
              cachePortlet,
              portletCtx,
              windowState,
              mode,
              portletPreferences,
              layout.getPlid());
      WSRPServletResponse res = new WSRPServletResponse();

      ActionResponseImpl actionResponse =
          new WSRPActionResponseImpl(
              pbo,
              _provider,
              actionRequest,
              res,
              portlet.getPortletId(),
              user,
              layout,
              windowState,
              mode);

      cachePortlet.processAction(actionRequest, actionResponse);
      String newNavState = null;

      Map renderParams = _getRenderParameters(httpReq, actionResponse);
      newNavState = Base64.encode(ObjectSerializer.serialize(renderParams));

      updateRes.setNavigationalState(newNavState);

      ActionRequestFactory.recycle(actionRequest);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return bir;
  }
  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 exportPortlet(
      PortletDataContext portletDataContext,
      LayoutCache layoutCache,
      String portletId,
      Layout layout,
      Element parentElement,
      long defaultUserId,
      boolean exportPermissions,
      boolean exportPortletArchivedSetups,
      boolean exportPortletData,
      boolean exportPortletSetup,
      boolean exportPortletUserPreferences,
      boolean exportUserPermissions)
      throws Exception {

    Portlet portlet =
        PortletLocalServiceUtil.getPortletById(portletDataContext.getCompanyId(), portletId);

    if (portlet == null) {
      if (_log.isDebugEnabled()) {
        _log.debug("Do not export portlet " + portletId + " because the portlet does not exist");
      }

      return;
    }

    if ((!portlet.isInstanceable())
        && (!portlet.isPreferencesUniquePerLayout())
        && (portletDataContext.hasNotUniquePerLayout(portletId))) {

      return;
    }

    Document document = SAXReaderUtil.createDocument();

    Element portletElement = document.addElement("portlet");

    portletElement.addAttribute("portlet-id", portletId);
    portletElement.addAttribute("root-portlet-id", PortletConstants.getRootPortletId(portletId));
    portletElement.addAttribute("old-plid", String.valueOf(layout.getPlid()));
    portletElement.addAttribute("scope-layout-type", portletDataContext.getScopeType());
    portletElement.addAttribute("scope-layout-uuid", portletDataContext.getScopeLayoutUuid());

    // Data

    if (exportPortletData) {
      javax.portlet.PortletPreferences jxPreferences =
          PortletPreferencesFactoryUtil.getPortletSetup(layout, portletId, StringPool.BLANK);

      if (!portlet.isPreferencesUniquePerLayout()) {
        StringBundler sb = new StringBundler(5);

        sb.append(portletId);
        sb.append(StringPool.AT);
        sb.append(portletDataContext.getScopeType());
        sb.append(StringPool.AT);
        sb.append(portletDataContext.getScopeLayoutUuid());

        String dataKey = sb.toString();

        if (!portletDataContext.hasNotUniquePerLayout(dataKey)) {
          portletDataContext.putNotUniquePerLayout(dataKey);

          exportPortletData(portletDataContext, portlet, layout, jxPreferences, portletElement);
        }
      } else {
        exportPortletData(portletDataContext, portlet, layout, jxPreferences, portletElement);
      }
    }

    // Portlet preferences

    long plid = PortletKeys.PREFS_OWNER_ID_DEFAULT;

    if (layout != null) {
      plid = layout.getPlid();
    }

    if (exportPortletSetup) {
      exportPortletPreferences(
          portletDataContext,
          PortletKeys.PREFS_OWNER_ID_DEFAULT,
          PortletKeys.PREFS_OWNER_TYPE_LAYOUT,
          false,
          layout,
          plid,
          portletId,
          portletElement);

      exportPortletPreferences(
          portletDataContext,
          portletDataContext.getScopeGroupId(),
          PortletKeys.PREFS_OWNER_TYPE_GROUP,
          false,
          layout,
          plid,
          portletId,
          portletElement);

      exportPortletPreferences(
          portletDataContext,
          portletDataContext.getCompanyId(),
          PortletKeys.PREFS_OWNER_TYPE_COMPANY,
          false,
          layout,
          plid,
          portletId,
          portletElement);
    }

    // Portlet preferences

    if (exportPortletUserPreferences) {
      List<PortletPreferences> portletPreferencesList =
          PortletPreferencesLocalServiceUtil.getPortletPreferences(
              PortletKeys.PREFS_OWNER_TYPE_USER, plid, portletId);

      for (PortletPreferences portletPreferences : portletPreferencesList) {

        boolean defaultUser = false;

        if (portletPreferences.getOwnerId() == PortletKeys.PREFS_OWNER_ID_DEFAULT) {

          defaultUser = true;
        }

        exportPortletPreferences(
            portletDataContext,
            portletPreferences.getOwnerId(),
            PortletKeys.PREFS_OWNER_TYPE_USER,
            defaultUser,
            layout,
            plid,
            portletId,
            portletElement);
      }

      try {
        PortletPreferences groupPortletPreferences =
            PortletPreferencesLocalServiceUtil.getPortletPreferences(
                portletDataContext.getScopeGroupId(),
                PortletKeys.PREFS_OWNER_TYPE_GROUP,
                PortletKeys.PREFS_PLID_SHARED,
                portletId);

        exportPortletPreference(
            portletDataContext,
            portletDataContext.getScopeGroupId(),
            PortletKeys.PREFS_OWNER_TYPE_GROUP,
            false,
            groupPortletPreferences,
            portletId,
            PortletKeys.PREFS_PLID_SHARED,
            portletElement);
      } catch (NoSuchPortletPreferencesException nsppe) {
      }
    }

    // Archived setups

    if (exportPortletArchivedSetups) {
      String rootPortletId = PortletConstants.getRootPortletId(portletId);

      List<PortletItem> portletItems =
          PortletItemLocalServiceUtil.getPortletItems(
              portletDataContext.getGroupId(), rootPortletId, PortletPreferences.class.getName());

      for (PortletItem portletItem : portletItems) {
        exportPortletPreferences(
            portletDataContext,
            portletItem.getPortletItemId(),
            PortletKeys.PREFS_OWNER_TYPE_ARCHIVED,
            false,
            null,
            plid,
            portletItem.getPortletId(),
            portletElement);
      }
    }

    // Permissions

    if (exportPermissions) {
      _permissionExporter.exportPortletPermissions(
          portletDataContext, layoutCache, portletId, layout, portletElement);
    }

    // Zip

    StringBundler sb = new StringBundler(4);

    sb.append(portletDataContext.getPortletPath(portletId));
    sb.append(StringPool.SLASH);
    sb.append(layout.getPlid());
    sb.append("/portlet.xml");

    String path = sb.toString();

    Element element = parentElement.addElement("portlet");

    element.addAttribute("portlet-id", portletId);
    element.addAttribute("layout-id", String.valueOf(layout.getLayoutId()));
    element.addAttribute("path", path);

    if (portletDataContext.isPathNotProcessed(path)) {
      try {
        portletDataContext.addZipEntry(path, document.formattedString());
      } catch (IOException ioe) {
        if (_log.isWarnEnabled()) {
          _log.warn(ioe.getMessage());
        }
      }

      portletDataContext.addPrimaryKey(String.class, path);
    }
  }
  protected PortletPreferences getCompanyPortletPreferences(long companyId, String settingsId) {

    return PortletPreferencesLocalServiceUtil.getStrictPreferences(
        companyId, companyId, PortletKeys.PREFS_OWNER_TYPE_COMPANY, 0, settingsId);
  }
  protected PortletPreferences getGroupPortletPreferences(
      long companyId, long groupId, String settingsId) {

    return PortletPreferencesLocalServiceUtil.getStrictPreferences(
        companyId, groupId, PortletKeys.PREFS_OWNER_TYPE_GROUP, 0, settingsId);
  }
  private void _doServeResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    HttpServletRequest ownerLayoutRequest = getOwnerLayoutRequestWrapper(request, portlet);

    Layout ownerLayout = (Layout) ownerLayoutRequest.getAttribute(WebKeys.LAYOUT);

    boolean allowAddPortletDefaultResource =
        PortalUtil.isAllowAddPortletDefaultResource(ownerLayoutRequest, portlet);

    if (!allowAddPortletDefaultResource) {
      String url = null;

      LastPath lastPath = (LastPath) request.getAttribute(WebKeys.LAST_PATH);

      if (lastPath != null) {
        StringBundler sb = new StringBundler(3);

        sb.append(PortalUtil.getPortalURL(request));
        sb.append(lastPath.getContextPath());
        sb.append(lastPath.getPath());

        url = sb.toString();
      } else {
        url = String.valueOf(request.getRequestURI());
      }

      response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      _log.error("Reject serveResource for " + url + " on " + portlet.getPortletId());

      return;
    }

    WindowState windowState = (WindowState) request.getAttribute(WebKeys.WINDOW_STATE);

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

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

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

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

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

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

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

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

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

    WebDAVStorage webDAVStorage = portlet.getWebDAVStorageInstance();

    if (webDAVStorage != null) {
      portletDisplay.setWebDAVEnabled(true);
    } else {
      portletDisplay.setWebDAVEnabled(false);
    }

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

    long companyId = PortalUtil.getCompanyId(request);

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

    resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

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

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      long scopeGroupId = themeDisplay.getScopeGroupId();

      boolean access =
          PortletPermissionUtil.hasAccessPermission(
              permissionChecker, scopeGroupId, ownerLayout, portlet, portletMode);

      if (access) {
        invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);

        resourceResponseImpl.transferHeaders(response);
      }
    } finally {
      ServiceContextThreadLocal.popServiceContext();
    }
  }
  protected void importPortletPreferences(
      PortletDataContext portletDataContext,
      long companyId,
      long groupId,
      Layout layout,
      String portletId,
      Element parentElement,
      boolean importPortletSetup,
      boolean importPortletArchivedSetups,
      boolean importPortletUserPreferences,
      boolean preserveScopeLayoutId)
      throws Exception {

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
    long plid = 0;
    String scopeType = StringPool.BLANK;
    String scopeLayoutUuid = StringPool.BLANK;

    if (layout != null) {
      plid = layout.getPlid();

      if (preserveScopeLayoutId && (portletId != null)) {
        javax.portlet.PortletPreferences jxPreferences =
            PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

        scopeType = GetterUtil.getString(jxPreferences.getValue("lfrScopeType", null));
        scopeLayoutUuid = GetterUtil.getString(jxPreferences.getValue("lfrScopeLayoutUuid", null));

        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }

    List<Element> portletPreferencesElements = parentElement.elements("portlet-preferences");

    for (Element portletPreferencesElement : portletPreferencesElements) {
      String path = portletPreferencesElement.attributeValue("path");

      if (portletDataContext.isPathNotProcessed(path)) {
        String xml = null;

        Element element = null;

        try {
          xml = portletDataContext.getZipEntryAsString(path);

          Document preferencesDocument = SAXReaderUtil.read(xml);

          element = preferencesDocument.getRootElement();
        } catch (DocumentException de) {
          throw new SystemException(de);
        }

        long ownerId = GetterUtil.getLong(element.attributeValue("owner-id"));
        int ownerType = GetterUtil.getInteger(element.attributeValue("owner-type"));

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
          continue;
        }

        if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP)
                || (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT))
            && !importPortletSetup) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && !importPortletArchivedSetups) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER)
            && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT)
            && !importPortletUserPreferences) {

          continue;
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
          plid = PortletKeys.PREFS_PLID_SHARED;
          ownerId = portletDataContext.getScopeGroupId();
        }

        boolean defaultUser = GetterUtil.getBoolean(element.attributeValue("default-user"));

        if (portletId == null) {
          portletId = element.attributeValue("portlet-id");
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
          portletId = PortletConstants.getRootPortletId(portletId);

          String userUuid = element.attributeValue("archive-user-uuid");
          String name = element.attributeValue("archive-name");

          long userId = portletDataContext.getUserId(userUuid);

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

          plid = 0;
          ownerId = portletItem.getPortletItemId();
        }

        if (defaultUser) {
          ownerId = defaultUserId;
        }

        xml =
            checkPortletPreferences(
                portletDataContext, companyId, ownerId, ownerType, plid, portletId, xml);

        PortletPreferencesLocalServiceUtil.updatePreferences(
            ownerId, ownerType, plid, portletId, xml);
      }
    }

    if (preserveScopeLayoutId && (layout != null)) {
      javax.portlet.PortletPreferences jxPreferences =
          PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

      try {
        jxPreferences.setValue("lfrScopeType", scopeType);
        jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);

        jxPreferences.store();
      } finally {
        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }
  }