protected void sendHTML(
      HttpServletResponse response, String path, List<WebServerEntry> webServerEntries)
      throws Exception {

    Template template =
        TemplateManagerUtil.getTemplate(
            TemplateManager.FREEMARKER, _TEMPLATE_FTL, TemplateContextType.RESTRICTED);

    template.put("dateFormat", _dateFormat);
    template.put("entries", webServerEntries);
    template.put("path", HttpUtil.encodePath(path));

    if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_DEFAULT) {
    } else if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_PARTIAL) {
      template.put("releaseInfo", ReleaseInfo.getName());
    } else {
      template.put("releaseInfo", ReleaseInfo.getReleaseInfo());
    }

    template.put("validator", Validator_IW.getInstance());

    response.setContentType(ContentTypes.TEXT_HTML_UTF8);

    template.processTemplate(response.getWriter());
  }
  private Version _getVersion(String version) {
    if (version.equals("${current-version}")) {
      version = ReleaseInfo.getVersion();
    }

    return Version.getInstance(version);
  }
示例#3
0
  protected boolean processServicePre(
      HttpServletRequest request, HttpServletResponse response, long userId)
      throws IOException, ServletException {

    try {
      EventsProcessorUtil.process(
          PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
          PropsValues.SERVLET_SERVICE_EVENTS_PRE,
          request,
          response);
    } catch (Exception e) {
      Throwable cause = e.getCause();

      if (cause instanceof NoSuchLayoutException) {
        sendError(HttpServletResponse.SC_NOT_FOUND, cause, request, response);

        return true;
      } else if (cause instanceof PrincipalException) {
        processServicePrePrincipalException(cause, userId, request, response);

        return true;
      }

      _log.error(e, e);

      request.setAttribute(PageContext.EXCEPTION, e);

      ServletContext servletContext = getServletContext();

      StrutsUtil.forward(
          PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE, servletContext, request, response);

      return true;
    }

    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
    } else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getName());
    } else {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
    }

    return false;
  }
  @Override
  public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {

    renderResponse.setContentType(ContentTypes.TEXT_HTML_UTF8);

    PrintWriter printWriter = renderResponse.getWriter();

    printWriter.print("Welcome to ".concat(ReleaseInfo.getReleaseInfo()).concat("."));
  }
示例#5
0
  protected Response doExecuteMethod(String url, String methodName, Object[] arguments)
      throws Exception {

    if (_log.isDebugEnabled()) {
      StringBundler sb = new StringBundler();

      sb.append("XML-RPC invoking ");
      sb.append(methodName);
      sb.append(" ");

      if (arguments != null) {
        for (int i = 0; i < arguments.length; i++) {
          sb.append(arguments[i]);

          if (i < (arguments.length - 1)) {
            sb.append(", ");
          }
        }
      }

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

    String requestXML = XmlRpcParser.buildMethod(methodName, arguments);

    Http.Options options = new Http.Options();

    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
    } else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
      options.addHeader(HttpHeaders.USER_AGENT, ReleaseInfo.getName());
    } else {
      options.addHeader(HttpHeaders.USER_AGENT, ReleaseInfo.getServerInfo());
    }

    options.setBody(requestXML, ContentTypes.TEXT_XML, StringPool.UTF8);
    options.setLocation(url);
    options.setPost(true);

    String responseXML = HttpUtil.URLtoString(options);

    return XmlRpcParser.parseResponse(responseXML);
  }
  private void _registerServletContext(ServletContext servletContext) {
    BundleContext bundleContext = _framework.getBundleContext();

    Hashtable<String, Object> properties = new Hashtable<String, Object>();

    properties.put(ServicePropsKeys.BEAN_ID, ServletContext.class.getName());
    properties.put(ServicePropsKeys.ORIGINAL_BEAN, Boolean.TRUE);
    properties.put(ServicePropsKeys.VENDOR, ReleaseInfo.getVendor());

    bundleContext.registerService(
        new String[] {ServletContext.class.getName()}, servletContext, properties);
  }
  @Override
  protected void processPortletParameterMap(
      PortletRequest portletRequest,
      PortletResponse portletResponse,
      Map<String, String[]> parameterMap) {

    parameterMap.put(
        "clientBuild", new String[] {String.valueOf(MarketplaceConstants.CLIENT_BUILD)});
    parameterMap.put("compatibility", new String[] {String.valueOf(ReleaseInfo.getBuildNumber())});
    parameterMap.put(
        "supportsHotDeploy", new String[] {String.valueOf(ServerDetector.isSupportsHotDeploy())});
  }
  protected String getMainReleaseVersion() {
    if (_mainReleaseVersion != null) {
      return _mainReleaseVersion;
    }

    String releaseVersion = ReleaseInfo.getVersion();

    int pos = releaseVersion.lastIndexOf(StringPool.PERIOD);

    _mainReleaseVersion = releaseVersion.substring(0, pos) + ".0";

    return _mainReleaseVersion;
  }
  protected void registerPortalInitialized() {
    Registry registry = RegistryUtil.getRegistry();

    Map<String, Object> properties = new HashMap<>();

    properties.put("module.service.lifecycle", "portal.initialized");
    properties.put("service.vendor", ReleaseInfo.getVendor());
    properties.put("service.version", ReleaseInfo.getVersion());

    _portalModuleServiceLifecycleServiceRegistration =
        registry.registerService(
            ModuleServiceLifecycle.class, new ModuleServiceLifecycle() {}, properties);

    properties = new HashMap<>();

    properties.put("bean.id", ServletContext.class.getName());
    properties.put("original.bean", Boolean.TRUE);
    properties.put("service.vendor", ReleaseInfo.getVendor());

    _servletContextServiceRegistration =
        registry.registerService(ServletContext.class, getServletContext(), properties);
  }
  private static JSONObject _createRequest(
      String orderUuid, String productEntryName, int maxServers) throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("version", 2);
    jsonObject.put("orderUuid", orderUuid);
    jsonObject.put("liferayVersion", ReleaseInfo.getBuildNumber());

    if (Validator.isNull(productEntryName)) {
      jsonObject.put("cmd", "QUERY");
    } else {
      jsonObject.put("cmd", "REGISTER");

      if (productEntryName.startsWith("basic")) {
        jsonObject.put("productEntryName", "basic");

        if (productEntryName.equals("basic-cluster")) {
          jsonObject.put("cluster", true);
          jsonObject.put("maxServers", maxServers);
        } else if (productEntryName.startsWith("basic-")) {
          String[] productNameArray = StringUtil.split(productEntryName, StringPool.DASH);

          if (productNameArray.length >= 3) {
            jsonObject.put("offeringEntryId", productNameArray[1]);
            jsonObject.put("clusterId", productNameArray[2]);
          }
        }
      } else {
        jsonObject.put("productEntryName", productEntryName);
      }

      jsonObject.put("hostName", getHostName());
      jsonObject.put("ipAddresses", StringUtil.merge(getIpAddresses()));
      jsonObject.put("macAddresses", StringUtil.merge(getMacAddresses()));
      jsonObject.put("serverId", Arrays.toString(getServerIdBytes()));
    }

    return jsonObject;
  }
  public void getPrepackagedApps(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, getServerPortletURL());

    setBaseRequestParameters(actionRequest, actionResponse, oAuthRequest);

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "1");
    addOAuthParameter(oAuthRequest, "p_p_state", WindowState.NORMAL.toString());

    String serverNamespace = getServerNamespace();

    addOAuthParameter(
        oAuthRequest,
        serverNamespace.concat("compatibility"),
        String.valueOf(ReleaseInfo.getBuildNumber()));
    addOAuthParameter(
        oAuthRequest, serverNamespace.concat("javax.portlet.action"), "getPrepackagedApps");

    Map<String, String> prepackagedApps = _appLocalService.getPrepackagedApps();

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    Set<String> keys = prepackagedApps.keySet();

    for (String key : keys) {
      jsonObject.put(key, prepackagedApps.get(key));
    }

    addOAuthParameter(
        oAuthRequest, serverNamespace.concat("prepackagedApps"), jsonObject.toString());

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    JSONObject responseJSONObject = JSONFactoryUtil.createJSONObject(response.getBody());

    writeJSON(actionRequest, actionResponse, responseJSONObject);
  }
  private void _registerService(BundleContext bundleContext, String beanName, Object bean) {

    Set<Class<?>> interfaces = _getInterfaces(bean);

    if (interfaces.isEmpty()) {
      return;
    }

    List<String> names = new ArrayList<String>(interfaces.size());

    for (Class<?> interfaceClass : interfaces) {
      String interfaceClassName = interfaceClass.getName();

      if (!_isIgnoredInterface(interfaceClassName)) {
        names.add(interfaceClassName);
      }
    }

    if (names.isEmpty()) {
      return;
    }

    Hashtable<String, Object> properties = new Hashtable<String, Object>();

    Map<String, Object> osgiBeanProperties = OSGiBeanProperties.Convert.fromObject(bean);

    if (osgiBeanProperties != null) {
      properties.putAll(osgiBeanProperties);
    }

    properties.put(ServicePropsKeys.BEAN_ID, beanName);
    properties.put(ServicePropsKeys.ORIGINAL_BEAN, Boolean.TRUE);
    properties.put(ServicePropsKeys.VENDOR, ReleaseInfo.getVendor());

    bundleContext.registerService(names.toArray(new String[names.size()]), bean, properties);
  }
示例#13
0
/**
 * @author Brian Wing Shun Chan
 * @author Jorge Ferrer
 * @author Brian Myunghun Kim
 */
public class MainServlet extends ActionServlet {

  @Override
  public void destroy() {
    if (_log.isDebugEnabled()) {
      _log.debug("Destroy plugins");
    }

    PortalLifecycleUtil.flushDestroys();

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

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy portlets");
    }

    try {
      destroyPortlets(portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy companies");
    }

    try {
      destroyCompanies();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process global shutdown events");
    }

    try {
      processGlobalShutdownEvents();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy");
    }

    callParentDestroy();
  }

  @Override
  public void init() throws ServletException {
    if (_log.isDebugEnabled()) {
      _log.debug("Initialize");
    }

    ServletContext servletContext = getServletContext();

    servletContext.setAttribute(MainServlet.class.getName(), Boolean.TRUE);

    callParentInit();

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize servlet context pool");
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process startup events");
    }

    try {
      processStartupEvents();
    } catch (Exception e) {
      _log.error(e, e);

      System.out.println("Stopping the server due to unexpected startup errors");

      System.exit(0);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize server detector");
    }

    try {
      initServerDetector();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize plugin package");
    }

    PluginPackage pluginPackage = null;

    try {
      pluginPackage = initPluginPackage();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize portlets");
    }

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

    try {
      portlets.addAll(initPortlets(pluginPackage));
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize layout templates");
    }

    try {
      initLayoutTemplates(pluginPackage, portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize social");
    }

    try {
      initSocial(pluginPackage);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize themes");
    }

    try {
      initThemes(pluginPackage, portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize web settings");
    }

    try {
      initWebSettings();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize extension environment");
    }

    try {
      initExt();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process global startup events");
    }

    try {
      processGlobalStartupEvents();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize resource actions");
    }

    try {
      initResourceActions(portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize companies");
    }

    try {
      initCompanies();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize plugins");
    }

    try {
      initPlugins();
    } catch (Exception e) {
      _log.error(e, e);
    }

    servletContext.setAttribute(WebKeys.STARTUP_FINISHED, true);

    StartupHelperUtil.setStartupFinished(true);

    ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);
  }

  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (_log.isDebugEnabled()) {
      _log.debug("Process service request");
    }

    if (processShutdownRequest(request, response)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed shutdown request");
      }

      return;
    }

    if (processMaintenanceRequest(request, response)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed maintenance request");
      }

