public void init(PortletConfig config) throws PortletException {

    long clock = System.currentTimeMillis();
    try {
      log.debug("Initializing InfoPortlet");
      super.init(config);

      normalView = config.getPortletContext().getRequestDispatcher(NORMAL_VIEW);
      maximizedView = config.getPortletContext().getRequestDispatcher(MAXIMIZED_VIEW);
    } finally {
      long duration = System.currentTimeMillis() - clock;
      log.debug(String.format("Initialization took %s ms.", duration));
    }
  }
  @Override
  public void init(PortletConfig config) throws PortletException {
    CurrentInstance.clearAll();
    super.init(config);
    Properties initParameters = new Properties();

    // Read default parameters from the context
    final PortletContext context = config.getPortletContext();
    for (final Enumeration<String> e = context.getInitParameterNames(); e.hasMoreElements(); ) {
      final String name = e.nextElement();
      initParameters.setProperty(name, context.getInitParameter(name));
    }

    // Override with application settings from portlet.xml
    for (final Enumeration<String> e = config.getInitParameterNames(); e.hasMoreElements(); ) {
      final String name = e.nextElement();
      initParameters.setProperty(name, config.getInitParameter(name));
    }

    DeploymentConfiguration deploymentConfiguration = createDeploymentConfiguration(initParameters);
    try {
      vaadinService = createPortletService(deploymentConfiguration);
    } catch (ServiceException e) {
      throw new PortletException("Could not initialized VaadinPortlet", e);
    }
    // Sets current service even though there are no request and response
    vaadinService.setCurrentInstances(null, null);

    portletInitialized();

    CurrentInstance.clearAll();
  }
  public void serveResource(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ResourceRequest resourceRequest,
      ResourceResponse resourceResponse)
      throws Exception {

    String resourceID = resourceRequest.getResourceID();

    if (Validator.isNull(resourceID)) {
      return;
    }

    PortletContext portletContext = portletConfig.getPortletContext();

    PortletRequestDispatcher portletRequestDispatcher =
        portletContext.getRequestDispatcher(resourceID);

    if (portletRequestDispatcher == null) {
      return;
    }

    portletRequestDispatcher.forward(resourceRequest, resourceResponse);
  }
  public BridgePhaseBaseImpl(PortletConfig portletConfig, BridgeConfig bridgeConfig) {

    this.portletConfig = portletConfig;
    this.bridgeConfig = bridgeConfig;
    this.portletName = portletConfig.getPortletName();
    this.bridgeRequestScopePreserved =
        PortletConfigParam.BridgeRequestScopePreserved.getBooleanValue(portletConfig);

    this.portletContext =
        BridgePortletContextFactory.getPortletContextInstance(portletConfig.getPortletContext());

    // Initialize the incongruity context implementation.
    this.incongruityContext = IncongruityContextFactory.getIncongruityContextInstance();

    // Get the bridge request scope cache from the factory.
    this.bridgeRequestScopeCache =
        BridgeRequestScopeCacheFactory.getBridgeRequestScopeCacheInstance(portletContext);

    // Get the default lifecycle instance from the factory.
    LifecycleFactory lifecycleFactory =
        (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    String lifecycleId = this.portletContext.getInitParameter(Bridge.LIFECYCLE_ID);

    if (lifecycleId == null) {
      lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
    }

    this.facesLifecycle = lifecycleFactory.getLifecycle(lifecycleId);
  }
  protected void runScript(
      PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String language = ParamUtil.getString(actionRequest, "language");
    String script = ParamUtil.getString(actionRequest, "script");

    PortletContext portletContext = portletConfig.getPortletContext();

    Map<String, Object> portletObjects =
        ScriptingUtil.getPortletObjects(
            portletConfig, portletContext, actionRequest, actionResponse);

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream);

    portletObjects.put("out", unsyncPrintWriter);

    try {
      SessionMessages.add(actionRequest, "language", language);
      SessionMessages.add(actionRequest, "script", script);

      ScriptingUtil.exec(null, portletObjects, language, script);

      unsyncPrintWriter.flush();

      SessionMessages.add(actionRequest, "scriptOutput", unsyncByteArrayOutputStream.toString());
    } catch (ScriptingException se) {
      SessionErrors.add(actionRequest, ScriptingException.class.getName(), se);

      _log.error(se.getMessage());
    }
  }
  public void removeBridgeRequestScopesByPortlet(PortletConfig portletConfig) {
    String portletNameToRemove = portletConfig.getPortletName();
    PortletContext portletContext = portletConfig.getPortletContext();
    BridgeRequestScopeCache bridgeRequestScopeCache =
        BridgeRequestScopeCacheFactory.getBridgeRequestScopeCacheInstance(portletContext);
    Set<Map.Entry<String, BridgeRequestScope>> mapEntries = bridgeRequestScopeCache.entrySet();

    if (mapEntries != null) {

      List<String> keysToRemove = new ArrayList<String>();

      for (Map.Entry<String, BridgeRequestScope> mapEntry : mapEntries) {
        BridgeRequestScope bridgeRequestScope = mapEntry.getValue();
        String bridgeRequestScopeId = bridgeRequestScope.getId();
        String portletName = bridgeRequestScopeId.split("[:][:][:]")[0];

        if (portletNameToRemove.equals(portletName)) {
          keysToRemove.add(mapEntry.getKey());
        }
      }

      for (String key : keysToRemove) {
        bridgeRequestScopeCache.remove(key);
      }
    }
  }
  public void init(PortletConfig config) throws PortletException {
    super.init(config);

    pContext = config.getPortletContext();
    try {
      vengine = vHelper.makeEngine(pContext);
    } catch (Exception e) {
      throw new PortletException("Cannot initialize Velocity ", e);
    }
    M_log.info("iFrame Portlet vengine=" + vengine + " rb=" + rb);
  }
  protected InvokerPortlet init(
      Portlet portlet, PortletConfig portletConfig, javax.portlet.Portlet portletInstance)
      throws PortletException {

    PortletContext portletContext = portletConfig.getPortletContext();

    InvokerFilterContainer invokerFilterContainer =
        new InvokerFilterContainerImpl(portlet, portletContext);

    InvokerPortlet invokerPortlet =
        _invokerPortletFactory.create(
            portlet, portletInstance, portletContext, invokerFilterContainer);

    invokerPortlet.init(portletConfig);

    return invokerPortlet;
  }
  @Override
  public void serveResource(ResourceRequest portletReq, ResourceResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet serveResource entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    // Now do the actual dispatch
    String target =
        SERVLET_PREFIX
            + "DispatcherTests_SPEC2_19_ForwardServletResource_servlet"
            + SERVLET_SUFFIX
            + "?"
            + QUERY_STRING;
    PortletRequestDispatcher rd = portletConfig.getPortletContext().getRequestDispatcher(target);
    rd.forward(portletReq, portletResp);
  }
  protected void initPortletApp(Portlet portlet, ServletContext servletContext)
      throws PortletException {

    PortletApp portletApp = portlet.getPortletApp();

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

    PortletContext portletContext = portletConfig.getPortletContext();

    Set<PortletFilter> portletFilters = portletApp.getPortletFilters();

    for (PortletFilter portletFilter : portletFilters) {
      PortletFilterFactory.create(portletFilter, portletContext);
    }

    Set<PortletURLListener> portletURLListeners = portletApp.getPortletURLListeners();

    for (PortletURLListener portletURLListener : portletURLListeners) {
      PortletURLListenerFactory.create(portletURLListener);
    }
  }
  @Override
  public void processAction(ActionRequest portletReq, ActionResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet processAction entry");

    portletResp.setRenderParameters(portletReq.getParameterMap());
    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    StringWriter writer = new StringWriter();

    // Now do the actual dispatch
    String target =
        JSP_PREFIX
            + "DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse"
            + JSP_SUFFIX
            + "?"
            + QUERY_STRING;
    PortletRequestDispatcher rd = portletConfig.getPortletContext().getRequestDispatcher(target);
    rd.include(portletReq, portletResp);
  }
  @SuppressWarnings("unchecked")
  @Override
  public void init(PortletConfig portletConfig) {

    PortletContext portletContext = portletConfig.getPortletContext();

    synchronized (portletContext) {
      bridgeFactoryCache =
          (Map<Class<? extends FactoryWrapper<?>>, FactoryWrapper<?>>)
              portletContext.getAttribute(BRIDGE_FACTORY_CACHE);

      if (bridgeFactoryCache == null) {
        bridgeFactoryCache = new HashMap<Class<? extends FactoryWrapper<?>>, FactoryWrapper<?>>();
        portletContext.setAttribute(BRIDGE_FACTORY_CACHE, bridgeFactoryCache);
      }
    }

    BridgeConfigFactory bridgeConfigFactory = new BridgeConfigFactoryImpl(portletConfig);
    bridgeFactoryCache.put(BridgeConfigFactory.class, bridgeConfigFactory);
    bridgeConfig = bridgeConfigFactory.getBridgeConfig();
  }
  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();
    }
  }
  private List<Event> _doProcessEvent(
      HttpServletRequest request,
      HttpServletResponse response,
      Portlet portlet,
      Layout layout,
      Event event)
      throws Exception {

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

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

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

    LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

    WindowState windowState = null;

    if (layoutTypePortlet.hasStateMaxPortletId(portlet.getPortletId())) {
      windowState = WindowState.MAXIMIZED;
    } else if (layoutTypePortlet.hasStateMinPortletId(portlet.getPortletId())) {

      windowState = WindowState.MINIMIZED;
    } else {
      windowState = WindowState.NORMAL;
    }

    PortletMode portletMode = null;

    if (layoutTypePortlet.hasModeAboutPortletId(portlet.getPortletId())) {
      portletMode = LiferayPortletMode.ABOUT;
    } else if (layoutTypePortlet.hasModeConfigPortletId(portlet.getPortletId())) {

      portletMode = LiferayPortletMode.CONFIG;
    } else if (layoutTypePortlet.hasModeEditPortletId(portlet.getPortletId())) {

      portletMode = PortletMode.EDIT;
    } else if (layoutTypePortlet.hasModeEditDefaultsPortletId(portlet.getPortletId())) {

      portletMode = LiferayPortletMode.EDIT_DEFAULTS;
    } else if (layoutTypePortlet.hasModeEditGuestPortletId(portlet.getPortletId())) {

      portletMode = LiferayPortletMode.EDIT_GUEST;
    } else if (layoutTypePortlet.hasModeHelpPortletId(portlet.getPortletId())) {

      portletMode = PortletMode.HELP;
    } else if (layoutTypePortlet.hasModePreviewPortletId(portlet.getPortletId())) {

      portletMode = LiferayPortletMode.PREVIEW;
    } else if (layoutTypePortlet.hasModePrintPortletId(portlet.getPortletId())) {

      portletMode = LiferayPortletMode.PRINT;
    } else {
      portletMode = PortletMode.VIEW;
    }

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

    PortletPreferences portletPreferences =
        PortletPreferencesFactoryUtil.getPortletSetup(
            scopeGroupId, layout, portlet.getPortletId(), null);

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

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

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

    EventResponseImpl eventResponseImpl =
        EventResponseFactory.create(
            eventRequestImpl, response, portlet.getPortletId(), user, requestLayout);

    eventRequestImpl.defineObjects(portletConfig, eventResponseImpl);

    try {
      invokerPortlet.processEvent(eventRequestImpl, eventResponseImpl);

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

        renderParameterMap.putAll(eventResponseImpl.getRenderParameterMap());

        RenderParametersPool.put(
            request, requestLayout.getPlid(), portlet.getPortletId(), renderParameterMap);
      }

      return eventResponseImpl.getEvents();
    } finally {
      eventRequestImpl.cleanUp();
    }
  }
  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 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;
  }
  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;
  }
