protected void collectSupportedPublishingEvents(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<QName> publishingEvents = new HashSet<>();

    PortletApp portletApp = portletModel.getPortletApp();

    List<String> supportedPublishingEvents =
        StringPlus.asList(serviceReference.getProperty("javax.portlet.supported-publishing-event"));

    for (String supportedPublishingEvent : supportedPublishingEvents) {
      String name = supportedPublishingEvent;
      String qname = null;

      String[] parts = StringUtil.split(supportedPublishingEvent, StringPool.SEMICOLON);

      if (parts.length == 2) {
        name = parts[0];
        qname = parts[1];
      }

      QName qName = getQName(name, qname, portletApp.getDefaultNamespace());

      publishingEvents.add(qName);
    }

    portletModel.setPublishingEvents(publishingEvents);
  }
  protected void collectSupportedPublicRenderParameters(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<PublicRenderParameter> publicRenderParameters = new HashSet<>();

    PortletApp portletApp = portletModel.getPortletApp();

    List<String> supportedPublicRenderParameters =
        StringPlus.asList(
            serviceReference.getProperty("javax.portlet.supported-public-render-parameter"));

    for (String supportedPublicRenderParameter : supportedPublicRenderParameters) {

      String name = supportedPublicRenderParameter;
      String qname = null;

      String[] parts = StringUtil.split(supportedPublicRenderParameter, StringPool.SEMICOLON);

      if (parts.length == 2) {
        name = parts[0];
        qname = parts[1];
      }

      QName qName = getQName(name, qname, portletApp.getDefaultNamespace());

      PublicRenderParameter publicRenderParameter =
          new PublicRenderParameterImpl(name, qName, portletApp);

      publicRenderParameters.add(publicRenderParameter);
    }

    portletModel.setPublicRenderParameters(publicRenderParameters);
  }
  protected void registerMessageListeners(String destinationName, Message message)
      throws SchedulerException {

    if (_portletLocalService == null) {
      throw new IllegalStateException("Portlet local service not initialized");
    }

    String messageListenerClassName =
        message.getString(SchedulerEngine.MESSAGE_LISTENER_CLASS_NAME);

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

    String portletId = message.getString(SchedulerEngine.PORTLET_ID);

    ClassLoader classLoader = null;

    if (Validator.isNull(portletId)) {
      classLoader = PortalClassLoaderUtil.getClassLoader();
    } else {
      Portlet portlet = _portletLocalService.getPortletById(portletId);

      if (portlet == null) {

        // No portlet found for the portlet ID. Try getting the class
        // loader where we assume the portlet ID is actually a servlet
        // context name.

        classLoader = ClassLoaderPool.getClassLoader(portletId);
      } else {
        PortletApp portletApp = portlet.getPortletApp();

        ServletContext servletContext = portletApp.getServletContext();

        classLoader = servletContext.getClassLoader();
      }
    }

    if (classLoader == null) {
      throw new SchedulerException("Unable to find class loader for portlet " + portletId);
    }

    MessageListener schedulerEventListener =
        getMessageListener(messageListenerClassName, classLoader);

    SchedulerEventMessageListenerWrapper schedulerEventListenerWrapper =
        new SchedulerEventMessageListenerWrapper();

    schedulerEventListenerWrapper.setMessageListener(schedulerEventListener);

    schedulerEventListenerWrapper.afterPropertiesSet();

    _messageBus.registerMessageListener(destinationName, schedulerEventListenerWrapper);

    message.put(
        SchedulerEngine.MESSAGE_LISTENER_UUID,
        schedulerEventListenerWrapper.getMessageListenerUUID());
  }
  protected void createContext(
      Bundle bundle, PortletApp portletApp, ServiceRegistrations serviceRegistrations) {

    ServletContextHelper servletContextHelper = new BundlePortletServletContextHelper(bundle);

    BundleContext bundleContext = bundle.getBundleContext();

    Dictionary<String, Object> properties = new HashMapDictionary<>();

    properties.put(
        HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, portletApp.getServletContextName());
    properties.put(
        HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH,
        "/" + portletApp.getServletContextName());
    properties.put(Constants.SERVICE_RANKING, 1000);

    serviceRegistrations.addServiceRegistration(
        bundleContext.registerService(
            ServletContextHelper.class, servletContextHelper, properties));
  }
  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 JSONArray getWARPortlets() {
    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    List<Portlet> portlets = portletLocalService.getPortlets();

    for (Portlet portlet : portlets) {
      PortletApp portletApp = portlet.getPortletApp();

      if (portletApp.isWARFile()) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        jsonObject.put("portlet_name", portlet.getPortletName());
        jsonObject.put("servlet_context_name", portletApp.getServletContextName());

        jsonArray.put(jsonObject);
      }
    }

    return jsonArray;
  }
  protected void collectSupportedProcessingEvents(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<QName> processingEvents = new HashSet<>();

    PortletApp portletApp = portletModel.getPortletApp();

    List<String> supportedProcessingEvents =
        StringPlus.asList(serviceReference.getProperty("javax.portlet.supported-processing-event"));

    for (String supportedProcessingEvent : supportedProcessingEvents) {
      String name = supportedProcessingEvent;
      String qname = null;

      String[] parts = StringUtil.split(supportedProcessingEvent, StringPool.SEMICOLON);

      if (parts.length == 2) {
        name = parts[0];
        qname = parts[1];
      }

      QName qName = getQName(name, qname, portletApp.getDefaultNamespace());

      processingEvents.add(qName);

      Set<EventDefinition> eventDefinitions = portletApp.getEventDefinitions();

      for (EventDefinition eventDefinition : eventDefinitions) {
        Set<QName> qNames = eventDefinition.getQNames();

        if (qNames.contains(qName)) {
          processingEvents.addAll(qNames);
        }
      }
    }

    portletModel.setProcessingEvents(processingEvents);
  }
  public boolean isWARFile() {
    PortletApp portletApp = _portlet.getPortletApp();

    return portletApp.isWARFile();
  }
  protected void init(
      HttpServletRequest request,
      Portlet portlet,
      InvokerPortlet invokerPortlet,
      PortletContext portletContext,
      WindowState windowState,
      PortletMode portletMode,
      PortletPreferences preferences,
      long plid) {

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

    _portlet = portlet;
    _portletName = portlet.getPortletId();
    _publicRenderParameters = PublicRenderParametersPool.get(request, plid);

    String portletNamespace = PortalUtil.getPortletNamespace(_portletName);

    boolean portalSessionShared = false;

    PortletApp portletApp = portlet.getPortletApp();

    if (portletApp.isWARFile() && !portlet.isPrivateSessionAttributes()) {
      portalSessionShared = true;
    }

    request = new SharedSessionServletRequest(request, portalSessionShared);

    DynamicServletRequest dynamicRequest = null;

    if (portlet.isPrivateRequestAttributes()) {
      dynamicRequest =
          new NamespaceServletRequest(request, portletNamespace, portletNamespace, false);
    } else {
      dynamicRequest = new DynamicServletRequest(request, false);
    }

    boolean portletFocus = false;

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

    boolean windowStateRestoreCurrentView = ParamUtil.getBoolean(request, "p_p_state_rcv");

    if (_portletName.equals(ppid)
        && !(windowStateRestoreCurrentView && portlet.isRestoreCurrentView())) {

      // Request was targeted to this portlet

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

        // Request was triggered by a render or resource URL

        portletFocus = true;
      } else if (themeDisplay.isLifecycleAction()) {
        _triggeredByActionURL = true;

        if (getLifecycle().equals(PortletRequest.ACTION_PHASE)) {

          // Request was triggered by an action URL and is being
          // processed by com.liferay.portlet.ActionRequestImpl

          portletFocus = true;
        }
      }
    }

    Map<String, String[]> renderParameters = RenderParametersPool.get(request, plid, _portletName);

    if (portletFocus) {
      renderParameters = new HashMap<String, String[]>();

      if (getLifecycle().equals(PortletRequest.RENDER_PHASE)
          && !LiferayWindowState.isExclusive(request)
          && !LiferayWindowState.isPopUp(request)) {

        RenderParametersPool.put(request, plid, _portletName, renderParameters);
      }

      Map<String, String[]> parameters = request.getParameterMap();

      for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
        String name = entry.getKey();

        if (isInvalidParameter(name)) {
          continue;
        }

        String[] values = entry.getValue();

        if (themeDisplay.isLifecycleRender()) {
          renderParameters.put(name, values);
        }

        if (values == null) {
          continue;
        }

        name = removePortletNamespace(invokerPortlet, portletNamespace, name);

        dynamicRequest.setParameterValues(name, values);
      }
    } else {
      for (Map.Entry<String, String[]> entry : renderParameters.entrySet()) {

        String name = entry.getKey();
        String[] values = entry.getValue();

        name = removePortletNamespace(invokerPortlet, portletNamespace, name);

        dynamicRequest.setParameterValues(name, values);
      }
    }

    mergePublicRenderParameters(dynamicRequest, preferences, plid);

    _request = dynamicRequest;
    _originalRequest = request;
    _wapTheme = BrowserSnifferUtil.isWap(_request);
    _portlet = portlet;
    _portalContext = new PortalContextImpl();
    _portletContext = portletContext;
    _windowState = windowState;
    _portletMode = portletMode;
    _preferences = preferences;
    _portalSessionId = _request.getRequestedSessionId();
    _session =
        new PortletSessionImpl(_request, _portletName, _portletContext, _portalSessionId, plid);

    String remoteUser = request.getRemoteUser();

    String userPrincipalStrategy = portlet.getUserPrincipalStrategy();

    if (userPrincipalStrategy.equals(PortletConstants.USER_PRINCIPAL_STRATEGY_SCREEN_NAME)) {

      try {
        User user = PortalUtil.getUser(request);

        if (user != null) {
          _remoteUser = user.getScreenName();
          _remoteUserId = user.getUserId();
          _userPrincipal = new ProtectedPrincipal(_remoteUser);
        }
      } catch (Exception e) {
        _log.error(e);
      }
    } else {
      long userId = PortalUtil.getUserId(request);

      if ((userId > 0) && (remoteUser == null)) {
        _remoteUser = String.valueOf(userId);
        _remoteUserId = userId;
        _userPrincipal = new ProtectedPrincipal(_remoteUser);
      } else {
        _remoteUser = remoteUser;
        _remoteUserId = GetterUtil.getLong(remoteUser);
        _userPrincipal = request.getUserPrincipal();
      }
    }

    _locale = themeDisplay.getLocale();
    _plid = plid;
  }
  protected void iteratePortlets(
      TreeNodeView parentNodeView,
      PortletCategory portletCategory,
      Set<String> portletIds,
      int parentNodeId,
      int depth) {

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

    String externalPortletCategory = null;

    for (String portletId : portletIds) {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(_user.getCompanyId(), portletId);

      if (portlet != null) {
        if (portlet.isSystem()) {
        } else if (!portlet.isActive()) {
        } else if (portlet.isInstanceable() && !_includeInstanceablePortlets) {
        } else if (!portlet.isInstanceable()
            && _layoutTypePortlet.hasPortletId(portlet.getPortletId())) {

          portlets.add(portlet);
        } else if (!portlet.hasAddPortletPermission(_user.getUserId())) {
        } else {
          portlets.add(portlet);
        }

        PortletApp portletApp = portlet.getPortletApp();

        if (portletApp.isWARFile() && Validator.isNull(externalPortletCategory)) {

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

          ResourceBundle resourceBundle = portletConfig.getResourceBundle(getLocale());

          externalPortletCategory =
              ResourceBundleUtil.getString(resourceBundle, portletCategory.getName());
        }
      }
    }

    portlets = ListUtil.sort(portlets, new PortletTitleComparator(getLocale()));

    for (int i = 0; i < portlets.size(); i++) {
      Portlet portlet = portlets.get(i);

      TreeNodeView nodeView = new TreeNodeView(++_nodeId);

      nodeView.setDepth(depth);
      nodeView.setLeaf(true);

      if ((i + 1) == portlets.size()) {
        nodeView.setLs("1");
      } else {
        nodeView.setLs("0");
      }

      nodeView.setName(PortalUtil.getPortletTitle(portlet, _servletContext, getLocale()));
      nodeView.setObjId(portlet.getRootPortletId());
      nodeView.setParentId(parentNodeId);

      if (_hierarchicalTree) {
        parentNodeView.addChild(nodeView);
      } else {
        _list.add(nodeView);
      }
    }
  }