      return;
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Get company id");
    }

    long companyId = getCompanyId(request);

    if (processCompanyInactiveRequest(request, response, companyId)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed company inactive request");
      }

      return;
    }

    try {
      if (processGroupInactiveRequest(request, response)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Processed site inactive request");
        }

        return;
      }
    } catch (Exception e) {
      if (e instanceof NoSuchLayoutException) {
        if (_log.isDebugEnabled()) {
          _log.debug(e, e);
        }
      } else {
        _log.error(e, e);
      }
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Set portal port");
    }

    setPortalPort(request);

    if (_log.isDebugEnabled()) {
      _log.debug("Check variables");
    }

    checkServletContext(request);
    checkPortletRequestProcessor(request);
    checkTilesDefinitionsFactory();

    if (_log.isDebugEnabled()) {
      _log.debug("Handle non-serializable request");
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Encrypt request");
    }

    request = encryptRequest(request, companyId);

    long userId = getUserId(request);

    String remoteUser = getRemoteUser(request, userId);

    if (_log.isDebugEnabled()) {
      _log.debug("Protect request");
    }

    request = protectRequest(request, remoteUser);

    if (_log.isDebugEnabled()) {
      _log.debug("Set principal");
    }

    String password = getPassword(request);

    setPrincipal(companyId, userId, remoteUser, password);

    try {
      if (_log.isDebugEnabled()) {
        _log.debug("Authenticate user id " + userId + " and remote user " + remoteUser);
      }

      userId = loginUser(request, response, companyId, userId, remoteUser);

      if (_log.isDebugEnabled()) {
        _log.debug("Authenticated user id " + userId);
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Set session thread local");
    }

    PortalSessionThreadLocal.setHttpSession(request.getSession());

    if (_log.isDebugEnabled()) {
      _log.debug("Process service pre events");
    }

    if (processServicePre(request, response, userId)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processing service pre events has errors");
      }

      return;
    }

    if (hasAbsoluteRedirect(request)) {
      if (_log.isDebugEnabled()) {
        String currentURL = PortalUtil.getCurrentURL(request);

        _log.debug("Current URL " + currentURL + " has absolute redirect");
      }

      return;
    }

    if (!hasThemeDisplay(request)) {
      if (_log.isDebugEnabled()) {
        String currentURL = PortalUtil.getCurrentURL(request);

        _log.debug("Current URL " + currentURL + " does not have a theme display");
      }

      return;
    }

    try {
      if (_log.isDebugEnabled()) {
        _log.debug("Call parent service");
      }

      callParentService(request, response);
    } finally {
      if (_log.isDebugEnabled()) {
        _log.debug("Process service post events");
      }

      processServicePost(request, response);
    }
  }

  protected void callParentDestroy() {
    super.destroy();
  }

  protected void callParentInit() throws ServletException {
    super.init();
  }

  protected void callParentService(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    super.service(request, response);
  }

  protected void checkPortletRequestProcessor(HttpServletRequest request) throws ServletException {

    ServletContext servletContext = getServletContext();

    PortletRequestProcessor portletReqProcessor =
        (PortletRequestProcessor) servletContext.getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
      ModuleConfig moduleConfig = getModuleConfig(request);

      portletReqProcessor = PortletRequestProcessor.getInstance(this, moduleConfig);

      servletContext.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }
  }

  protected void checkServletContext(HttpServletRequest request) {
    ServletContext servletContext = getServletContext();

    request.setAttribute(WebKeys.CTX, servletContext);

    String contextPath = request.getContextPath();

    servletContext.setAttribute(WebKeys.CTX_PATH, contextPath);
  }

  protected void checkTilesDefinitionsFactory() {
    ServletContext servletContext = getServletContext();

    if (servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) != null) {

      return;
    }

    servletContext.setAttribute(
        TilesUtilImpl.DEFINITIONS_FACTORY,
        servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
  }

  protected void checkWebSettings(String xml) throws DocumentException {
    Document doc = SAXReaderUtil.read(xml);

    Element root = doc.getRootElement();

    int timeout = PropsValues.SESSION_TIMEOUT;

    Element sessionConfig = root.element("session-config");

    if (sessionConfig != null) {
      String sessionTimeout = sessionConfig.elementText("session-timeout");

      timeout = GetterUtil.getInteger(sessionTimeout, timeout);
    }

    PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));

    PropsValues.SESSION_TIMEOUT = timeout;

    I18nServlet.setLanguageIds(root);
    I18nFilter.setLanguageIds(I18nServlet.getLanguageIds());
  }

  protected void destroyCompanies() throws Exception {
    long[] companyIds = PortalInstances.getCompanyIds();

    for (long companyId : companyIds) {
      destroyCompany(companyId);
    }
  }

  protected void destroyCompany(long companyId) {
    if (_log.isDebugEnabled()) {
      _log.debug("Process shutdown events");
    }

    try {
      EventsProcessorUtil.process(
          PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
          PropsValues.APPLICATION_SHUTDOWN_EVENTS,
          new String[] {String.valueOf(companyId)});
    } catch (Exception e) {
      _log.error(e, e);
    }
  }

  protected void destroyPortlets(List<Portlet> portlets) throws Exception {
    for (Portlet portlet : portlets) {
      PortletInstanceFactoryUtil.destroy(portlet);
    }
  }

  protected HttpServletRequest encryptRequest(HttpServletRequest request, long companyId) {

    boolean encryptRequest = ParamUtil.getBoolean(request, WebKeys.ENCRYPT);

    if (!encryptRequest) {
      return request;
    }

    try {
      Company company = CompanyLocalServiceUtil.getCompanyById(companyId);

      request = new EncryptedServletRequest(request, company.getKeyObj());
    } catch (Exception e) {
    }

    return request;
  }

  protected long getCompanyId(HttpServletRequest request) {
    return PortalInstances.getCompanyId(request);
  }

  protected String getPassword(HttpServletRequest request) {
    return PortalUtil.getUserPassword(request);
  }

  protected String getRemoteUser(HttpServletRequest request, long userId) {
    String remoteUser = request.getRemoteUser();

    if (!PropsValues.PORTAL_JAAS_ENABLE) {
      HttpSession session = request.getSession();

      String jRemoteUser = (String) session.getAttribute("j_remoteuser");

      if (jRemoteUser != null) {
        remoteUser = jRemoteUser;

        session.removeAttribute("j_remoteuser");
      }
    }

    if ((userId > 0) && (remoteUser == null)) {
      remoteUser = String.valueOf(userId);
    }

    return remoteUser;
  }

  @Override
  protected synchronized RequestProcessor getRequestProcessor(ModuleConfig moduleConfig)
      throws ServletException {

    ServletContext servletContext = getServletContext();

    String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();

    RequestProcessor requestProcessor = (RequestProcessor) servletContext.getAttribute(key);

    if (requestProcessor == null) {
      ControllerConfig controllerConfig = moduleConfig.getControllerConfig();

      try {
        requestProcessor =
            (RequestProcessor)
                InstanceFactory.newInstance(
                    ClassLoaderUtil.getPortalClassLoader(), controllerConfig.getProcessorClass());
      } catch (Exception e) {
        throw new ServletException(e);
      }

      requestProcessor.init(this, moduleConfig);

      servletContext.setAttribute(key, requestProcessor);
    }

    return requestProcessor;
  }

  protected long getUserId(HttpServletRequest request) {
    return PortalUtil.getUserId(request);
  }

  protected boolean hasAbsoluteRedirect(HttpServletRequest request) {
    if (request.getAttribute(AbsoluteRedirectsResponse.class.getName()) == null) {

      return false;
    } else {
      return true;
    }
  }

  protected boolean hasThemeDisplay(HttpServletRequest request) {
    if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
      return false;
    } else {
      return true;
    }
  }

  protected void initCompanies() throws Exception {
    ServletContext servletContext = getServletContext();

    try {
      String[] webIds = PortalInstances.getWebIds();

      for (String webId : webIds) {
        PortalInstances.initCompany(servletContext, webId);
      }
    } finally {
      CompanyThreadLocal.setCompanyId(PortalInstances.getDefaultCompanyId());

      ShardDataSourceTargetSource shardDataSourceTargetSource =
          (ShardDataSourceTargetSource) InfrastructureUtil.getShardDataSourceTargetSource();

      if (shardDataSourceTargetSource != null) {
        shardDataSourceTargetSource.resetDataSource();
      }
    }
  }

  protected void initExt() throws Exception {
    ServletContext servletContext = getServletContext();

    ExtRegistry.registerPortal(servletContext);
  }

  protected void initLayoutTemplates(PluginPackage pluginPackage, List<Portlet> portlets)
      throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-layout-templates.xml")),
          HttpUtil.URLtoString(
              servletContext.getResource("/WEB-INF/liferay-layout-templates-ext.xml"))
        };

    List<LayoutTemplate> layoutTemplates =
        LayoutTemplateLocalServiceUtil.init(servletContext, xmls, pluginPackage);

    servletContext.setAttribute(WebKeys.PLUGIN_LAYOUT_TEMPLATES, layoutTemplates);
  }

  protected PluginPackage initPluginPackage() throws Exception {
    ServletContext servletContext = getServletContext();

    return PluginPackageUtil.readPluginPackageServletContext(servletContext);
  }

  /** @see SetupWizardUtil#_initPlugins */
  protected void initPlugins() throws Exception {

    // See LEP-2885. Don't flush hot deploy events until after the portal
    // has initialized.

    if (SetupWizardUtil.isSetupFinished()) {
      HotDeployUtil.setCapturePrematureEvents(false);

      PortalLifecycleUtil.flushInits();
    }
  }

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

  protected List<Portlet> initPortlets(PluginPackage pluginPackage) throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(
              servletContext.getResource("/WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_CUSTOM)),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/portlet-ext.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-portlet.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-portlet-ext.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/web.xml"))
        };

    PortletLocalServiceUtil.initEAR(servletContext, xmls, pluginPackage);

    PortletBagFactory portletBagFactory = new PortletBagFactory();

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

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

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

      portletBagFactory.create(portlet);

      if (i == 0) {
        initPortletApp(portlet, servletContext);
      }
    }

    servletContext.setAttribute(WebKeys.PLUGIN_PORTLETS, portlets);

    return portlets;
  }

  protected void initResourceActions(List<Portlet> portlets) throws Exception {

    for (Portlet portlet : portlets) {
      List<String> portletActions = ResourceActionsUtil.getPortletResourceActions(portlet);

      ResourceActionLocalServiceUtil.checkResourceActions(portlet.getPortletId(), portletActions);

      List<String> modelNames =
          ResourceActionsUtil.getPortletModelResources(portlet.getPortletId());

      for (String modelName : modelNames) {
        List<String> modelActions = ResourceActionsUtil.getModelResourceActions(modelName);

        ResourceActionLocalServiceUtil.checkResourceActions(modelName, modelActions);
      }
    }
  }

  protected void initServerDetector() throws Exception {
    ServerCapabilitiesUtil.determineServerCapabilities(getServletContext());
  }

  protected void initSocial(PluginPackage pluginPackage) throws Exception {
    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-social.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-social-ext.xml"))
        };

    SocialConfigurationUtil.read(classLoader, xmls);
  }

  protected void initThemes(PluginPackage pluginPackage, List<Portlet> portlets) throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-look-and-feel.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-look-and-feel-ext.xml"))
        };

    List<Theme> themes =
        ThemeLocalServiceUtil.init(servletContext, null, true, xmls, pluginPackage);

    servletContext.setAttribute(WebKeys.PLUGIN_THEMES, themes);
  }

  protected void initWebSettings() throws Exception {
    ServletContext servletContext = getServletContext();

    String xml = HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/web.xml"));

    checkWebSettings(xml);
  }

  protected long loginUser(
      HttpServletRequest request,
      HttpServletResponse response,
      long companyId,
      long userId,
      String remoteUser)
      throws PortalException, SystemException {

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

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

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

    User user = UserLocalServiceUtil.getUserById(userId);

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

    HttpSession session = request.getSession();

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

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

    return userId;
  }

  protected boolean processCompanyInactiveRequest(
      HttpServletRequest request, HttpServletResponse response, long companyId) throws IOException {

    if (PortalInstances.isCompanyActive(companyId)) {
      return false;
    }

    processInactiveRequest(
        request, response, "this-instance-is-inactive-please-contact-the-administrator");

    return true;
  }

  protected void processGlobalShutdownEvents() throws Exception {
    EventsProcessorUtil.process(
        PropsKeys.GLOBAL_SHUTDOWN_EVENTS, PropsValues.GLOBAL_SHUTDOWN_EVENTS);

    super.destroy();
  }

  protected void processGlobalStartupEvents() throws Exception {
    EventsProcessorUtil.process(PropsKeys.GLOBAL_STARTUP_EVENTS, PropsValues.GLOBAL_STARTUP_EVENTS);
  }

  protected boolean processGroupInactiveRequest(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, PortalException, SystemException {

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid <= 0) {
      return false;
    }

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    Group group = layout.getGroup();

    if (group.isActive()) {
      return false;
    }

    processInactiveRequest(
        request, response, "this-site-is-inactive-please-contact-the-administrator");

    return true;
  }

  protected void processInactiveRequest(
      HttpServletRequest request, HttpServletResponse response, String messageKey)
      throws IOException {

    response.setContentType(ContentTypes.TEXT_HTML_UTF8);

    Locale locale = LocaleUtil.getDefault();

    String message = LanguageUtil.get(locale, messageKey);

    String html = ContentUtil.get("com/liferay/portal/dependencies/inactive.html");

    html = StringUtil.replace(html, "[$MESSAGE$]", message);

    PrintWriter printWriter = response.getWriter();

    printWriter.print(html);
  }

  protected boolean processMaintenanceRequest(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (!MaintenanceUtil.isMaintaining()) {
      return false;
    }

    RequestDispatcher requestDispatcher =
        request.getRequestDispatcher("/html/portal/maintenance.jsp");

    requestDispatcher.include(request, response);

    return true;
  }

  protected void processServicePost(HttpServletRequest request, HttpServletResponse response) {

    try {
      EventsProcessorUtil.process(
          PropsKeys.SERVLET_SERVICE_EVENTS_POST,
          PropsValues.SERVLET_SERVICE_EVENTS_POST,
          request,
          response);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }

  protected boolean processServicePre(
      HttpServletRequest request, HttpServletResponse response, long userId)
      throws IOException, ServletException {

    try {
      EventsProcessorUtil.process(
          PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
          PropsValues.SERVLET_SERVICE_EVENTS_PRE,
          request,
          response);
    } catch (Exception e) {
      Throwable cause = e.getCause();

      if (cause instanceof NoSuchLayoutException) {
        sendError(HttpServletResponse.SC_NOT_FOUND, cause, request, response);

        return true;
      } else if (cause instanceof PrincipalException) {
        processServicePrePrincipalException(cause, userId, request, response);

        return true;
      }

      _log.error(e, e);

      request.setAttribute(PageContext.EXCEPTION, e);

      ServletContext servletContext = getServletContext();

      StrutsUtil.forward(
          PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE, servletContext, request, response);

      return true;
    }

    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
    } else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getName());
    } else {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
    }

    return false;
  }

  protected void processServicePrePrincipalException(
      Throwable t, long userId, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (userId > 0) {
      sendError(HttpServletResponse.SC_UNAUTHORIZED, t, request, response);

      return;
    }

    String redirect = PortalUtil.getPathMain().concat("/portal/login");

    String currentURL = PortalUtil.getCurrentURL(request);

    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
      try {
        Layout layout = LayoutLocalServiceUtil.getLayout(plid);

        Group group = layout.getGroup();

        plid = group.getDefaultPublicPlid();

        if ((plid == LayoutConstants.DEFAULT_PLID) || group.isStagingGroup()) {

          Group guestGroup =
              GroupLocalServiceUtil.getGroup(layout.getCompanyId(), GroupConstants.GUEST);

          plid = guestGroup.getDefaultPublicPlid();
        }

        redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
      } catch (Exception e) {
      }
    }

    response.sendRedirect(redirect);
  }

  protected boolean processShutdownRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    if (!ShutdownUtil.isShutdown()) {
      return false;
    }

    String messageKey = ShutdownUtil.getMessage();

    if (Validator.isNull(messageKey)) {
      messageKey = "the-system-is-shutdown-please-try-again-later";
    }

    processInactiveRequest(request, response, messageKey);

    return true;
  }

  protected void processStartupEvents() throws Exception {
    StartupAction startupAction = new StartupAction();

    startupAction.run(null);
  }

  protected HttpServletRequest protectRequest(HttpServletRequest request, String remoteUser) {

    // WebSphere will not return the remote user unless you are
    // authenticated AND accessing a protected path. Other servers will
    // return the remote user for all threads associated with an
    // authenticated user. We use ProtectedServletRequest to ensure we get
    // similar behavior across all servers.

    return new ProtectedServletRequest(request, remoteUser);
  }

  protected void sendError(
      int status, Throwable t, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    DynamicServletRequest dynamicRequest = new DynamicServletRequest(request);

    // Reset layout params or there will be an infinite loop

    dynamicRequest.setParameter("p_l_id", StringPool.BLANK);

    dynamicRequest.setParameter("groupId", StringPool.BLANK);
    dynamicRequest.setParameter("layoutId", StringPool.BLANK);
    dynamicRequest.setParameter("privateLayout", StringPool.BLANK);

    PortalUtil.sendError(status, (Exception) t, dynamicRequest, response);
  }

  protected void setPortalPort(HttpServletRequest request) {
    PortalUtil.setPortalPort(request);
  }

  protected void setPrincipal(long companyId, long userId, String remoteUser, String password) {

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

    String name = String.valueOf(userId);

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      long remoteUserId = 0;

      try {
        remoteUserId = JAASHelper.getJaasUserId(companyId, remoteUser);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(e);
        }
      }

      if (remoteUserId > 0) {
        name = String.valueOf(remoteUserId);
      }
    } else if (remoteUser != null) {
      name = remoteUser;
    }

    PrincipalThreadLocal.setName(name);

    PrincipalThreadLocal.setPassword(password);
  }

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_DEFAULT =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, ReleaseInfo.getName());

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_PARTIAL =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, "partial");

  private static final String _LIFERAY_PORTAL_REQUEST_HEADER = "Liferay-Portal";

  private static Log _log = LogFactoryUtil.getLog(MainServlet.class);
}
示例#14
0
  public static void upgrade() throws Exception {

    // Disable database caching before upgrade

    if (_log.isDebugEnabled()) {
      _log.debug("Disable cache registry");
    }

    CacheRegistryUtil.setActive(false);

    // Check release

    int buildNumber = ReleaseLocalServiceUtil.getBuildNumberOrCreate();

    if (buildNumber > ReleaseInfo.getParentBuildNumber()) {
      StringBundler sb = new StringBundler(6);

      sb.append("Attempting to deploy an older Liferay Portal version. ");
      sb.append("Current build version is ");
      sb.append(buildNumber);
      sb.append(" and attempting to deploy version ");
      sb.append(ReleaseInfo.getParentBuildNumber());
      sb.append(".");

      throw new IllegalStateException(sb.toString());
    } else if (buildNumber < ReleaseInfo.RELEASE_5_2_3_BUILD_NUMBER) {
      String msg = "You must first upgrade to Liferay Portal 5.2.3";

      System.out.println(msg);

      throw new RuntimeException(msg);
    }

    // Reload SQL

    CustomSQLUtil.reloadCustomSQL();
    SQLTransformer.reloadSQLTransformer();

    // Upgrade

    if (_log.isDebugEnabled()) {
      _log.debug("Update build " + buildNumber);
    }

    _checkPermissionAlgorithm();
    _checkReleaseState();

    if (PropsValues.UPGRADE_DATABASE_TRANSACTIONS_DISABLED) {
      _disableTransactions();
    }

    try {
      StartupHelperUtil.upgradeProcess(buildNumber);
    } catch (Exception e) {
      _updateReleaseState(ReleaseConstants.STATE_UPGRADE_FAILURE);

      throw e;
    } finally {
      if (PropsValues.UPGRADE_DATABASE_TRANSACTIONS_DISABLED) {
        _enableTransactions();
      }
    }

    // Update company key

    if (StartupHelperUtil.isUpgraded()) {
      if (_log.isDebugEnabled()) {
        _log.debug("Update company key");
      }

      _updateCompanyKey();
    }

    // Check class names

    if (_log.isDebugEnabled()) {
      _log.debug("Check class names");
    }

    ClassNameLocalServiceUtil.checkClassNames();

    // Check resource actions

    if (_log.isDebugEnabled()) {
      _log.debug("Check resource actions");
    }

    ResourceActionLocalServiceUtil.checkResourceActions();

    // Delete temporary images

    if (_log.isDebugEnabled()) {
      _log.debug("Delete temporary images");
    }

    _deleteTempImages();

    // Clear the caches only if the upgrade process was run

    if (_log.isDebugEnabled()) {
      _log.debug("Clear cache if upgrade process was run");
    }

    if (StartupHelperUtil.isUpgraded()) {
      MultiVMPoolUtil.clear();
    }
  }