Exemple #18
0
 public void init(PortletConfig config) throws PortletException {
   super.init(config);
   normalView = config.getPortletContext().getRequestDispatcher(NORMAL_VIEW);
   maximizedView = config.getPortletContext().getRequestDispatcher(MAXIMIZED_VIEW);
   helpView = config.getPortletContext().getRequestDispatcher(HELP_VIEW);
 }
  private ActionResult _doProcessAction(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    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.getStrictPreferences(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)) {

        LiferayPortletConfig liferayPortletConfig =
            (LiferayPortletConfig) invokerPortlet.getPortletConfig();

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

          uploadServletRequest = PortalUtil.getUploadServletRequest(request);

          request = uploadServletRequest;
        }
      }

      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);

      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();
    }
  }
  private void _doServeResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    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.getStrictPreferences(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.setControlPanelCategory(portlet.getControlPanelEntryCategory());
    portletDisplay.setId(portlet.getPortletId());
    portletDisplay.setInstanceId(portlet.getInstanceId());
    portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portlet.getPortletId()));
    portletDisplay.setPortletName(portletConfig.getPortletName());
    portletDisplay.setResourcePK(portletPrimaryKey);
    portletDisplay.setRootPortletId(portlet.getRootPortletId());

    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);

      invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);

      resourceResponseImpl.transferHeaders(response);
    } finally {
      ServiceContextThreadLocal.popServiceContext();
    }
  }
  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();
    }
  }
  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;
  }
  @Override
  public InvokerPortlet create(
      Portlet portlet, ServletContext servletContext, boolean destroyPrevious)
      throws PortletException {

    if (destroyPrevious) {
      destroyRelated(portlet);
    }

    boolean instanceable = false;

    boolean deployed = !portlet.isUndeployedPortlet();

    if (portlet.isInstanceable()
        && deployed
        && PortletConstants.hasInstanceId(portlet.getPortletId())) {

      instanceable = true;
    }

    String rootPortletId = portlet.getRootPortletId();

    InvokerPortlet rootInvokerPortletInstance = null;

    Map<String, InvokerPortlet> portletInstances = null;

    if (deployed) {
      portletInstances = _pool.get(rootPortletId);

      if (portletInstances == null) {
        portletInstances = new ConcurrentHashMap<>();

        _pool.put(rootPortletId, portletInstances);
      } else {
        if (instanceable) {
          InvokerPortlet instanceInvokerPortletInstance =
              portletInstances.get(portlet.getPortletId());

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

        rootInvokerPortletInstance = portletInstances.get(rootPortletId);
      }
    }

    if (rootInvokerPortletInstance == null) {
      PortletBag portletBag = PortletBagPool.get(rootPortletId);

      // Portlet bag should never be null unless the portlet has been
      // undeployed

      if (portletBag == null) {
        PortletBagFactory portletBagFactory = new PortletBagFactory();

        portletBagFactory.setClassLoader(ClassLoaderUtil.getPortalClassLoader());
        portletBagFactory.setServletContext(servletContext);
        portletBagFactory.setWARFile(false);

        try {
          portletBag = portletBagFactory.create(portlet);
        } catch (Exception e) {
          throw new PortletException(e);
        }
      }

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

      rootInvokerPortletInstance = init(portlet, portletConfig, portletBag.getPortletInstance());

      if (deployed) {
        portletInstances.put(rootPortletId, rootInvokerPortletInstance);
      }
    }

    if (!instanceable) {
      return rootInvokerPortletInstance;
    }

    javax.portlet.Portlet portletInstance = rootInvokerPortletInstance.getPortletInstance();

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

    PortletContext portletContext = portletConfig.getPortletContext();
    boolean checkAuthToken = rootInvokerPortletInstance.isCheckAuthToken();
    boolean facesPortlet = rootInvokerPortletInstance.isFacesPortlet();
    boolean strutsPortlet = rootInvokerPortletInstance.isStrutsPortlet();
    boolean strutsBridgePortlet = rootInvokerPortletInstance.isStrutsBridgePortlet();

    InvokerPortlet instanceInvokerPortletInstance =
        _invokerPortletFactory.create(
            portlet,
            portletInstance,
            portletConfig,
            portletContext,
            (InvokerFilterContainer) rootInvokerPortletInstance,
            checkAuthToken,
            facesPortlet,
            strutsPortlet,
            strutsBridgePortlet);

    if (deployed) {
      portletInstances.put(portlet.getPortletId(), instanceInvokerPortletInstance);
    }

    return instanceInvokerPortletInstance;
  }