示例#15
0
 public String getServerInfo() {
   return ReleaseInfo.getServerInfo();
 }
  protected void doImportLayouts(
      long userId,
      long groupId,
      boolean privateLayout,
      Map<String, String[]> parameterMap,
      File file)
      throws Exception {

    boolean deleteMissingLayouts =
        MapUtil.getBoolean(
            parameterMap,
            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
            Boolean.TRUE.booleanValue());
    boolean deletePortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
    boolean importCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importPublicLayoutPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLIC_LAYOUT_PERMISSIONS);
    boolean importUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean importPortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    boolean importPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean importPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean importPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean importTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean importThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean importLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean importLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);

    boolean layoutSetPrototypeLinkEnabled =
        MapUtil.getBoolean(
            parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED, true);

    Group group = GroupLocalServiceUtil.getGroup(groupId);

    if (group.isLayoutSetPrototype()) {
      layoutSetPrototypeLinkEnabled = false;
    }

    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    String layoutsImportMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
    String portletsMergeMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE);
    String userIdStrategy =
        MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

    if (_log.isDebugEnabled()) {
      _log.debug("Delete portlet data " + deletePortletData);
      _log.debug("Import categories " + importCategories);
      _log.debug("Import permissions " + importPermissions);
      _log.debug("Import user permissions " + importUserPermissions);
      _log.debug("Import portlet data " + importPortletData);
      _log.debug("Import portlet setup " + importPortletSetup);
      _log.debug("Import portlet archived setups " + importPortletArchivedSetups);
      _log.debug("Import portlet user preferences " + importPortletUserPreferences);
      _log.debug("Import theme " + importTheme);
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();

    User user = UserUtil.findByPrimaryKey(userId);

    UserIdStrategy strategy = _portletImporter.getUserIdStrategy(user, userIdStrategy);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), strategy, zipReader);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPrivateLayout(privateLayout);

    // Zip

    Element rootElement = null;
    InputStream themeZip = null;

    // Manifest

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    if (xml == null) {
      throw new LARFileException("manifest.xml not found in the LAR");
    }

    try {
      Document document = SAXReaderUtil.read(xml);

      rootElement = document.getRootElement();
    } catch (Exception e) {
      throw new LARFileException(e);
    }

    // Build compatibility

    Element headerElement = rootElement.element("header");

    int buildNumber = ReleaseInfo.getBuildNumber();

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type compatibility

    String larType = headerElement.attributeValue("type");

    if (!larType.equals("layout-set") && !larType.equals("layout-set-prototype")) {

      throw new LARTypeException("Invalid type of LAR file (" + larType + ")");
    }

    // Group id

    long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

    portletDataContext.setSourceGroupId(sourceGroupId);

    // Layout set prototype

    if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) {

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      String layoutSetPrototypeUuid =
          GetterUtil.getString(headerElement.attributeValue("type-uuid"));

      LayoutSetPrototype existingLayoutSetPrototype = null;

      if (Validator.isNotNull(layoutSetPrototypeUuid)) {
        try {
          existingLayoutSetPrototype =
              LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(
                  layoutSetPrototypeUuid);
        } catch (NoSuchLayoutSetPrototypeException nslspe) {
        }
      }

      if (existingLayoutSetPrototype == null) {
        layoutSetPrototype.setUuid(layoutSetPrototypeUuid);

        LayoutSetPrototypeLocalServiceUtil.updateLayoutSetPrototype(layoutSetPrototype);
      }
    }

    Element layoutsElement = rootElement.element("layouts");

    String layoutSetPrototypeUuid = layoutsElement.attributeValue("layout-set-prototype-uuid");

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      if (layoutSetPrototypeLinkEnabled) {
        if (publishToRemote) {
          importLayoutSetPrototype(
              portletDataContext, user, layoutSetPrototypeUuid, serviceContext);
        }
      }

      layoutSet.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid);
      layoutSet.setLayoutSetPrototypeLinkEnabled(layoutSetPrototypeLinkEnabled);

      LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
    }

    // Look and feel

    if (importTheme) {
      themeZip = portletDataContext.getZipEntryAsInputStream("theme.zip");
    }

    // Look and feel

    String themeId = layoutSet.getThemeId();
    String colorSchemeId = layoutSet.getColorSchemeId();

    if (importThemeSettings) {
      Attribute themeIdAttribute = headerElement.attribute("theme-id");

      if (themeIdAttribute != null) {
        themeId = themeIdAttribute.getValue();
      }

      Attribute colorSchemeIdAttribute = headerElement.attribute("color-scheme-id");

      if (colorSchemeIdAttribute != null) {
        colorSchemeId = colorSchemeIdAttribute.getValue();
      }
    }

    if (importLogo) {
      String logoPath = headerElement.attributeValue("logo-path");

      byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(logoPath);

      if ((iconBytes != null) && (iconBytes.length > 0)) {
        File logo = FileUtil.createTempFile(iconBytes);

        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, true, logo);
      } else {
        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, false, (File) null);
      }
    }

    if (importLayoutSetSettings) {
      String settings = GetterUtil.getString(headerElement.elementText("settings"));

      LayoutSetLocalServiceUtil.updateSettings(groupId, privateLayout, settings);
    }

    String css = GetterUtil.getString(headerElement.elementText("css"));

    if (themeZip != null) {
      String importThemeId = importTheme(layoutSet, themeZip);

      if (importThemeId != null) {
        themeId = importThemeId;
        colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Importing theme takes " + stopWatch.getTime() + " ms");
      }
    }

    boolean wapTheme = false;

    LayoutSetLocalServiceUtil.updateLookAndFeel(
        groupId, privateLayout, themeId, colorSchemeId, css, wapTheme);

    // Read asset categories, asset tags, comments, locks, permissions, and
    // ratings entries to make them available to the data handlers through
    // the context

    if (importPermissions) {
      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    if (importCategories) {
      _portletImporter.readAssetCategories(portletDataContext);
    }

    _portletImporter.readAssetTags(portletDataContext);
    _portletImporter.readComments(portletDataContext);
    _portletImporter.readExpandoTables(portletDataContext);
    _portletImporter.readLocks(portletDataContext);
    _portletImporter.readRatingsEntries(portletDataContext);

    // Layouts

    List<Layout> previousLayouts = LayoutUtil.findByG_P(groupId, privateLayout);

    // Remove layouts that were deleted from the layout set prototype

    if (Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeLinkEnabled) {

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup();

      for (Layout layout : previousLayouts) {
        String sourcePrototypeLayoutUuid = layout.getSourcePrototypeLayoutUuid();

        if (Validator.isNull(layout.getSourcePrototypeLayoutUuid())) {
          continue;
        }

        Layout sourcePrototypeLayout =
            LayoutUtil.fetchByUUID_G(
                sourcePrototypeLayoutUuid, layoutSetPrototypeGroup.getGroupId());

        if (sourcePrototypeLayout == null) {
          LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext);
        }
      }
    }

    List<Layout> newLayouts = new ArrayList<Layout>();

    Set<Long> newLayoutIds = new HashSet<Long>();

    Map<Long, Layout> newLayoutsMap =
        (Map<Long, Layout>) portletDataContext.getNewPrimaryKeysMap(Layout.class);

    List<Element> layoutElements = layoutsElement.elements("layout");

    if (_log.isDebugEnabled()) {
      if (layoutElements.size() > 0) {
        _log.debug("Importing layouts");
      }
    }

    for (Element layoutElement : layoutElements) {
      importLayout(
          portletDataContext,
          user,
          layoutCache,
          previousLayouts,
          newLayouts,
          newLayoutsMap,
          newLayoutIds,
          portletsMergeMode,
          themeId,
          colorSchemeId,
          layoutsImportMode,
          privateLayout,
          importPermissions,
          importPublicLayoutPermissions,
          importUserPermissions,
          importThemeSettings,
          rootElement,
          layoutElement);
    }

    Element portletsElement = rootElement.element("portlets");

    List<Element> portletElements = portletsElement.elements("portlet");

    // Delete portlet data

    if (deletePortletData) {
      if (_log.isDebugEnabled()) {
        if (portletElements.size() > 0) {
          _log.debug("Deleting portlet data");
        }
      }

      for (Element portletElement : portletElements) {
        String portletId = portletElement.attributeValue("portlet-id");
        long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
        long plid = newLayoutsMap.get(layoutId).getPlid();

        portletDataContext.setPlid(plid);

        _portletImporter.deletePortletData(portletDataContext, portletId, plid);
      }
    }

    // Import portlets

    if (_log.isDebugEnabled()) {
      if (portletElements.size() > 0) {
        _log.debug("Importing portlets");
      }
    }

    for (Element portletElement : portletElements) {
      String portletPath = portletElement.attributeValue("path");
      String portletId = portletElement.attributeValue("portlet-id");
      long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
      long plid = newLayoutsMap.get(layoutId).getPlid();
      long oldPlid = GetterUtil.getLong(portletElement.attributeValue("old-plid"));

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

      if (!portlet.isActive() || portlet.isUndeployedPortlet()) {
        continue;
      }

      Layout layout = null;

      try {
        layout = LayoutUtil.findByPrimaryKey(plid);
      } catch (NoSuchLayoutException nsle) {
        continue;
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(oldPlid);

      Document portletDocument =
          SAXReaderUtil.read(portletDataContext.getZipEntryAsString(portletPath));

      portletElement = portletDocument.getRootElement();

      // The order of the import is important. You must always import
      // the portlet preferences first, then the portlet data, then
      // the portlet permissions. The import of the portlet data
      // assumes that portlet preferences already exist.

      _portletImporter.setPortletScope(portletDataContext, portletElement);

      try {

        // Portlet preferences

        _portletImporter.importPortletPreferences(
            portletDataContext,
            layoutSet.getCompanyId(),
            layout.getGroupId(),
            layout,
            null,
            portletElement,
            importPortletSetup,
            importPortletArchivedSetups,
            importPortletUserPreferences,
            false);

        // Portlet data

        Element portletDataElement = portletElement.element("portlet-data");

        if (importPortletData && (portletDataElement != null)) {
          _portletImporter.importPortletData(
              portletDataContext, portletId, plid, portletDataElement);
        }
      } finally {
        _portletImporter.resetPortletScope(portletDataContext, layout.getGroupId());
      }

      // Portlet permissions

      if (importPermissions) {
        _permissionImporter.importPortletPermissions(
            layoutCache,
            companyId,
            groupId,
            userId,
            layout,
            portletElement,
            portletId,
            importUserPermissions);
      }

      // Archived setups

      _portletImporter.importPortletPreferences(
          portletDataContext,
          layoutSet.getCompanyId(),
          groupId,
          null,
          null,
          portletElement,
          importPortletSetup,
          importPortletArchivedSetups,
          importPortletUserPreferences,
          false);
    }

    if (importPermissions) {
      if ((userId > 0)
          && ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5)
              || (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) {

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        indexer.reindex(userId);
      }
    }

    // Asset links

    _portletImporter.readAssetLinks(portletDataContext);

    // Delete missing layouts

    if (deleteMissingLayouts) {
      deleteMissingLayouts(groupId, privateLayout, newLayoutIds, previousLayouts, serviceContext);
    }

    // Page count

    LayoutSetLocalServiceUtil.updatePageCount(groupId, privateLayout);

    if (_log.isInfoEnabled()) {
      _log.info("Importing layouts takes " + stopWatch.getTime() + " ms");
    }

    // Site

    GroupLocalServiceUtil.updateSite(groupId, true);

    // Web content layout type

    for (Layout layout : newLayouts) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

      String articleId = typeSettingsProperties.getProperty("article-id");

      if (Validator.isNotNull(articleId)) {
        Map<String, String> articleIds =
            (Map<String, String>)
                portletDataContext.getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

        typeSettingsProperties.setProperty(
            "article-id", MapUtil.getString(articleIds, articleId, articleId));

        LayoutUtil.update(layout, false);
      }
    }

    zipReader.close();
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export user permissions " + exportUserPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if (image != null) {
        String logoPath = getLayoutSetLogoPath(portletDataContext);

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Portlet layoutConfigurationPortlet =
        PortletLocalServiceUtil.getPortletById(
            portletDataContext.getCompanyId(), PortletKeys.LAYOUT_CONFIGURATION);

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = null;

    if ((layoutIds == null) || (layoutIds.length == 0)) {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);
    } else {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds);
    }

    List<Portlet> portlets = getAlwaysExportablePortlets(companyId);

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      if (group.isStagingGroup()) {
        group = group.getLiveGroup();
      }

      for (Portlet portlet : portlets) {
        String portletId = portlet.getRootPortletId();

        if (!group.isStagedPortlet(portletId)) {
          continue;
        }

        String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

        if (portletIds.get(key) == null) {
          portletIds.put(
              key,
              new Object[] {
                portletId, firstLayout.getPlid(), groupId, StringPool.BLANK, StringPool.BLANK
              });
        }
      }
    }

    Element layoutsElement = rootElement.addElement("layouts");

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      if (publishToRemote) {
        String path = getLayoutSetPrototype(portletDataContext, layoutSetPrototypeUuid);

        File layoutSetPrototypeFile = null;

        InputStream inputStream = null;

        try {
          layoutSetPrototypeFile =
              SitesUtil.exportLayoutSetPrototype(layoutSetPrototype, serviceContext);

          inputStream = new FileInputStream(layoutSetPrototypeFile);

          portletDataContext.addZipEntry(path.concat(".lar"), inputStream);
          portletDataContext.addZipEntry(path.concat(".xml"), layoutSetPrototype);
        } finally {
          StreamUtil.cleanUp(inputStream);

          FileUtil.delete(layoutSetPrototypeFile);
        }
      }
    }

    for (Layout layout : layouts) {
      exportLayout(
          portletDataContext,
          layoutConfigurationPortlet,
          layoutCache,
          portlets,
          portletIds,
          exportPermissions,
          exportUserPermissions,
          layout,
          layoutsElement);
    }

    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
      Element rolesElement = rootElement.addElement("roles");

      if (exportPermissions) {
        _permissionExporter.exportLayoutRoles(layoutCache, companyId, groupId, rolesElement);
      }
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = 0;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.getLayout(plid);

      portletDataContext.setPlid(layout.getPlid());
      portletDataContext.setOldPlid(layout.getPlid());
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, portletDataContext, parameterMap);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletArchivedSetups,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletUserPreferences,
          exportUserPermissions);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
示例#18
0
  protected void doRun(String[] ids) throws Exception {

    // Print release information

    System.out.println("Starting " + ReleaseInfo.getReleaseInfo());

    // Portal resiliency

    DistributedRegistry.registerDistributed(
        ComponentConstants.COMPONENT_CONTEXT, Direction.DUPLEX, MatchType.POSTFIX);
    DistributedRegistry.registerDistributed(
        MimeResponse.MARKUP_HEAD_ELEMENT, Direction.DUPLEX, MatchType.EXACT);
    DistributedRegistry.registerDistributed(
        PortletRequest.LIFECYCLE_PHASE, Direction.DUPLEX, MatchType.EXACT);
    DistributedRegistry.registerDistributed(WebKeys.class);

    Intraband intraband = MPIHelperUtil.getIntraband();

    intraband.registerDatagramReceiveHandler(
        SystemDataType.MAILBOX.getValue(), new MailboxDatagramReceiveHandler());

    MessageBus messageBus = (MessageBus) PortalBeanLocatorUtil.locate(MessageBus.class.getName());

    intraband.registerDatagramReceiveHandler(
        SystemDataType.MESSAGE.getValue(), new MessageDatagramReceiveHandler(messageBus));

    intraband.registerDatagramReceiveHandler(
        SystemDataType.PROXY.getValue(), new IntrabandProxyDatagramReceiveHandler());

    intraband.registerDatagramReceiveHandler(
        SystemDataType.RPC.getValue(), new RPCDatagramReceiveHandler());

    // Shutdown hook

    if (_log.isDebugEnabled()) {
      _log.debug("Add shutdown hook");
    }

    Runtime runtime = Runtime.getRuntime();

    runtime.addShutdownHook(new Thread(new ShutdownHook()));

    // Template manager

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize template manager");
    }

    TemplateManagerUtil.init();

    // Indexers

    IndexerRegistryUtil.register(new MBMessageIndexer());
    IndexerRegistryUtil.register(new PluginPackageIndexer());

    // Upgrade

    if (_log.isDebugEnabled()) {
      _log.debug("Upgrade database");
    }

    DBUpgrader.upgrade();

    // Clear locks

    if (_log.isDebugEnabled()) {
      _log.debug("Clear locks");
    }

    try {
      LockLocalServiceUtil.clear();
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Unable to clear locks because Lock table does not exist");
      }
    }

    // Messaging

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize message bus");
    }

    MessageSender messageSender =
        (MessageSender) PortalBeanLocatorUtil.locate(MessageSender.class.getName());
    SynchronousMessageSender synchronousMessageSender =
        (SynchronousMessageSender)
            PortalBeanLocatorUtil.locate(SynchronousMessageSender.class.getName());

    MessageBusUtil.init(
        DoPrivilegedUtil.wrap(messageBus),
        DoPrivilegedUtil.wrap(messageSender),
        DoPrivilegedUtil.wrap(synchronousMessageSender));

    // Cluster executor

    ClusterExecutorUtil.initialize();

    if (!SPIUtil.isSPI()) {
      ClusterMasterExecutorUtil.initialize();
    }

    // Ehache bootstrap

    EhcacheStreamBootstrapCacheLoader.start();

    // Scheduler

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize scheduler engine lifecycle");
    }

    SchedulerEngineHelperUtil.initialize();

    // Verify

    if (_log.isDebugEnabled()) {
      _log.debug("Verify database");
    }

    DBUpgrader.verify();

    // Background tasks

    if (!ClusterMasterExecutorUtil.isEnabled()) {
      BackgroundTaskLocalServiceUtil.cleanUpBackgroundTasks();
    }

    // Liferay JspFactory

    JspFactorySwapper.swap();

    // Jericho

    CachedLoggerProvider.install();
  }
示例#19
0
  public static void verify() throws Exception {

    // Check release

    Release release = null;

    try {
      release =
          ReleaseLocalServiceUtil.getRelease(
              ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME, ReleaseInfo.getParentBuildNumber());
    } catch (PortalException pe) {
      release =
          ReleaseLocalServiceUtil.addRelease(
              ReleaseConstants.DEFAULT_SERVLET_CONTEXT_NAME, ReleaseInfo.getParentBuildNumber());
    }

    _checkReleaseState();

    // Update indexes

    if (PropsValues.DATABASE_INDEXES_UPDATE_ON_STARTUP) {
      StartupHelperUtil.setDropIndexes(true);

      StartupHelperUtil.updateIndexes();
    } else if (StartupHelperUtil.isUpgraded()) {
      StartupHelperUtil.updateIndexes();
    }

    // Verify

    if (PropsValues.VERIFY_DATABASE_TRANSACTIONS_DISABLED) {
      _disableTransactions();
    }

    try {
      StartupHelperUtil.verifyProcess(release.isVerified());
    } catch (Exception e) {
      _updateReleaseState(ReleaseConstants.STATE_VERIFY_FAILURE);

      throw e;
    } finally {
      if (PropsValues.VERIFY_DATABASE_TRANSACTIONS_DISABLED) {
        _enableTransactions();
      }
    }

    // Update indexes

    if (PropsValues.DATABASE_INDEXES_UPDATE_ON_STARTUP || StartupHelperUtil.isUpgraded()) {

      StartupHelperUtil.updateIndexes(false);
    }

    // Update release

    boolean verified = StartupHelperUtil.isVerified();

    if (release.isVerified()) {
      verified = true;
    }

    ReleaseLocalServiceUtil.updateRelease(
        release.getReleaseId(),
        ReleaseInfo.getParentBuildNumber(),
        ReleaseInfo.getBuildDate(),
        verified);

    // Enable database caching after verify

    CacheRegistryUtil.setActive(true);
  }
  protected File doExportPortletInfoAsFile(
      long plid,
      long groupId,
      String portletId,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);

    boolean exportPortletData = false;

    if (parameterMap.containsKey(
        PortletDataHandlerKeys.PORTLET_DATA + "_" + PortletConstants.getRootPortletId(portletId))) {

      exportPortletData =
          MapUtil.getBoolean(
              parameterMap,
              PortletDataHandlerKeys.PORTLET_DATA
                  + "_"
                  + PortletConstants.getRootPortletId(portletId));
    } else {
      exportPortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    }

    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet data " + exportPortletData);
      _log.debug("Export all portlet data " + exportPortletDataAll);
      _log.debug("Export portlet setup " + exportPortletSetup);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export user permissions " + exportUserPermissions);
    }

    if (exportPortletDataAll) {
      exportPortletData = true;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    if (!layout.isTypeControlPanel() && !layout.isTypePanel() && !layout.isTypePortlet()) {

      throw new LayoutImportException("Layout type " + layout.getType() + " is not valid");
    }

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    long scopeGroupId = groupId;

    javax.portlet.PortletPreferences jxPreferences =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

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

    if (Validator.isNotNull(scopeType)) {
      Group scopeGroup = null;

      if (scopeType.equals("company")) {
        scopeGroup = GroupLocalServiceUtil.getCompanyGroup(layout.getCompanyId());
      } else if (Validator.isNotNull(scopeLayoutUuid)) {
        scopeGroup = layout.getScopeGroup();
      }

      if (scopeGroup != null) {
        scopeGroupId = scopeGroup.getGroupId();
      }
    }

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            layout.getCompanyId(),
            scopeGroupId,
            parameterMap,
            new HashSet<String>(),
            startDate,
            endDate,
            zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPlid(plid);
    portletDataContext.setOldPlid(plid);
    portletDataContext.setScopeType(scopeType);
    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("type", "portlet");
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", PortletConstants.getRootPortletId(portletId));

    exportPortlet(
        portletDataContext,
        layoutCache,
        portletId,
        layout,
        rootElement,
        defaultUserId,
        exportPermissions,
        exportPortletArchivedSetups,
        exportPortletData,
        exportPortletSetup,
        exportPortletUserPreferences,
        exportUserPermissions);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    exportAssetLinks(portletDataContext);
    exportAssetTags(portletDataContext);
    exportComments(portletDataContext);
    exportExpandoTables(portletDataContext);
    exportLocks(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    exportRatingsEntries(portletDataContext, rootElement);

    if (_log.isInfoEnabled()) {
      _log.info("Exporting portlet took " + stopWatch.getTime() + " ms");
    }

    try {
      portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }

    return zipWriter.getFile();
  }
  private Set<String> _readThemes(
      String servletContextName,
      ServletContext servletContext,
      String themesPath,
      boolean loadFromServletContext,
      String xml,
      PluginPackage pluginPackage)
      throws Exception {

    Set<String> themeIds = new HashSet<String>();

    if (xml == null) {
      return themeIds;
    }

    Document document = SAXReaderUtil.read(xml, true);

    Element rootElement = document.getRootElement();

    Version portalVersion = _getVersion(ReleaseInfo.getVersion());

    boolean compatible = false;

    Element compatibilityElement = rootElement.element("compatibility");

    if (compatibilityElement != null) {
      List<Element> versionElements = compatibilityElement.elements("version");

      for (Element versionElement : versionElements) {
        Version version = _getVersion(versionElement.getTextTrim());

        if (version.includes(portalVersion)) {
          compatible = true;

          break;
        }
      }
    }

    if (!compatible) {
      _log.error("Themes in this WAR are not compatible with " + ReleaseInfo.getServerInfo());

      return themeIds;
    }

    ThemeCompanyLimit companyLimit = null;

    Element companyLimitElement = rootElement.element("company-limit");

    if (companyLimitElement != null) {
      companyLimit = new ThemeCompanyLimit();

      Element companyIncludesElement = companyLimitElement.element("company-includes");

      if (companyIncludesElement != null) {
        companyLimit.setIncludes(_getCompanyLimitIncludes(companyIncludesElement));
      }

      Element companyExcludesElement = companyLimitElement.element("company-excludes");

      if (companyExcludesElement != null) {
        companyLimit.setExcludes(_getCompanyLimitExcludes(companyExcludesElement));
      }
    }

    ThemeGroupLimit groupLimit = null;

    Element groupLimitElement = rootElement.element("group-limit");

    if (groupLimitElement != null) {
      groupLimit = new ThemeGroupLimit();

      Element groupIncludesElement = groupLimitElement.element("group-includes");

      if (groupIncludesElement != null) {
        groupLimit.setIncludes(_getGroupLimitIncludes(groupIncludesElement));
      }

      Element groupExcludesElement = groupLimitElement.element("group-excludes");

      if (groupExcludesElement != null) {
        groupLimit.setExcludes(_getGroupLimitExcludes(groupExcludesElement));
      }
    }

    long timestamp = ServletContextUtil.getLastModified(servletContext);

    List<Element> themeElements = rootElement.elements("theme");

    for (Element themeElement : themeElements) {
      ContextReplace themeContextReplace = new ContextReplace();

      themeContextReplace.addValue("themes-path", themesPath);

      String themeId = themeElement.attributeValue("id");

      if (servletContextName != null) {
        themeId = themeId + PortletConstants.WAR_SEPARATOR + servletContextName;
      }

      themeId = PortalUtil.getJsSafePortletId(themeId);

      themeContextReplace.addValue("theme-id", themeId);

      themeIds.add(themeId);

      Theme theme = _themes.get(themeId);

      if (theme == null) {
        theme = new ThemeImpl(themeId);
      }

      theme.setTimestamp(timestamp);

      PluginSetting pluginSetting = pluginSettingLocalService.getDefaultPluginSetting();

      theme.setPluginPackage(pluginPackage);
      theme.setDefaultPluginSetting(pluginSetting);

      theme.setThemeCompanyLimit(companyLimit);
      theme.setThemeGroupLimit(groupLimit);

      if (servletContextName != null) {
        theme.setServletContextName(servletContextName);
      }

      theme.setLoadFromServletContext(loadFromServletContext);

      String name = GetterUtil.getString(themeElement.attributeValue("name"), theme.getName());

      String rootPath =
          GetterUtil.getString(themeElement.elementText("root-path"), theme.getRootPath());

      rootPath = themeContextReplace.replace(rootPath);

      themeContextReplace.addValue("root-path", rootPath);

      String templatesPath =
          GetterUtil.getString(
              themeElement.elementText("templates-path"), theme.getTemplatesPath());

      templatesPath = themeContextReplace.replace(templatesPath);
      templatesPath = StringUtil.safePath(templatesPath);

      themeContextReplace.addValue("templates-path", templatesPath);

      String cssPath =
          GetterUtil.getString(themeElement.elementText("css-path"), theme.getCssPath());

      cssPath = themeContextReplace.replace(cssPath);
      cssPath = StringUtil.safePath(cssPath);

      themeContextReplace.addValue("css-path", cssPath);

      String imagesPath =
          GetterUtil.getString(themeElement.elementText("images-path"), theme.getImagesPath());

      imagesPath = themeContextReplace.replace(imagesPath);
      imagesPath = StringUtil.safePath(imagesPath);

      themeContextReplace.addValue("images-path", imagesPath);

      String javaScriptPath =
          GetterUtil.getString(
              themeElement.elementText("javascript-path"), theme.getJavaScriptPath());

      javaScriptPath = themeContextReplace.replace(javaScriptPath);
      javaScriptPath = StringUtil.safePath(javaScriptPath);

      themeContextReplace.addValue("javascript-path", javaScriptPath);

      String virtualPath =
          GetterUtil.getString(themeElement.elementText("virtual-path"), theme.getVirtualPath());

      String templateExtension =
          GetterUtil.getString(
              themeElement.elementText("template-extension"), theme.getTemplateExtension());

      theme.setName(name);
      theme.setRootPath(rootPath);
      theme.setTemplatesPath(templatesPath);
      theme.setCssPath(cssPath);
      theme.setImagesPath(imagesPath);
      theme.setJavaScriptPath(javaScriptPath);
      theme.setVirtualPath(virtualPath);
      theme.setTemplateExtension(templateExtension);

      Element settingsElement = themeElement.element("settings");

      if (settingsElement != null) {
        List<Element> settingElements = settingsElement.elements("setting");

        for (Element settingElement : settingElements) {
          boolean configurable =
              GetterUtil.getBoolean(settingElement.attributeValue("configurable"));
          String key = settingElement.attributeValue("key");
          String[] options = StringUtil.split(settingElement.attributeValue("options"));
          String type = settingElement.attributeValue("type");
          String value = settingElement.attributeValue("value");
          String script = settingElement.getTextTrim();

          theme.addSetting(key, value, configurable, type, options, script);
        }
      }

      theme.setWapTheme(
          GetterUtil.getBoolean(themeElement.elementText("wap-theme"), theme.isWapTheme()));

      Element rolesElement = themeElement.element("roles");

      if (rolesElement != null) {
        List<Element> roleNameElements = rolesElement.elements("role-name");

        for (Element roleNameElement : roleNameElements) {
          pluginSetting.addRole(roleNameElement.getText());
        }
      }

      _readColorSchemes(themeElement, theme.getColorSchemesMap(), themeContextReplace);
      _readColorSchemes(themeElement, theme.getColorSchemesMap(), themeContextReplace);

      Element layoutTemplatesElement = themeElement.element("layout-templates");

      if (layoutTemplatesElement != null) {
        Element standardElement = layoutTemplatesElement.element("standard");

        if (standardElement != null) {
          layoutTemplateLocalService.readLayoutTemplate(
              servletContextName,
              servletContext,
              null,
              standardElement,
              true,
              themeId,
              pluginPackage);
        }

        Element customElement = layoutTemplatesElement.element("custom");

        if (customElement != null) {
          layoutTemplateLocalService.readLayoutTemplate(
              servletContextName,
              servletContext,
              null,
              customElement,
              false,
              themeId,
              pluginPackage);
        }
      }

      if (!theme.isWapTheme()) {
        _setSpriteImages(servletContext, theme, imagesPath);
      }

      if (!_themes.containsKey(themeId)) {
        _themes.put(themeId, theme);
      }
    }

    return themeIds;
  }
/**
 * @author Alexander Chow
 * @author Brian Wing Shun Chan
 */
public class WebServerServlet extends HttpServlet {

  /** @see com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter */
  public static boolean hasFiles(HttpServletRequest request) {
    try {

      // Do not use permission checking since this may be called from
      // other contexts that are also managing the principal

      User user = _getUser(request);

      String path = HttpUtil.fixPath(request.getPathInfo());

      String[] pathArray = StringUtil.split(path, CharPool.SLASH);

      if (pathArray.length == 0) {
        return true;
      } else if (_PATH_DDM.equals(pathArray[0])) {
        _checkDDMRecord(pathArray);
      } else if (Validator.isNumber(pathArray[0])) {
        _checkFileEntry(pathArray);
      } else {
        long groupId = _getGroupId(user.getCompanyId(), pathArray[0]);
        long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;

        for (int i = 1; i < pathArray.length; i++) {
          try {
            Folder folder = DLAppLocalServiceUtil.getFolder(groupId, folderId, pathArray[i]);

            folderId = folder.getFolderId();
          } catch (NoSuchFolderException nsfe) {
            if (i != (pathArray.length - 1)) {
              return false;
            }

            pathArray =
                new String[] {String.valueOf(groupId), String.valueOf(folderId), pathArray[i]};

            _checkFileEntry(pathArray);
          }
        }
      }
    } catch (Exception e) {
      return false;
    }

    return true;
  }

  @Override
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    _lastModified = GetterUtil.getBoolean(servletConfig.getInitParameter("last_modified"), true);
  }

  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    User user = null;

    try {
      user = _getUser(request);

      PrincipalThreadLocal.setName(user.getUserId());
      PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      if (_lastModified) {
        long lastModified = getLastModified(request);

        if (lastModified > 0) {
          long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);

          if ((ifModifiedSince > 0) && (ifModifiedSince == lastModified)) {

            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
          }
        }

        if (lastModified > 0) {
          response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
        }
      }

      String path = HttpUtil.fixPath(request.getPathInfo());
      String[] pathArray = StringUtil.split(path, CharPool.SLASH);

      if (pathArray.length == 0) {
        sendGroups(response, user, request.getServletPath() + StringPool.SLASH + path);
      } else {
        if (_PATH_DDM.equals(pathArray[0])) {
          sendDDMRecordFile(request, response, pathArray);
        } else if (Validator.isNumber(pathArray[0])) {
          sendFile(request, response, user, pathArray);
        } else {
          if (isLegacyImageGalleryImageId(request, response)) {
            return;
          }

          Image image = getImage(request, true);

          if (image != null) {
            writeImage(image, request, response);
          } else {
            sendDocumentLibrary(
                request,
                response,
                user,
                request.getServletPath() + StringPool.SLASH + path,
                pathArray);
          }
        }
      }
    } catch (NoSuchFileEntryException nsfee) {
      PortalUtil.sendError(HttpServletResponse.SC_NOT_FOUND, nsfee, request, response);
    } catch (PrincipalException pe) {
      processPrincipalException(pe, user, request, response);
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);
    }
  }

  protected Image convertFileEntry(boolean smallImage, FileEntry fileEntry)
      throws PortalException, SystemException {

    try {
      Image image = new ImageImpl();

      image.setModifiedDate(fileEntry.getModifiedDate());

      InputStream is = null;

      if (smallImage) {
        is = ImageProcessorUtil.getThumbnailAsStream(fileEntry.getFileVersion(), 0);
      } else {
        is = fileEntry.getContentStream();
      }

      byte[] bytes = FileUtil.getBytes(is);

      image.setTextObj(bytes);

      image.setType(fileEntry.getExtension());

      return image;
    } catch (PortalException pe) {
      throw pe;
    } catch (SystemException se) {
      throw se;
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }

  protected Image getDefaultImage(HttpServletRequest request, long imageId) {
    String path = GetterUtil.getString(request.getPathInfo());

    if (path.startsWith("/company_logo")
        || path.startsWith("/layout_set_logo")
        || path.startsWith("/logo")) {

      return ImageLocalServiceUtil.getDefaultCompanyLogo();
    } else if (path.startsWith("/organization_logo")) {
      return ImageLocalServiceUtil.getDefaultOrganizationLogo();
    } else if (path.startsWith("/user_female_portrait")) {
      return ImageLocalServiceUtil.getDefaultUserFemalePortrait();
    } else if (path.startsWith("/user_male_portrait")) {
      return ImageLocalServiceUtil.getDefaultUserMalePortrait();
    } else if (path.startsWith("/user_portrait")) {
      return ImageLocalServiceUtil.getDefaultUserMalePortrait();
    } else {
      return null;
    }
  }

  protected FileEntry getFileEntry(String[] pathArray) throws Exception {
    if (pathArray.length == 1) {
      long dlFileShortcutId = GetterUtil.getLong(pathArray[0]);

      DLFileShortcut dlFileShortcut = DLAppServiceUtil.getFileShortcut(dlFileShortcutId);

      return DLAppServiceUtil.getFileEntry(dlFileShortcut.getToFileEntryId());
    } else if (pathArray.length == 2) {
      long groupId = GetterUtil.getLong(pathArray[0]);

      return DLAppServiceUtil.getFileEntryByUuidAndGroupId(pathArray[1], groupId);
    } else if (pathArray.length == 3) {
      long groupId = GetterUtil.getLong(pathArray[0]);
      long folderId = GetterUtil.getLong(pathArray[1]);

      String fileName = pathArray[2];

      if (fileName.contains(StringPool.QUESTION)) {
        fileName = fileName.substring(0, fileName.indexOf(StringPool.QUESTION));
      }

      return DLAppServiceUtil.getFileEntry(groupId, folderId, fileName);
    } else {
      long groupId = GetterUtil.getLong(pathArray[0]);

      String uuid = pathArray[3];

      return DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);
    }
  }

  protected Image getImage(HttpServletRequest request, boolean getDefault)
      throws PortalException, SystemException {

    Image image = null;

    long imageId = getImageId(request);

    if (imageId > 0) {
      image = ImageServiceUtil.getImage(imageId);

      String path = GetterUtil.getString(request.getPathInfo());

      if (path.startsWith("/user_female_portrait")
          || path.startsWith("/user_male_portrait")
          || path.startsWith("/user_portrait")) {

        image = getUserPortraitImageResized(image, imageId);
      }
    } else {
      String uuid = ParamUtil.getString(request, "uuid");
      long groupId = ParamUtil.getLong(request, "groupId");
      boolean igSmallImage = ParamUtil.getBoolean(request, "igSmallImage");

      if (Validator.isNotNull(uuid) && (groupId > 0)) {
        try {
          FileEntry fileEntry = DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);

          image = convertFileEntry(igSmallImage, fileEntry);
        } catch (Exception e) {
        }
      }
    }

    if (getDefault) {
      if (image == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Get a default image for " + imageId);
        }

        image = getDefaultImage(request, imageId);
      }
    }

    return image;
  }

  protected byte[] getImageBytes(HttpServletRequest request, Image image) {
    try {
      if (!PropsValues.IMAGE_AUTO_SCALE) {
        return image.getTextObj();
      }

      ImageBag imageBag = null;

      if (image.getImageId() == 0) {
        imageBag = ImageToolUtil.read(image.getTextObj());

        RenderedImage renderedImage = imageBag.getRenderedImage();

        image.setHeight(renderedImage.getHeight());
        image.setWidth(renderedImage.getWidth());
      }

      int height = ParamUtil.getInteger(request, "height", image.getHeight());
      int width = ParamUtil.getInteger(request, "width", image.getWidth());

      if ((height >= image.getHeight()) && (width >= image.getWidth())) {
        return image.getTextObj();
      }

      if (image.getImageId() != 0) {
        imageBag = ImageToolUtil.read(image.getTextObj());
      }

      RenderedImage renderedImage = ImageToolUtil.scale(imageBag.getRenderedImage(), height, width);

      return ImageToolUtil.getBytes(renderedImage, imageBag.getType());
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Error scaling image " + image.getImageId(), e);
      }
    }

    return image.getTextObj();
  }

  protected long getImageId(HttpServletRequest request) {

    // The image id may be passed in as image_id, img_id, or i_id

    long imageId = ParamUtil.getLong(request, "image_id");

    if (imageId <= 0) {
      imageId = ParamUtil.getLong(request, "img_id");
    }

    if (imageId <= 0) {
      imageId = ParamUtil.getLong(request, "i_id");
    }

    if (imageId <= 0) {
      long companyId = ParamUtil.getLong(request, "companyId");
      String screenName = ParamUtil.getString(request, "screenName");

      try {
        if ((companyId > 0) && Validator.isNotNull(screenName)) {
          User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName);

          imageId = user.getPortraitId();
        }
      } catch (Exception e) {
      }
    }

    return imageId;
  }

  @Override
  protected long getLastModified(HttpServletRequest request) {
    try {
      Date modifiedDate = null;

      Image image = getImage(request, true);

      if (image != null) {
        modifiedDate = image.getModifiedDate();
      } else {
        String path = HttpUtil.fixPath(request.getPathInfo());

        String[] pathArray = StringUtil.split(path, CharPool.SLASH);

        if (pathArray.length == 0) {
          return -1;
        }

        if (pathArray[0].equals("language")) {
          return -1;
        }

        FileEntry fileEntry = null;

        try {
          fileEntry = getFileEntry(pathArray);
        } catch (Exception e) {
        }

        if (fileEntry == null) {
          return -1;
        } else {
          String version = ParamUtil.getString(request, "version");

          if (Validator.isNotNull(version)) {
            FileVersion fileVersion = fileEntry.getFileVersion(version);

            modifiedDate = fileVersion.getModifiedDate();
          } else {
            modifiedDate = fileEntry.getModifiedDate();
          }
        }
      }

      if (modifiedDate == null) {
        modifiedDate = PortalUtil.getUptime();
      }

      // Round down and remove milliseconds

      return (modifiedDate.getTime() / 1000) * 1000;
    } catch (PrincipalException pe) {
      if (_log.isWarnEnabled()) {
        _log.warn(pe, pe);
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return -1;
  }

  protected Image getUserPortraitImageResized(Image image, long imageId)
      throws PortalException, SystemException {

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

    if ((image.getHeight() > PropsValues.USERS_IMAGE_MAX_HEIGHT)
        || (image.getWidth() > PropsValues.USERS_IMAGE_MAX_WIDTH)) {

      User user = UserLocalServiceUtil.getUserByPortraitId(imageId);

      UserLocalServiceUtil.updatePortrait(user.getUserId(), image.getTextObj());

      return ImageLocalServiceUtil.getImage(imageId);
    }

    return image;
  }

  protected boolean isLegacyImageGalleryImageId(
      HttpServletRequest request, HttpServletResponse response) {

    try {
      long imageId = getImageId(request);

      if (imageId == 0) {
        return false;
      }

      DLFileEntry dlFileEntry = DLFileEntryServiceUtil.fetchFileEntryByImageId(imageId);

      if (dlFileEntry == null) {
        return false;
      }

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

      String queryString = StringPool.BLANK;

      if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=1";
      } else if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=2";
      } else if (imageId == dlFileEntry.getSmallImageId()) {
        queryString = "&imageThumbnail=3";
      }

      String url =
          DLUtil.getPreviewURL(
              new LiferayFileEntry(dlFileEntry),
              new LiferayFileVersion(dlFileEntry.getFileVersion()),
              themeDisplay,
              queryString);

      response.setHeader(HttpHeaders.LOCATION, url);
      response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

      return true;
    } catch (Exception e) {
    }

    return false;
  }

  protected void processPrincipalException(
      Throwable t, User user, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (!user.isDefaultUser()) {
      PortalUtil.sendError(HttpServletResponse.SC_UNAUTHORIZED, (Exception) t, request, response);

      return;
    }

    String redirect = request.getContextPath() + Portal.PATH_MAIN + "/portal/login";

    String currentURL = PortalUtil.getCurrentURL(request);

    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);

    response.sendRedirect(redirect);
  }

  protected void sendDDMRecordFile(
      HttpServletRequest request, HttpServletResponse response, String[] pathArray)
      throws Exception {

    if (pathArray.length == 4) {
      String className = GetterUtil.getString(pathArray[1]);
      long classPK = GetterUtil.getLong(pathArray[2]);
      String fieldName = GetterUtil.getString(pathArray[3]);

      Field field = null;

      if (className.equals(DDLRecord.class.getName())) {
        DDLRecord ddlRecord = DDLRecordLocalServiceUtil.getRecord(classPK);

        field = ddlRecord.getField(fieldName);
      } else if (className.equals(DLFileEntryMetadata.class.getName())) {
        DLFileEntryMetadata fileEntryMetadata =
            DLFileEntryMetadataLocalServiceUtil.getDLFileEntryMetadata(classPK);

        Fields fields = StorageEngineUtil.getFields(fileEntryMetadata.getDDMStorageId());

        field = fields.get(fieldName);
      }

      DDMUtil.sendFieldFile(request, response, field);
    }
  }

  protected void sendDocumentLibrary(
      HttpServletRequest request,
      HttpServletResponse response,
      User user,
      String path,
      String[] pathArray)
      throws Exception {

    if (!PropsValues.WEB_SERVER_SERVLET_DIRECTORY_INDEXING_ENABLED) {
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);

      return;
    }

    long groupId = _getGroupId(user.getCompanyId(), pathArray[0]);
    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;

    for (int i = 1; i < pathArray.length; i++) {
      String name = pathArray[i];

      try {
        Folder folder = DLAppServiceUtil.getFolder(groupId, folderId, name);

        folderId = folder.getFolderId();
      } catch (NoSuchFolderException nsfe) {
        if (i != (pathArray.length - 1)) {
          throw nsfe;
        }

        String title = name;

        sendFile(response, user, groupId, folderId, title);

        return;
      }
    }

    try {
      sendFile(response, user, groupId, folderId, "index.html");

      return;
    } catch (Exception e) {
      if ((e instanceof NoSuchFileEntryException) || (e instanceof PrincipalException)) {

        try {
          sendFile(response, user, groupId, folderId, "index.htm");

          return;
        } catch (NoSuchFileEntryException nsfee) {
        } catch (PrincipalException pe) {
        }
      } else {
        throw e;
      }
    }

    List<WebServerEntry> webServerEntries = new ArrayList<WebServerEntry>();

    webServerEntries.add(new WebServerEntry(path, "../"));

    List<Folder> folders = DLAppServiceUtil.getFolders(groupId, folderId);

    for (Folder folder : folders) {
      WebServerEntry webServerEntry =
          new WebServerEntry(
              path,
              folder.getName() + StringPool.SLASH,
              folder.getCreateDate(),
              folder.getModifiedDate(),
              folder.getDescription(),
              0);

      webServerEntries.add(webServerEntry);
    }

    List<FileEntry> fileEntries = DLAppServiceUtil.getFileEntries(groupId, folderId);

    for (FileEntry fileEntry : fileEntries) {
      WebServerEntry webServerEntry =
          new WebServerEntry(
              path,
              fileEntry.getTitle(),
              fileEntry.getCreateDate(),
              fileEntry.getModifiedDate(),
              fileEntry.getDescription(),
              fileEntry.getSize());

      webServerEntries.add(webServerEntry);
    }

    sendHTML(response, path, webServerEntries);
  }

  protected void sendFile(
      HttpServletRequest request, HttpServletResponse response, User user, String[] pathArray)
      throws Exception {

    // Retrieve file details

    FileEntry fileEntry = getFileEntry(pathArray);

    if (fileEntry == null) {
      throw new NoSuchFileEntryException();
    }

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

    if (Validator.isNull(version)) {
      if (Validator.isNotNull(fileEntry.getVersion())) {
        version = fileEntry.getVersion();
      }
    }

    String tempFileId = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    String fileName = fileVersion.getTitle();

    String extension = fileVersion.getExtension();

    if (Validator.isNotNull(extension) && !fileName.endsWith(StringPool.PERIOD + extension)) {

      fileName += StringPool.PERIOD + extension;
    }

    // Handle requested conversion

    boolean converted = false;

    String targetExtension = ParamUtil.getString(request, "targetExtension");
    int imageThumbnail = ParamUtil.getInteger(request, "imageThumbnail");
    int documentThumbnail = ParamUtil.getInteger(request, "documentThumbnail");
    int previewFileIndex = ParamUtil.getInteger(request, "previewFileIndex");
    boolean audioPreview = ParamUtil.getBoolean(request, "audioPreview");
    boolean imagePreview = ParamUtil.getBoolean(request, "imagePreview");
    boolean videoPreview = ParamUtil.getBoolean(request, "videoPreview");
    int videoThumbnail = ParamUtil.getInteger(request, "videoThumbnail");

    InputStream inputStream = null;
    long contentLength = 0;

    if ((imageThumbnail > 0) && (imageThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(ImageProcessorUtil.getThumbnailType(fileVersion));

      int thumbnailIndex = imageThumbnail - 1;

      inputStream = ImageProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = ImageProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if ((documentThumbnail > 0) && (documentThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = documentThumbnail - 1;

      inputStream = PDFProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = PDFProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if (previewFileIndex > 0) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.PREVIEW_TYPE);
      inputStream = PDFProcessorUtil.getPreviewAsStream(fileVersion, previewFileIndex);
      contentLength = PDFProcessorUtil.getPreviewFileSize(fileVersion, previewFileIndex);

      converted = true;
    } else if (audioPreview || videoPreview) {
      String type = ParamUtil.getString(request, "type");

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      if (audioPreview) {
        inputStream = AudioProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = AudioProcessorUtil.getPreviewFileSize(fileVersion, type);
      } else {
        inputStream = VideoProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = VideoProcessorUtil.getPreviewFileSize(fileVersion, type);
      }

      converted = true;
    } else if (imagePreview) {
      String type = ImageProcessorUtil.getPreviewType(fileVersion);

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      inputStream = ImageProcessorUtil.getPreviewAsStream(fileVersion);

      contentLength = ImageProcessorUtil.getPreviewFileSize(fileVersion);

      converted = true;
    } else if ((videoThumbnail > 0) && (videoThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(VideoProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = videoThumbnail - 1;

      inputStream = VideoProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = VideoProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else {
      inputStream = fileVersion.getContentStream(true);
      contentLength = fileVersion.getSize();

      if (Validator.isNotNull(targetExtension)) {
        File convertedFile =
            DocumentConversionUtil.convert(tempFileId, inputStream, extension, targetExtension);

        if (convertedFile != null) {
          fileName =
              FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
          inputStream = new FileInputStream(convertedFile);
          contentLength = convertedFile.length();

          converted = true;
        }
      }
    }

    // Determine proper content type

    String contentType = null;

    if (converted) {
      contentType = MimeTypesUtil.getContentType(fileName);
    } else {
      contentType = fileVersion.getMimeType();
    }

    // Support range HTTP header

    response.setHeader(HttpHeaders.ACCEPT_RANGES, HttpHeaders.ACCEPT_RANGES_BYTES_VALUE);

    List<Range> ranges = null;

    try {
      ranges = ServletResponseUtil.getRanges(request, response, contentLength);
    } catch (IOException ioe) {
      if (_log.isErrorEnabled()) {
        _log.error(ioe);
      }

      response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + contentLength);

      response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);

      return;
    }

    if ((ranges == null) || ranges.isEmpty()) {
      ServletResponseUtil.sendFile(
          request, response, fileName, inputStream, contentLength, contentType);
    } else {
      if (_log.isDebugEnabled()) {
        _log.debug("Request has range header " + request.getHeader(HttpHeaders.RANGE));
      }

      ServletResponseUtil.write(
          request, response, fileName, ranges, inputStream, contentLength, contentType);
    }
  }

  protected void sendFile(
      HttpServletResponse response, User user, long groupId, long folderId, String title)
      throws Exception {

    FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, title);

    String contentType = fileEntry.getMimeType();

    response.setContentType(contentType);

    InputStream inputStream = fileEntry.getContentStream();

    ServletResponseUtil.write(response, inputStream);
  }

  protected void sendGroups(HttpServletResponse response, User user, String path) throws Exception {

    if (!PropsValues.WEB_SERVER_SERVLET_DIRECTORY_INDEXING_ENABLED) {
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);

      return;
    }

    List<WebServerEntry> webServerEntries = new ArrayList<WebServerEntry>();

    List<Group> groups = WebDAVUtil.getGroups(user);

    for (Group group : groups) {
      String name = HttpUtil.fixPath(group.getFriendlyURL());

      WebServerEntry webServerEntry =
          new WebServerEntry(path, name + StringPool.SLASH, null, null, group.getDescription(), 0);

      webServerEntries.add(webServerEntry);
    }

    sendHTML(response, path, webServerEntries);
  }

  protected void sendHTML(
      HttpServletResponse response, String path, List<WebServerEntry> webServerEntries)
      throws Exception {

    Template template =
        TemplateManagerUtil.getTemplate(
            TemplateManager.FREEMARKER, _TEMPLATE_FTL, TemplateContextType.RESTRICTED);

    template.put("dateFormat", _dateFormat);
    template.put("entries", webServerEntries);
    template.put("path", HttpUtil.encodePath(path));

    if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_DEFAULT) {
    } else if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_PARTIAL) {
      template.put("releaseInfo", ReleaseInfo.getName());
    } else {
      template.put("releaseInfo", ReleaseInfo.getReleaseInfo());
    }

    template.put("validator", Validator_IW.getInstance());

    response.setContentType(ContentTypes.TEXT_HTML_UTF8);

    template.processTemplate(response.getWriter());
  }

  protected void writeImage(Image image, HttpServletRequest request, HttpServletResponse response) {

    if (image == null) {
      return;
    }

    String contentType = null;

    String type = image.getType();

    if (!type.equals(ImageConstants.TYPE_NOT_AVAILABLE)) {
      contentType = MimeTypesUtil.getContentType("A." + type);

      response.setContentType(contentType);
    }

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

    try {
      byte[] bytes = getImageBytes(request, image);

      if (Validator.isNotNull(fileName)) {
        ServletResponseUtil.sendFile(request, response, fileName, bytes, contentType);
      } else {
        ServletResponseUtil.write(response, bytes);
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }
  }

  private static void _checkDDMRecord(String[] pathArray) throws Exception {
    if (pathArray.length == 3) {
      String className = GetterUtil.getString(pathArray[1]);
      long classPK = GetterUtil.getLong(pathArray[2]);

      if (className.equals(DDLRecord.class.getName())) {
        DDLRecordLocalServiceUtil.getRecord(classPK);
      } else if (className.equals(DLFileEntryMetadata.class.getName())) {
        DLFileEntryMetadataLocalServiceUtil.getDLFileEntryMetadata(classPK);
      }
    }
  }

  private static void _checkFileEntry(String[] pathArray) throws Exception {
    if (pathArray.length == 1) {
      long dlFileShortcutId = GetterUtil.getLong(pathArray[0]);

      DLFileShortcut dlFileShortcut = DLAppLocalServiceUtil.getFileShortcut(dlFileShortcutId);

      DLAppLocalServiceUtil.getFileEntry(dlFileShortcut.getToFileEntryId());
    } else if (pathArray.length == 2) {

      // Unable to check with UUID because of multiple repositories

    } else if (pathArray.length == 3) {
      long groupId = GetterUtil.getLong(pathArray[0]);
      long folderId = GetterUtil.getLong(pathArray[1]);
      String fileName = pathArray[2];

      try {
        DLAppLocalServiceUtil.getFileEntry(groupId, folderId, fileName);
      } catch (RepositoryException re) {
      }
    } else {
      long groupId = GetterUtil.getLong(pathArray[0]);

      String uuid = pathArray[3];

      try {
        DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);
      } catch (RepositoryException re) {
      }
    }
  }

  private static long _getGroupId(long companyId, String name) throws Exception {

    try {
      Group group = GroupLocalServiceUtil.getFriendlyURLGroup(companyId, StringPool.SLASH + name);

      return group.getGroupId();
    } catch (NoSuchGroupException nsge) {
    }

    User user = UserLocalServiceUtil.getUserByScreenName(companyId, name);

    Group group = user.getGroup();

    return group.getGroupId();
  }

  private static User _getUser(HttpServletRequest request) throws Exception {
    HttpSession session = request.getSession();

    if (PortalSessionThreadLocal.getHttpSession() == null) {
      PortalSessionThreadLocal.setHttpSession(session);
    }

    User user = PortalUtil.getUser(request);

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

    String userIdString = (String) session.getAttribute("j_username");
    String password = (String) session.getAttribute("j_password");

    if ((userIdString != null) && (password != null)) {
      long userId = GetterUtil.getLong(userIdString);

      user = UserLocalServiceUtil.getUser(userId);
    } else {
      long companyId = PortalUtil.getCompanyId(request);

      Company company = CompanyLocalServiceUtil.getCompany(companyId);

      user = company.getDefaultUser();
    }

    return user;
  }

  private static final String _DATE_FORMAT_PATTERN = "d MMM yyyy HH:mm z";

  private static final String _PATH_DDM = "ddm";

  private static final String _TEMPLATE_FTL =
      "com/liferay/portal/webserver/dependencies/template.ftl";

  private static final boolean _WEB_SERVER_SERVLET_VERSION_VERBOSITY_DEFAULT =
      PropsValues.WEB_SERVER_SERVLET_VERSION_VERBOSITY.equalsIgnoreCase(ReleaseInfo.getName());

  private static final boolean _WEB_SERVER_SERVLET_VERSION_VERBOSITY_PARTIAL =
      PropsValues.WEB_SERVER_SERVLET_VERSION_VERBOSITY.equalsIgnoreCase("partial");

  private static Log _log = LogFactoryUtil.getLog(WebServerServlet.class);

  private static Format _dateFormat =
      FastDateFormatFactoryUtil.getSimpleDateFormat(_DATE_FORMAT_PATTERN);

  private boolean _lastModified = true;
}
示例#23
0
  public void importPortletInfo(
      long userId,
      long plid,
      long groupId,
      String portletId,
      Map<String, String[]> parameterMap,
      File file)
      throws Exception {

    boolean deletePortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importPortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    boolean importPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean importPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean importPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    String userIdStrategyString =
        MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    User user = UserUtil.findByPrimaryKey(userId);

    UserIdStrategy userIdStrategy = getUserIdStrategy(user, userIdStrategyString);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            layout.getCompanyId(),
            groupId,
            parameterMap,
            new HashSet<String>(),
            userIdStrategy,
            zipReader);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPlid(plid);
    portletDataContext.setPrivateLayout(layout.isPrivateLayout());

    // Manifest

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    Element rootElement = null;

    try {
      Document document = SAXReaderUtil.read(xml);

      rootElement = document.getRootElement();
    } catch (Exception e) {
      throw new LARFileException("Unable to read /manifest.xml");
    }

    // Build compatibility

    Element headerElement = rootElement.element("header");

    int buildNumber = ReleaseInfo.getBuildNumber();

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type compatibility

    String type = headerElement.attributeValue("type");

    if (!type.equals("portlet")) {
      throw new LARTypeException("Invalid type of LAR file (" + type + ")");
    }

    // Portlet compatibility

    String rootPortletId = headerElement.attributeValue("root-portlet-id");

    if (!PortletConstants.getRootPortletId(portletId).equals(rootPortletId)) {

      throw new PortletIdException("Invalid portlet id " + rootPortletId);
    }

    // Import group id

    long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

    portletDataContext.setSourceGroupId(sourceGroupId);

    // Read asset categories, asset tags, comments, locks, and ratings
    // entries to make them available to the data handlers through the
    // context

    if (importPermissions) {
      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    readAssetCategories(portletDataContext);
    readAssetTags(portletDataContext);
    readComments(portletDataContext);
    readExpandoTables(portletDataContext);
    readLocks(portletDataContext);
    readRatingsEntries(portletDataContext);

    // Delete portlet data

    if (_log.isDebugEnabled()) {
      _log.debug("Deleting portlet data");
    }

    if (deletePortletData) {
      deletePortletData(portletDataContext, portletId, plid);
    }

    Element portletElement = null;

    try {
      portletElement = rootElement.element("portlet");

      Document portletDocument =
          SAXReaderUtil.read(
              portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

      portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
      throw new SystemException(de);
    }

    setPortletScope(portletDataContext, portletElement);

    try {

      // Portlet preferences

      importPortletPreferences(
          portletDataContext,
          layout.getCompanyId(),
          groupId,
          layout,
          portletId,
          portletElement,
          importPortletSetup,
          importPortletArchivedSetups,
          importPortletUserPreferences,
          true);

      // Portlet data

      Element portletDataElement = portletElement.element("portlet-data");

      if (importPortletData && (portletDataElement != null)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Importing portlet data");
        }

        importPortletData(portletDataContext, portletId, plid, portletDataElement);
      }
    } finally {
      resetPortletScope(portletDataContext, groupId);
    }

    // Portlet permissions

    if (importPermissions) {
      if (_log.isDebugEnabled()) {
        _log.debug("Importing portlet permissions");
      }

      LayoutCache layoutCache = new LayoutCache();

      _permissionImporter.importPortletPermissions(
          layoutCache,
          layout.getCompanyId(),
          groupId,
          userId,
          layout,
          portletElement,
          portletId,
          importUserPermissions);
    }

    // Asset links

    if (_log.isDebugEnabled()) {
      _log.debug("Importing asset links");
    }

    readAssetLinks(portletDataContext);

    if (_log.isInfoEnabled()) {
      _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
    }

    zipReader.close();
  }
  @AccessControlled(guestAccessEnabled = true)
  @Override
  public SyncContext getSyncContext() throws PortalException {
    try {
      User user = getGuestOrUser();

      SyncContext syncContext = new SyncContext();

      String authType =
          PrefsPropsUtil.getString(
              CompanyThreadLocal.getCompanyId(),
              PropsKeys.COMPANY_SECURITY_AUTH_TYPE,
              PropsUtil.get(PropsKeys.COMPANY_SECURITY_AUTH_TYPE));

      syncContext.setAuthType(authType);

      boolean oAuthEnabled =
          PrefsPropsUtil.getBoolean(
              user.getCompanyId(),
              PortletPropsKeys.SYNC_OAUTH_ENABLED,
              PortletPropsValues.SYNC_OAUTH_ENABLED);

      if (oAuthEnabled) {
        String oAuthConsumerKey =
            PrefsPropsUtil.getString(user.getCompanyId(), PortletPropsKeys.SYNC_OAUTH_CONSUMER_KEY);

        syncContext.setOAuthConsumerKey(oAuthConsumerKey);

        String oAuthConsumerSecret =
            PrefsPropsUtil.getString(
                user.getCompanyId(), PortletPropsKeys.SYNC_OAUTH_CONSUMER_SECRET);

        syncContext.setOAuthConsumerSecret(oAuthConsumerSecret);
      }

      syncContext.setOAuthEnabled(oAuthEnabled);

      PluginPackage syncWebPluginPackage = DeployManagerUtil.getInstalledPluginPackage("sync-web");

      syncContext.setPluginVersion(syncWebPluginPackage.getVersion());

      if (!user.isDefaultUser()) {
        syncContext.setPortalBuildNumber(ReleaseInfo.getBuildNumber());

        PluginPackage soPortletPluginPackage =
            DeployManagerUtil.getInstalledPluginPackage("so-portlet");

        syncContext.setPortletPreferencesMap(getPortletPreferencesMap());

        if (soPortletPluginPackage != null) {
          syncContext.setSocialOfficeInstalled(true);
        } else {
          syncContext.setSocialOfficeInstalled(false);
        }

        syncContext.setUser(user);
        syncContext.setUserSitesGroups(getUserSitesGroups());
      }

      return syncContext;
    } catch (PortalException pe) {
      throw new PortalException(SyncUtil.buildExceptionMessage(pe), pe);
    }
  }
/** @author Michael C. Han */
public class XMLDefinitionExporter implements DefinitionExporter {

  public void afterPropertiesSet() {
    _namespace = "urn:liferay.com:liferay-workflow_" + _version;
    _schemaVersion = StringUtil.replace(_version, StringPool.PERIOD, StringPool.UNDERLINE);
  }

  @Override
  public String export(long kaleoDefinitionId) throws PortalException {
    Definition definition = _definitionBuilder.buildDefinition(kaleoDefinitionId);

    return doExport(definition);
  }

  @Override
  public String export(long companyId, String name, int version) throws PortalException {

    Definition definition = _definitionBuilder.buildDefinition(companyId, name, version);

    return doExport(definition);
  }

  public void setDefinitionBuilder(DefinitionBuilder definitionBuilder) {
    _definitionBuilder = definitionBuilder;
  }

  public void setVersion(String version) {
    _version = version;
  }

  protected String doExport(Definition definition) {
    try {
      Document document = SAXReaderUtil.createDocument();

      Element workflowDefinitionElement = document.addElement("workflow-definition");

      workflowDefinitionElement.addAttribute(
          "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
      workflowDefinitionElement.addAttribute(
          "xsi:schemaLocation",
          "urn:liferay.com:liferay-workflow_"
              + _version
              + " http://www.liferay.com/dtd/liferay-workflow-definition_"
              + _schemaVersion
              + ".xsd");
      workflowDefinitionElement.addNamespace("", "urn:liferay.com:liferay-workflow_" + _version);

      Element nameElement = workflowDefinitionElement.addElement("name", _namespace);

      nameElement.addText(definition.getName());

      if (Validator.isNotNull(definition.getDescription())) {
        Element descriptionElement =
            workflowDefinitionElement.addElement("description", _namespace);

        descriptionElement.addText(definition.getDescription());
      }

      Element versionElement = workflowDefinitionElement.addElement("version", _namespace);

      versionElement.addText(String.valueOf(definition.getVersion()));

      Collection<Node> nodes = definition.getNodes();

      for (Node node : nodes) {
        NodeExporter nodeExporter = NodeExporterRegistry.getNodeExporter(node.getNodeType());

        nodeExporter.exportNode(node, workflowDefinitionElement, _namespace);
      }

      return document.formattedString();
    } catch (IOException ioe) {
      throw new SystemException("Unable to export definition", ioe);
    }
  }

  private DefinitionBuilder _definitionBuilder;
  private String _namespace;
  private String _schemaVersion;
  private String _version = ReleaseInfo.getVersion();
}
  protected File doExport(PortletDataContext portletDataContext) throws Exception {

    boolean exportPermissions =
        MapUtil.getBoolean(
            portletDataContext.getParameterMap(), PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + exportPermissions);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    if (!layout.isTypeControlPanel() && !layout.isTypePanel() && !layout.isTypePortlet()) {

      throw new LayoutImportException("Layout type " + layout.getType() + " is not valid");
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(layout.getCompanyId());
      serviceContext.setSignedIn(false);

      long defaultUserId = _userLocalService.getDefaultUserId(layout.getCompanyId());

      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    long layoutSetBranchId =
        MapUtil.getLong(portletDataContext.getParameterMap(), "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long scopeGroupId = portletDataContext.getGroupId();

    javax.portlet.PortletPreferences jxPortletPreferences =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(
            layout, portletDataContext.getPortletId());

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

    if (Validator.isNotNull(scopeType)) {
      Group scopeGroup = null;

      if (scopeType.equals("company")) {
        scopeGroup = _groupLocalService.getCompanyGroup(layout.getCompanyId());
      } else if (Validator.isNotNull(scopeLayoutUuid)) {
        scopeGroup = layout.getScopeGroup();
      }

      if (scopeGroup != null) {
        scopeGroupId = scopeGroup.getGroupId();
      }
    }

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

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute(
        "available-locales",
        StringUtil.merge(
            LanguageUtil.getAvailableLocales(
                PortalUtil.getSiteGroupId(portletDataContext.getScopeGroupId()))));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("type", "portlet");
    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute(
        "company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", portletDataContext.getRootPortletId());

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    Map<String, Boolean> exportPortletControlsMap =
        ExportImportHelperUtil.getExportPortletControlsMap(
            layout.getCompanyId(),
            portletDataContext.getPortletId(),
            portletDataContext.getParameterMap());

    exportPortlet(
        portletDataContext,
        layout,
        rootElement,
        exportPermissions,
        exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
        exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
        exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
        exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
    exportService(
        portletDataContext,
        rootElement,
        exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

    exportAssetLinks(portletDataContext);
    exportExpandoTables(portletDataContext);
    exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    ExportImportHelperUtil.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
      _log.info("Exporting portlet took " + stopWatch.getTime() + " ms");
    }

    try {
      portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
  }
  private Map<String, String> _buildFrameworkProperties(Class<?> clazz) {
    Map<String, String> properties = new HashMap<String, String>();

    properties.put(Constants.BUNDLE_DESCRIPTION, ReleaseInfo.getReleaseInfo());
    properties.put(Constants.BUNDLE_NAME, ReleaseInfo.getName());
    properties.put(Constants.BUNDLE_VENDOR, ReleaseInfo.getVendor());
    properties.put(Constants.BUNDLE_VERSION, ReleaseInfo.getVersion());
    properties.put(FrameworkPropsKeys.FELIX_FILEINSTALL_DIR, _getFelixFileInstallDir());
    properties.put(FrameworkPropsKeys.FELIX_FILEINSTALL_LOG_LEVEL, _getFelixFileInstallLogLevel());
    properties.put(
        FrameworkPropsKeys.FELIX_FILEINSTALL_POLL,
        String.valueOf(PropsValues.MODULE_FRAMEWORK_AUTO_DEPLOY_INTERVAL));
    properties.put(
        FrameworkPropsKeys.FELIX_FILEINSTALL_TMPDIR,
        SystemProperties.get(SystemProperties.TMP_DIR));
    properties.put(
        Constants.FRAMEWORK_BEGINNING_STARTLEVEL,
        String.valueOf(PropsValues.MODULE_FRAMEWORK_BEGINNING_START_LEVEL));
    properties.put(Constants.FRAMEWORK_BUNDLE_PARENT, Constants.FRAMEWORK_BUNDLE_PARENT_APP);
    properties.put(Constants.FRAMEWORK_STORAGE, PropsValues.MODULE_FRAMEWORK_STATE_DIR);

    properties.put("eclipse.security", null);
    properties.put("java.security.manager", null);
    properties.put("org.osgi.framework.security", null);

    ProtectionDomain protectionDomain = clazz.getProtectionDomain();

    CodeSource codeSource = protectionDomain.getCodeSource();

    URL codeSourceURL = codeSource.getLocation();

    properties.put(FrameworkPropsKeys.OSGI_FRAMEWORK, codeSourceURL.toExternalForm());

    File frameworkFile = new File(codeSourceURL.getFile());

    properties.put(FrameworkPropsKeys.OSGI_INSTALL_AREA, frameworkFile.getParent());

    Properties extraProperties =
        PropsUtil.getProperties(PropsKeys.MODULE_FRAMEWORK_PROPERTIES, true);

    for (Map.Entry<Object, Object> entry : extraProperties.entrySet()) {
      String key = (String) entry.getKey();
      String value = (String) entry.getValue();

      // We need to support an empty string and a null value distinctly.
      // This is due to some different behaviors between OSGi
      // implementations. If a property is passed as xyz= it will be
      // treated as an empty string. Otherwise, xyz=null will be treated
      // as an explicit null value.

      if (value.equals(StringPool.NULL)) {
        value = null;
      }

      properties.put(key, value);
    }

    String systemPackagesExtra = _getSystemPackagesExtra();

    properties.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, systemPackagesExtra);

    return properties;
  }
  protected File doExport(PortletDataContext portletDataContext, long[] layoutIds)
      throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean ignoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean layoutSetPrototypeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS);
    boolean layoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean logo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + permissions);
    }

    LayoutSet layoutSet =
        _layoutSetLocalService.getLayoutSet(
            portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = _userLocalService.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();
    }

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(false);
    serviceContext.setUserId(defaultUserId);

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    if (ignoreLastPublishDate) {
      portletDataContext.setEndDate(null);
      portletDataContext.setStartDate(null);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute(
        "available-locales",
        StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute(
        "company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(portletDataContext.getGroupId()));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute(
        "private-layout", String.valueOf(portletDataContext.isPrivateLayout()));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
      type = "layout-prototype";

      LayoutPrototype layoutPrototype =
          _layoutPrototypeLocalService.getLayoutPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());

      layoutIds =
          ExportImportHelperUtil.getAllLayoutIds(
              portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          _layoutSetPrototypeLocalService.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    LayoutSetBranch layoutSetBranch =
        _layoutSetBranchLocalService.fetchLayoutSetBranch(layoutSetBranchId);

    if (logo) {
      Image image = null;

      if (layoutSetBranch != null) {
        image = _imageLocalService.getImage(layoutSetBranch.getLogoId());
      } else {
        image = _imageLocalService.getImage(layoutSet.getLogoId());
      }

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (layoutSetPrototypeSettings && Validator.isNotNull(layoutSetPrototypeUuid)) {

      LayoutSetPrototype layoutSetPrototype =
          _layoutSetPrototypeLocalService.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

      headerElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);
      headerElement.addAttribute(
          "layout-set-prototype-name", layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    if (layoutSetBranch != null) {
      _themeExporter.exportTheme(portletDataContext, layoutSetBranch);
    } else {
      _themeExporter.exportTheme(portletDataContext, layoutSet);
    }

    if (layoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      if (layoutSetBranch != null) {
        settingsElement.addCDATA(layoutSetBranch.getSettings());
      } else {
        settingsElement.addCDATA(layoutSet.getSettings());
      }
    }

    Map<String, Object[]> portletIds = new LinkedHashMap<>();

    List<Layout> layouts =
        _layoutLocalService.getLayouts(
            portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    // Collect data portlets

    for (Portlet portlet : ExportImportHelperUtil.getDataSiteLevelPortlets(companyId)) {

      String portletId = portlet.getRootPortletId();

      if (ExportImportThreadLocal.isStagingInProcess() && !group.isStagedPortlet(portletId)) {

        continue;
      }

      // Calculate the amount of exported data

      if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

        portletDataHandler.prepareManifestSummary(portletDataContext);
      }

      // Add portlet ID to exportable portlets list

      portletIds.put(
          PortletPermissionUtil.getPrimaryKey(0, portletId),
          new Object[] {
            portletId,
            LayoutConstants.DEFAULT_PLID,
            portletDataContext.getGroupId(),
            StringPool.BLANK,
            StringPool.BLANK
          });

      if (!portlet.isScopeable()) {
        continue;
      }

      // Scoped data

      for (Layout layout : layouts) {
        if (!ArrayUtil.contains(layoutIds, layout.getLayoutId())
            || !layout.isTypePortlet()
            || !layout.hasScopeGroup()) {

          continue;
        }

        Group scopeGroup = layout.getScopeGroup();

        portletIds.put(
            PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId()),
            new Object[] {
              portlet.getPortletId(),
              layout.getPlid(),
              scopeGroup.getGroupId(),
              StringPool.BLANK,
              layout.getUuid()
            });
      }
    }

    // Collect layout portlets

    for (Layout layout : layouts) {
      getLayoutPortlets(portletDataContext, layoutIds, portletIds, layout);
    }

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "layout", ArrayUtil.toStringArray(portletIds.keySet()), manifestSummary);

      manifestSummary.resetCounters();
    }

    // Export actual data

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(Layout.class));

    // Force to always have a layout group element

    portletDataContext.getExportDataGroupElement(Layout.class);

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, layoutIds, layout);
    }

    Element portletsElement = rootElement.addElement("portlets");

    Element servicesElement = rootElement.addElement("services");

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = _layoutLocalService.fetchLayout(plid);

      if (layout == null) {
        layout = new LayoutImpl();

        layout.setCompanyId(companyId);
        layout.setGroupId(portletDataContext.getGroupId());
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setPortletId(portletId);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      Map<String, Boolean> exportPortletControlsMap =
          ExportImportHelperUtil.getExportPortletControlsMap(
              companyId, portletId, parameterMap, type);

      try {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_STARTED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));

        _portletExportController.exportPortlet(
            portletDataContext,
            layout,
            portletsElement,
            permissions,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
        _portletExportController.exportService(
            portletDataContext,
            servicesElement,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_SUCCEEDED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));
      } catch (Throwable t) {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_FAILED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext),
            t);

        throw t;
      }
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    _portletExportController.exportAssetLinks(portletDataContext);
    _portletExportController.exportExpandoTables(portletDataContext);
    _portletExportController.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (permissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    ExportImportHelperUtil.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
      _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
    }

    boolean updateLastPublishDate =
        MapUtil.getBoolean(
            portletDataContext.getParameterMap(), PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (ExportImportThreadLocal.isStagingInProcess() && updateLastPublishDate) {

      ExportImportProcessCallbackRegistryUtil.registerCallback(
          new UpdateLayoutSetLastPublishDateCallable(
              portletDataContext.getDateRange(),
              portletDataContext.getGroupId(),
              portletDataContext.isPrivateLayout()));
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
  }
  protected void validateFile(long companyId, long groupId, String portletId, ZipReader zipReader)
      throws Exception {

    // XML

    String xml = zipReader.getEntryAsString("/manifest.xml");

    if (xml == null) {
      throw new LARFileException("manifest.xml not found in the LAR");
    }

    Element rootElement = null;

    try {
      Document document = SAXReaderUtil.read(xml);

      rootElement = document.getRootElement();
    } catch (Exception e) {
      throw new LARFileException(e);
    }

    // Build compatibility

    int buildNumber = ReleaseInfo.getBuildNumber();

    Element headerElement = rootElement.element("header");

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type

    String larType = headerElement.attributeValue("type");

    if (!larType.equals("portlet")) {
      throw new LARTypeException(larType);
    }

    // Portlet compatibility

    String rootPortletId = headerElement.attributeValue("root-portlet-id");

    if (!PortletConstants.getRootPortletId(portletId).equals(rootPortletId)) {

      throw new PortletIdException("Invalid portlet id " + rootPortletId);
    }

    // Available locales

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

    PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

    if (portletDataHandler.isDataLocalized()) {
      List<Locale> sourceAvailableLocales =
          Arrays.asList(
              LocaleUtil.fromLanguageIds(
                  StringUtil.split(headerElement.attributeValue("available-locales"))));

      for (Locale sourceAvailableLocale : sourceAvailableLocales) {
        if (!LanguageUtil.isAvailableLocale(
            PortalUtil.getSiteGroupId(groupId), sourceAvailableLocale)) {

          LocaleException le =
              new LocaleException(
                  LocaleException.TYPE_EXPORT_IMPORT,
                  "Locale "
                      + sourceAvailableLocale
                      + " is not "
                      + "available in company "
                      + companyId);

          le.setSourceAvailableLocales(sourceAvailableLocales);
          le.setTargetAvailableLocales(
              LanguageUtil.getAvailableLocales(PortalUtil.getSiteGroupId(groupId)));

          throw le;
        }
      }
    }
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        PortletDataContextFactoryUtil.createExportPortletDataContext(
            companyId, groupId, parameterMap, startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute(
        "available-locales",
        StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute(
        "company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
      type = "layout-prototype";

      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);

    List<Portlet> portlets = getDataSiteLevelPortlets(companyId);

    long plid = LayoutConstants.DEFAULT_PLID;

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      plid = firstLayout.getPlid();
    }

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    for (Portlet portlet : portlets) {
      String portletId = portlet.getRootPortletId();

      if (!group.isStagedPortlet(portletId)) {
        continue;
      }

      String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

      if (portletIds.get(key) == null) {
        portletIds.put(
            key, new Object[] {portletId, plid, groupId, StringPool.BLANK, StringPool.BLANK});
      }
    }

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(Layout.class));

    Element layoutsElement = portletDataContext.getExportDataGroupElement(Layout.class);

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      layoutsElement.addAttribute(
          "layout-set-prototype-name", layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, portlets, layoutIds, portletIds, layout);
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.fetchLayout(plid);

      if (layout == null) {
        if (!group.isCompany() && (plid <= LayoutConstants.DEFAULT_PLID)) {

          continue;
        }

        if (_log.isWarnEnabled()) {
          _log.warn("Assuming global scope because no layout was found");
        }

        layout = new LayoutImpl();

        layout.setGroupId(groupId);
        layout.setCompanyId(companyId);
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, parameterMap, type);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletControls[2],
          exportPortletControls[3]);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    exportAssetCategories(
        portletDataContext, exportPortletDataAll, exportCategories, group.isCompany());

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    ExportImportHelperUtil.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }